blob: a9cbbc390d795edf1f41fa53b47fb2d29409d4bb [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 Lorenzab980492015-07-20 20:51:18 +000023#include "llvm/CodeGen/MachineConstantPool.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000024#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenz60541c12015-07-09 19:55:27 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz78d78312015-05-28 22:41:12 +000027#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000028#include "llvm/IR/BasicBlock.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000029#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000030#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000031#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000032#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000033#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000034#include "llvm/Support/LineIterator.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000035#include "llvm/Support/SMLoc.h"
36#include "llvm/Support/SourceMgr.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/YAMLTraits.h"
39#include <memory>
40
41using namespace llvm;
42
Alex Lorenz735c47e2015-06-15 20:30:22 +000043namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000044
45/// This class implements the parsing of LLVM IR that's embedded inside a MIR
46/// file.
47class MIRParserImpl {
48 SourceMgr SM;
49 StringRef Filename;
50 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000051 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000052 SlotMapping IRSlots;
Alex Lorenz28148ba2015-07-09 22:23:13 +000053 /// Maps from register class names to register classes.
54 StringMap<const TargetRegisterClass *> Names2RegClasses;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000055
56public:
57 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58 LLVMContext &Context);
59
Alex Lorenz735c47e2015-06-15 20:30:22 +000060 void reportDiagnostic(const SMDiagnostic &Diag);
61
62 /// Report an error with the given message at unknown location.
63 ///
64 /// Always returns true.
65 bool error(const Twine &Message);
66
Alex Lorenzb1f9ce82015-07-08 20:22:20 +000067 /// Report an error with the given message at the given location.
68 ///
69 /// Always returns true.
70 bool error(SMLoc Loc, const Twine &Message);
71
Alex Lorenz0fd7c622015-06-30 17:55:00 +000072 /// Report a given error with the location translated from the location in an
73 /// embedded string literal to a location in the MIR file.
74 ///
75 /// Always returns true.
76 bool error(const SMDiagnostic &Error, SMRange SourceRange);
77
Alex Lorenz78d78312015-05-28 22:41:12 +000078 /// Try to parse the optional LLVM module and the machine functions in the MIR
79 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000080 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000081 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000082 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000083
84 /// Parse the machine function in the current YAML document.
85 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000086 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
87 /// A dummy IR function is created and inserted into the given module when
88 /// this parameter is true.
89 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000090 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000091 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000092
Alex Lorenz735c47e2015-06-15 20:30:22 +000093 /// Initialize the machine function to the state that's described in the MIR
94 /// file.
95 ///
96 /// Return true if error occurred.
97 bool initializeMachineFunction(MachineFunction &MF);
98
Alex Lorenz4f093bf2015-06-19 17:43:07 +000099 /// Initialize the machine basic block using it's YAML representation.
100 ///
101 /// Return true if an error occurred.
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000102 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
103 const yaml::MachineBasicBlock &YamlMBB,
104 const PerFunctionMIParsingState &PFS);
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000105
Alex Lorenzdb07c402015-07-28 16:48:37 +0000106 bool initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000107 const yaml::MachineFunction &YamlMF,
108 PerFunctionMIParsingState &PFS);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000109
Alex Lorenzc4838082015-08-11 00:32:49 +0000110 void inferRegisterInfo(MachineFunction &MF,
111 const yaml::MachineFunction &YamlMF);
112
Alex Lorenzdb07c402015-07-28 16:48:37 +0000113 bool initializeFrameInfo(MachineFunction &MF,
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000114 const yaml::MachineFunction &YamlMF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000115 PerFunctionMIParsingState &PFS);
116
117 bool parseCalleeSavedRegister(MachineFunction &MF,
118 PerFunctionMIParsingState &PFS,
119 std::vector<CalleeSavedInfo> &CSIInfo,
120 const yaml::StringValue &RegisterSource,
121 int FrameIdx);
Alex Lorenz60541c12015-07-09 19:55:27 +0000122
Alex Lorenzab980492015-07-20 20:51:18 +0000123 bool initializeConstantPool(MachineConstantPool &ConstantPool,
124 const yaml::MachineFunction &YamlMF,
125 const MachineFunction &MF,
126 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
127
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000128 bool initializeJumpTableInfo(MachineFunction &MF,
129 const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000130 PerFunctionMIParsingState &PFS);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000131
Alex Lorenz09b832c2015-05-29 17:05:41 +0000132private:
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000133 bool parseMBBReference(MachineBasicBlock *&MBB,
134 const yaml::StringValue &Source, MachineFunction &MF,
135 const PerFunctionMIParsingState &PFS);
136
Alex Lorenz51af1602015-06-23 22:39:23 +0000137 /// Return a MIR diagnostic converted from an MI string diagnostic.
138 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
139 SMRange SourceRange);
140
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000141 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
142 /// block scalar string.
143 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
144 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000145
146 /// Create an empty function with the given name.
147 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000148
149 void initNames2RegClasses(const MachineFunction &MF);
150
151 /// Check if the given identifier is a name of a register class.
152 ///
153 /// Return null if the name isn't a register class.
154 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
155 StringRef Name);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000156};
157
Alex Lorenz735c47e2015-06-15 20:30:22 +0000158} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000159
160MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
161 StringRef Filename, LLVMContext &Context)
162 : SM(), Filename(Filename), Context(Context) {
163 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
164}
165
Alex Lorenz735c47e2015-06-15 20:30:22 +0000166bool MIRParserImpl::error(const Twine &Message) {
167 Context.diagnose(DiagnosticInfoMIRParser(
168 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
169 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000170}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000171
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000172bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
173 Context.diagnose(DiagnosticInfoMIRParser(
174 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
175 return true;
176}
177
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000178bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
179 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
180 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
181 return true;
182}
183
Alex Lorenz735c47e2015-06-15 20:30:22 +0000184void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
185 DiagnosticSeverity Kind;
186 switch (Diag.getKind()) {
187 case SourceMgr::DK_Error:
188 Kind = DS_Error;
189 break;
190 case SourceMgr::DK_Warning:
191 Kind = DS_Warning;
192 break;
193 case SourceMgr::DK_Note:
194 Kind = DS_Note;
195 break;
196 }
197 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
198}
199
200static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
201 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
202}
203
204std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000205 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000206 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000207 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000208
209 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000210 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000211 return nullptr;
212 // Create an empty module when the MIR file is empty.
213 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000214 }
215
Alex Lorenz78d78312015-05-28 22:41:12 +0000216 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000217 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000218 // Parse the block scalar manually so that we can return unique pointer
219 // without having to go trough YAML traits.
220 if (const auto *BSN =
221 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000222 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000223 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000224 Context, &IRSlots);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000225 if (!M) {
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000226 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000227 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000228 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000229 In.nextDocument();
230 if (!In.setCurrentDocument())
231 return M;
232 } else {
233 // Create an new, empty module.
234 M = llvm::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000235 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000236 }
237
238 // Parse the machine functions.
239 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000240 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000241 return nullptr;
242 In.nextDocument();
243 } while (In.setCurrentDocument());
244
245 return M;
246}
247
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000248bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
249 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000250 auto MF = llvm::make_unique<yaml::MachineFunction>();
251 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000252 if (In.error())
253 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000254 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000255 if (Functions.find(FunctionName) != Functions.end())
256 return error(Twine("redefinition of machine function '") + FunctionName +
257 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000258 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000259 if (NoLLVMIR)
260 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000261 else if (!M.getFunction(FunctionName))
262 return error(Twine("function '") + FunctionName +
263 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000264 return false;
265}
266
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000267void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
268 auto &Context = M.getContext();
269 Function *F = cast<Function>(M.getOrInsertFunction(
270 Name, FunctionType::get(Type::getVoidTy(Context), false)));
271 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
272 new UnreachableInst(Context, BB);
273}
274
Alex Lorenz735c47e2015-06-15 20:30:22 +0000275bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
276 auto It = Functions.find(MF.getName());
277 if (It == Functions.end())
278 return error(Twine("no machine function information for function '") +
279 MF.getName() + "' in the MIR file");
280 // TODO: Recreate the machine function.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000281 const yaml::MachineFunction &YamlMF = *It->getValue();
282 if (YamlMF.Alignment)
283 MF.setAlignment(YamlMF.Alignment);
284 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
285 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
Alex Lorenz53464512015-07-10 22:51:20 +0000286 PerFunctionMIParsingState PFS;
Alex Lorenzdb07c402015-07-28 16:48:37 +0000287 if (initializeRegisterInfo(MF, YamlMF, PFS))
Alex Lorenz54565cf2015-06-24 19:56:10 +0000288 return true;
Alex Lorenzab980492015-07-20 20:51:18 +0000289 if (!YamlMF.Constants.empty()) {
290 auto *ConstantPool = MF.getConstantPool();
291 assert(ConstantPool && "Constant pool must be created");
292 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
293 PFS.ConstantPoolSlots))
294 return true;
295 }
Alex Lorenz54565cf2015-06-24 19:56:10 +0000296
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000297 const auto &F = *MF.getFunction();
298 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
299 const BasicBlock *BB = nullptr;
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000300 const yaml::StringValue &Name = YamlMBB.Name;
Alex Lorenz8a1915b2015-07-27 22:42:41 +0000301 const yaml::StringValue &IRBlock = YamlMBB.IRBlock;
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000302 if (!Name.Value.empty()) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000303 BB = dyn_cast_or_null<BasicBlock>(
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000304 F.getValueSymbolTable().lookup(Name.Value));
Alex Lorenz00302df2015-06-19 20:12:03 +0000305 if (!BB)
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000306 return error(Name.SourceRange.Start,
307 Twine("basic block '") + Name.Value +
308 "' is not defined in the function '" + MF.getName() +
309 "'");
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000310 }
Alex Lorenz8a1915b2015-07-27 22:42:41 +0000311 if (!IRBlock.Value.empty()) {
312 // TODO: Report an error when both name and ir block are specified.
313 SMDiagnostic Error;
314 if (parseIRBlockReference(BB, SM, MF, IRBlock.Value, PFS, IRSlots, Error))
315 return error(Error, IRBlock.SourceRange);
316 }
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000317 auto *MBB = MF.CreateMachineBasicBlock(BB);
318 MF.insert(MF.end(), MBB);
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000319 bool WasInserted =
320 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000321 if (!WasInserted)
322 return error(Twine("redefinition of machine basic block with id #") +
323 Twine(YamlMBB.ID));
324 }
325
Alex Lorenzc8704b02015-07-09 21:21:33 +0000326 if (YamlMF.BasicBlocks.empty())
327 return error(Twine("machine function '") + Twine(MF.getName()) +
328 "' requires at least one machine basic block in its body");
Alex Lorenza6f9a372015-07-29 21:09:09 +0000329 // Initialize the frame information after creating all the MBBs so that the
330 // MBB references in the frame information can be resolved.
331 if (initializeFrameInfo(MF, YamlMF, PFS))
332 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000333 // Initialize the jump table after creating all the MBBs so that the MBB
334 // references can be resolved.
335 if (!YamlMF.JumpTableInfo.Entries.empty() &&
336 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
337 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000338 // Initialize the machine basic blocks after creating them all so that the
339 // machine instructions parser can resolve the MBB references.
340 unsigned I = 0;
341 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
342 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000343 PFS))
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000344 return true;
345 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000346 inferRegisterInfo(MF, YamlMF);
Alex Lorenzc7bf2042015-07-24 17:44:49 +0000347 // FIXME: This is a temporary workaround until the reserved registers can be
348 // serialized.
349 MF.getRegInfo().freezeReservedRegs(MF);
350 MF.verify();
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000351 return false;
352}
353
354bool MIRParserImpl::initializeMachineBasicBlock(
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000355 MachineFunction &MF, MachineBasicBlock &MBB,
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000356 const yaml::MachineBasicBlock &YamlMBB,
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000357 const PerFunctionMIParsingState &PFS) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000358 MBB.setAlignment(YamlMBB.Alignment);
359 if (YamlMBB.AddressTaken)
360 MBB.setHasAddressTaken();
361 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
Alex Lorenzf09df002015-06-30 18:16:42 +0000362 SMDiagnostic Error;
363 // Parse the successors.
Alex Lorenz618b2832015-07-30 16:54:38 +0000364 const auto &Weights = YamlMBB.SuccessorWeights;
365 bool HasWeights = !Weights.empty();
366 if (HasWeights && Weights.size() != YamlMBB.Successors.size()) {
367 bool IsFew = Weights.size() < YamlMBB.Successors.size();
368 return error(IsFew ? Weights.back().SourceRange.End
369 : Weights[YamlMBB.Successors.size()].SourceRange.Start,
370 Twine("too ") + (IsFew ? "few" : "many") +
371 " successor weights, expected " +
372 Twine(YamlMBB.Successors.size()) + ", have " +
373 Twine(Weights.size()));
374 }
375 size_t SuccessorIndex = 0;
Alex Lorenzf09df002015-06-30 18:16:42 +0000376 for (const auto &MBBSource : YamlMBB.Successors) {
377 MachineBasicBlock *SuccMBB = nullptr;
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000378 if (parseMBBReference(SuccMBB, MBBSource, MF, PFS))
379 return true;
Alex Lorenzf09df002015-06-30 18:16:42 +0000380 // TODO: Report an error when adding the same successor more than once.
Alex Lorenz618b2832015-07-30 16:54:38 +0000381 MBB.addSuccessor(SuccMBB, HasWeights ? Weights[SuccessorIndex++].Value : 0);
Alex Lorenzf09df002015-06-30 18:16:42 +0000382 }
Alex Lorenz9fab3702015-07-14 21:24:41 +0000383 // Parse the liveins.
384 for (const auto &LiveInSource : YamlMBB.LiveIns) {
385 unsigned Reg = 0;
386 if (parseNamedRegisterReference(Reg, SM, MF, LiveInSource.Value, PFS,
387 IRSlots, Error))
388 return error(Error, LiveInSource.SourceRange);
389 MBB.addLiveIn(Reg);
390 }
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000391 // Parse the instructions.
392 for (const auto &MISource : YamlMBB.Instructions) {
Alex Lorenz3708a642015-06-30 17:47:50 +0000393 MachineInstr *MI = nullptr;
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000394 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000395 return error(Error, MISource.SourceRange);
Alex Lorenz3708a642015-06-30 17:47:50 +0000396 MBB.insert(MBB.end(), MI);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000397 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000398 return false;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000399}
400
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000401bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000402 const yaml::MachineFunction &YamlMF,
403 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000404 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Alex Lorenz54565cf2015-06-24 19:56:10 +0000405 assert(RegInfo.isSSA());
406 if (!YamlMF.IsSSA)
407 RegInfo.leaveSSA();
408 assert(RegInfo.tracksLiveness());
409 if (!YamlMF.TracksRegLiveness)
410 RegInfo.invalidateLiveness();
411 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000412
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000413 SMDiagnostic Error;
Alex Lorenz28148ba2015-07-09 22:23:13 +0000414 // Parse the virtual register information.
415 for (const auto &VReg : YamlMF.VirtualRegisters) {
416 const auto *RC = getRegClass(MF, VReg.Class.Value);
417 if (!RC)
418 return error(VReg.Class.SourceRange.Start,
419 Twine("use of undefined register class '") +
420 VReg.Class.Value + "'");
Alex Lorenz53464512015-07-10 22:51:20 +0000421 unsigned Reg = RegInfo.createVirtualRegister(RC);
Alex Lorenza06c0c62015-07-30 21:54:10 +0000422 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
423 .second)
424 return error(VReg.ID.SourceRange.Start,
425 Twine("redefinition of virtual register '%") +
426 Twine(VReg.ID.Value) + "'");
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000427 if (!VReg.PreferredRegister.Value.empty()) {
428 unsigned PreferredReg = 0;
429 if (parseNamedRegisterReference(PreferredReg, SM, MF,
430 VReg.PreferredRegister.Value, PFS,
431 IRSlots, Error))
432 return error(Error, VReg.PreferredRegister.SourceRange);
433 RegInfo.setSimpleHint(Reg, PreferredReg);
434 }
Alex Lorenz28148ba2015-07-09 22:23:13 +0000435 }
Alex Lorenz12045a42015-07-27 17:42:45 +0000436
437 // Parse the liveins.
438 for (const auto &LiveIn : YamlMF.LiveIns) {
439 unsigned Reg = 0;
440 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
441 IRSlots, Error))
442 return error(Error, LiveIn.Register.SourceRange);
443 unsigned VReg = 0;
444 if (!LiveIn.VirtualRegister.Value.empty()) {
445 if (parseVirtualRegisterReference(
446 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
447 return error(Error, LiveIn.VirtualRegister.SourceRange);
448 }
449 RegInfo.addLiveIn(Reg, VReg);
450 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000451
452 // Parse the callee saved register mask.
453 BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
454 if (!YamlMF.CalleeSavedRegisters)
455 return false;
456 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
457 unsigned Reg = 0;
458 if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
459 Error))
460 return error(Error, RegSource.SourceRange);
461 CalleeSavedRegisterMask[Reg] = true;
462 }
463 RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
Alex Lorenz54565cf2015-06-24 19:56:10 +0000464 return false;
465}
466
Alex Lorenzc4838082015-08-11 00:32:49 +0000467void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
468 const yaml::MachineFunction &YamlMF) {
469 if (YamlMF.CalleeSavedRegisters)
470 return;
471 for (const MachineBasicBlock &MBB : MF) {
472 for (const MachineInstr &MI : MBB) {
473 for (const MachineOperand &MO : MI.operands()) {
474 if (!MO.isRegMask())
475 continue;
476 MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
477 }
478 }
479 }
480}
481
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000482bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000483 const yaml::MachineFunction &YamlMF,
484 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000485 MachineFrameInfo &MFI = *MF.getFrameInfo();
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000486 const Function &F = *MF.getFunction();
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000487 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
Alex Lorenz60541c12015-07-09 19:55:27 +0000488 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
489 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
490 MFI.setHasStackMap(YamlMFI.HasStackMap);
491 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
492 MFI.setStackSize(YamlMFI.StackSize);
493 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
494 if (YamlMFI.MaxAlignment)
495 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
496 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
497 MFI.setHasCalls(YamlMFI.HasCalls);
498 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
499 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
500 MFI.setHasVAStart(YamlMFI.HasVAStart);
501 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
Alex Lorenza6f9a372015-07-29 21:09:09 +0000502 if (!YamlMFI.SavePoint.Value.empty()) {
503 MachineBasicBlock *MBB = nullptr;
504 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
505 return true;
506 MFI.setSavePoint(MBB);
507 }
508 if (!YamlMFI.RestorePoint.Value.empty()) {
509 MachineBasicBlock *MBB = nullptr;
510 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
511 return true;
512 MFI.setRestorePoint(MBB);
513 }
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000514
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000515 std::vector<CalleeSavedInfo> CSIInfo;
Alex Lorenzde491f02015-07-13 18:07:26 +0000516 // Initialize the fixed frame objects.
517 for (const auto &Object : YamlMF.FixedStackObjects) {
518 int ObjectIdx;
519 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
520 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
521 Object.IsImmutable, Object.IsAliased);
522 else
523 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
524 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
Alex Lorenz1d9a3032015-08-10 23:45:02 +0000525 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
526 ObjectIdx))
527 .second)
528 return error(Object.ID.SourceRange.Start,
529 Twine("redefinition of fixed stack object '%fixed-stack.") +
530 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000531 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
532 ObjectIdx))
533 return true;
Alex Lorenzde491f02015-07-13 18:07:26 +0000534 }
535
536 // Initialize the ordinary frame objects.
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000537 for (const auto &Object : YamlMF.StackObjects) {
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000538 int ObjectIdx;
Alex Lorenz37643a02015-07-15 22:14:49 +0000539 const AllocaInst *Alloca = nullptr;
540 const yaml::StringValue &Name = Object.Name;
541 if (!Name.Value.empty()) {
542 Alloca = dyn_cast_or_null<AllocaInst>(
543 F.getValueSymbolTable().lookup(Name.Value));
544 if (!Alloca)
545 return error(Name.SourceRange.Start,
546 "alloca instruction named '" + Name.Value +
547 "' isn't defined in the function '" + F.getName() +
548 "'");
549 }
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000550 if (Object.Type == yaml::MachineStackObject::VariableSized)
Alex Lorenz37643a02015-07-15 22:14:49 +0000551 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000552 else
553 ObjectIdx = MFI.CreateStackObject(
554 Object.Size, Object.Alignment,
Alex Lorenz37643a02015-07-15 22:14:49 +0000555 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000556 MFI.setObjectOffset(ObjectIdx, Object.Offset);
Alex Lorenzc5d35ba2015-08-10 23:50:41 +0000557 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
558 .second)
559 return error(Object.ID.SourceRange.Start,
560 Twine("redefinition of stack object '%stack.") +
561 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000562 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
563 ObjectIdx))
564 return true;
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000565 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000566 MFI.setCalleeSavedInfo(CSIInfo);
567 if (!CSIInfo.empty())
568 MFI.setCalleeSavedInfoValid(true);
569 return false;
570}
571
572bool MIRParserImpl::parseCalleeSavedRegister(
573 MachineFunction &MF, PerFunctionMIParsingState &PFS,
574 std::vector<CalleeSavedInfo> &CSIInfo,
575 const yaml::StringValue &RegisterSource, int FrameIdx) {
576 if (RegisterSource.Value.empty())
577 return false;
578 unsigned Reg = 0;
579 SMDiagnostic Error;
580 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
581 IRSlots, Error))
582 return error(Error, RegisterSource.SourceRange);
583 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
Alex Lorenz60541c12015-07-09 19:55:27 +0000584 return false;
585}
586
Alex Lorenzab980492015-07-20 20:51:18 +0000587bool MIRParserImpl::initializeConstantPool(
588 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
589 const MachineFunction &MF,
590 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
591 const auto &M = *MF.getFunction()->getParent();
592 SMDiagnostic Error;
593 for (const auto &YamlConstant : YamlMF.Constants) {
594 const Constant *Value = dyn_cast_or_null<Constant>(
595 parseConstantValue(YamlConstant.Value.Value, Error, M));
596 if (!Value)
597 return error(Error, YamlConstant.Value.SourceRange);
598 unsigned Alignment =
599 YamlConstant.Alignment
600 ? YamlConstant.Alignment
601 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
Alex Lorenz60bf5992015-07-30 22:00:17 +0000602 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
603 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
604 .second)
605 return error(YamlConstant.ID.SourceRange.Start,
606 Twine("redefinition of constant pool item '%const.") +
607 Twine(YamlConstant.ID.Value) + "'");
Alex Lorenzab980492015-07-20 20:51:18 +0000608 }
609 return false;
610}
611
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000612bool MIRParserImpl::initializeJumpTableInfo(
613 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000614 PerFunctionMIParsingState &PFS) {
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000615 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000616 for (const auto &Entry : YamlJTI.Entries) {
617 std::vector<MachineBasicBlock *> Blocks;
618 for (const auto &MBBSource : Entry.Blocks) {
619 MachineBasicBlock *MBB = nullptr;
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000620 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
621 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000622 Blocks.push_back(MBB);
623 }
Alex Lorenz31d70682015-07-15 23:38:35 +0000624 unsigned Index = JTI->createJumpTableIndex(Blocks);
Alex Lorenz59ed5912015-07-31 23:13:23 +0000625 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
626 .second)
627 return error(Entry.ID.SourceRange.Start,
628 Twine("redefinition of jump table entry '%jump-table.") +
629 Twine(Entry.ID.Value) + "'");
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000630 }
631 return false;
632}
633
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000634bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
635 const yaml::StringValue &Source,
636 MachineFunction &MF,
637 const PerFunctionMIParsingState &PFS) {
638 SMDiagnostic Error;
639 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
640 return error(Error, Source.SourceRange);
641 return false;
642}
643
Alex Lorenz51af1602015-06-23 22:39:23 +0000644SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
645 SMRange SourceRange) {
646 assert(SourceRange.isValid() && "Invalid source range");
647 SMLoc Loc = SourceRange.Start;
648 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
649 *Loc.getPointer() == '\'';
650 // Translate the location of the error from the location in the MI string to
651 // the corresponding location in the MIR file.
652 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
653 (HasQuote ? 1 : 0));
654
655 // TODO: Translate any source ranges as well.
656 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
657 Error.getFixIts());
658}
659
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000660SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
661 SMRange SourceRange) {
Alex Lorenz09b832c2015-05-29 17:05:41 +0000662 assert(SourceRange.isValid());
663
664 // Translate the location of the error from the location in the llvm IR string
665 // to the corresponding location in the MIR file.
666 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
667 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
668 unsigned Column = Error.getColumnNo();
669 StringRef LineStr = Error.getLineContents();
670 SMLoc Loc = Error.getLoc();
671
672 // Get the full line and adjust the column number by taking the indentation of
673 // LLVM IR into account.
674 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
675 L != E; ++L) {
676 if (L.line_number() == Line) {
677 LineStr = *L;
678 Loc = SMLoc::getFromPointer(LineStr.data());
679 auto Indent = LineStr.find(Error.getLineContents());
680 if (Indent != StringRef::npos)
681 Column += Indent;
682 break;
683 }
684 }
685
686 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
687 Error.getMessage(), LineStr, Error.getRanges(),
688 Error.getFixIts());
689}
690
Alex Lorenz28148ba2015-07-09 22:23:13 +0000691void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
692 if (!Names2RegClasses.empty())
693 return;
694 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
695 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
696 const auto *RC = TRI->getRegClass(I);
697 Names2RegClasses.insert(
698 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
699 }
700}
701
702const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
703 StringRef Name) {
704 initNames2RegClasses(MF);
705 auto RegClassInfo = Names2RegClasses.find(Name);
706 if (RegClassInfo == Names2RegClasses.end())
707 return nullptr;
708 return RegClassInfo->getValue();
709}
710
Alex Lorenz735c47e2015-06-15 20:30:22 +0000711MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
712 : Impl(std::move(Impl)) {}
713
714MIRParser::~MIRParser() {}
715
716std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
717
718bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
719 return Impl->initializeMachineFunction(MF);
720}
721
722std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
723 SMDiagnostic &Error,
724 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000725 auto FileOrErr = MemoryBuffer::getFile(Filename);
726 if (std::error_code EC = FileOrErr.getError()) {
727 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
728 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000729 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000730 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000731 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000732}
733
Alex Lorenz735c47e2015-06-15 20:30:22 +0000734std::unique_ptr<MIRParser>
735llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
736 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000737 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000738 return llvm::make_unique<MIRParser>(
739 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000740}