blob: e977973b1a591eedb5cadfd8e645dde36a602f4a [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/STLExtras.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000019#include "llvm/ADT/StringMap.h"
20#include "llvm/ADT/StringRef.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000021#include "llvm/AsmParser/Parser.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000022#include "llvm/AsmParser/SlotMapping.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000023#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24#include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
25#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenzab980492015-07-20 20:51:18 +000026#include "llvm/CodeGen/MachineConstantPool.h"
Alex Lorenz60541c12015-07-09 19:55:27 +000027#include "llvm/CodeGen/MachineFrameInfo.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000028#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenzdf9e3c62015-08-19 00:13:25 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000031#include "llvm/IR/BasicBlock.h"
Reid Kleckner28865802016-04-14 18:29:59 +000032#include "llvm/IR/DebugInfo.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000033#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000034#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000035#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000036#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000037#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000038#include "llvm/Support/LineIterator.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000039#include "llvm/Support/MemoryBuffer.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000040#include "llvm/Support/SMLoc.h"
41#include "llvm/Support/SourceMgr.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000042#include "llvm/Support/YAMLTraits.h"
43#include <memory>
44
45using namespace llvm;
46
Alex Lorenz735c47e2015-06-15 20:30:22 +000047namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000048
49/// This class implements the parsing of LLVM IR that's embedded inside a MIR
50/// file.
51class MIRParserImpl {
52 SourceMgr SM;
53 StringRef Filename;
54 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000055 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000056 SlotMapping IRSlots;
Alex Lorenz28148ba2015-07-09 22:23:13 +000057 /// Maps from register class names to register classes.
58 StringMap<const TargetRegisterClass *> Names2RegClasses;
Quentin Colombet876ddf82016-04-08 16:40:43 +000059 /// Maps from register bank names to register banks.
60 StringMap<const RegisterBank *> Names2RegBanks;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000061
62public:
63 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
64 LLVMContext &Context);
65
Alex Lorenz735c47e2015-06-15 20:30:22 +000066 void reportDiagnostic(const SMDiagnostic &Diag);
67
68 /// Report an error with the given message at unknown location.
69 ///
70 /// Always returns true.
71 bool error(const Twine &Message);
72
Alex Lorenzb1f9ce82015-07-08 20:22:20 +000073 /// Report an error with the given message at the given location.
74 ///
75 /// Always returns true.
76 bool error(SMLoc Loc, const Twine &Message);
77
Alex Lorenz0fd7c622015-06-30 17:55:00 +000078 /// Report a given error with the location translated from the location in an
79 /// embedded string literal to a location in the MIR file.
80 ///
81 /// Always returns true.
82 bool error(const SMDiagnostic &Error, SMRange SourceRange);
83
Alex Lorenz78d78312015-05-28 22:41:12 +000084 /// Try to parse the optional LLVM module and the machine functions in the MIR
85 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000086 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000087 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000088 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000089
90 /// Parse the machine function in the current YAML document.
91 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000092 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
93 /// A dummy IR function is created and inserted into the given module when
94 /// this parameter is true.
95 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000096 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000097 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000098
Alex Lorenz735c47e2015-06-15 20:30:22 +000099 /// Initialize the machine function to the state that's described in the MIR
100 /// file.
101 ///
102 /// Return true if error occurred.
103 bool initializeMachineFunction(MachineFunction &MF);
104
Alex Lorenzdb07c402015-07-28 16:48:37 +0000105 bool initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000106 const yaml::MachineFunction &YamlMF,
107 PerFunctionMIParsingState &PFS);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000108
Alex Lorenzc4838082015-08-11 00:32:49 +0000109 void inferRegisterInfo(MachineFunction &MF,
110 const yaml::MachineFunction &YamlMF);
111
Alex Lorenzdb07c402015-07-28 16:48:37 +0000112 bool initializeFrameInfo(MachineFunction &MF,
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000113 const yaml::MachineFunction &YamlMF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000114 PerFunctionMIParsingState &PFS);
115
116 bool parseCalleeSavedRegister(MachineFunction &MF,
117 PerFunctionMIParsingState &PFS,
118 std::vector<CalleeSavedInfo> &CSIInfo,
119 const yaml::StringValue &RegisterSource,
120 int FrameIdx);
Alex Lorenz60541c12015-07-09 19:55:27 +0000121
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000122 bool parseStackObjectsDebugInfo(MachineFunction &MF,
123 PerFunctionMIParsingState &PFS,
124 const yaml::MachineStackObject &Object,
125 int FrameIdx);
126
Alex Lorenzab980492015-07-20 20:51:18 +0000127 bool initializeConstantPool(MachineConstantPool &ConstantPool,
128 const yaml::MachineFunction &YamlMF,
129 const MachineFunction &MF,
130 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
131
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000132 bool initializeJumpTableInfo(MachineFunction &MF,
133 const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000134 PerFunctionMIParsingState &PFS);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000135
Alex Lorenz09b832c2015-05-29 17:05:41 +0000136private:
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000137 bool parseMDNode(MDNode *&Node, const yaml::StringValue &Source,
138 MachineFunction &MF, const PerFunctionMIParsingState &PFS);
139
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000140 bool parseMBBReference(MachineBasicBlock *&MBB,
141 const yaml::StringValue &Source, MachineFunction &MF,
142 const PerFunctionMIParsingState &PFS);
143
Alex Lorenz51af1602015-06-23 22:39:23 +0000144 /// Return a MIR diagnostic converted from an MI string diagnostic.
145 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
146 SMRange SourceRange);
147
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000148 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
149 /// block scalar string.
150 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
151 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000152
153 /// Create an empty function with the given name.
154 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000155
156 void initNames2RegClasses(const MachineFunction &MF);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000157 void initNames2RegBanks(const MachineFunction &MF);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000158
159 /// Check if the given identifier is a name of a register class.
160 ///
161 /// Return null if the name isn't a register class.
162 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
163 StringRef Name);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000164
165 /// Check if the given identifier is a name of a register bank.
166 ///
167 /// Return null if the name isn't a register bank.
168 const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000169};
170
Alex Lorenz735c47e2015-06-15 20:30:22 +0000171} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000172
173MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
174 StringRef Filename, LLVMContext &Context)
175 : SM(), Filename(Filename), Context(Context) {
176 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
177}
178
Alex Lorenz735c47e2015-06-15 20:30:22 +0000179bool MIRParserImpl::error(const Twine &Message) {
180 Context.diagnose(DiagnosticInfoMIRParser(
181 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
182 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000183}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000184
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000185bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
186 Context.diagnose(DiagnosticInfoMIRParser(
187 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
188 return true;
189}
190
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000191bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
192 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
193 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
194 return true;
195}
196
Alex Lorenz735c47e2015-06-15 20:30:22 +0000197void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
198 DiagnosticSeverity Kind;
199 switch (Diag.getKind()) {
200 case SourceMgr::DK_Error:
201 Kind = DS_Error;
202 break;
203 case SourceMgr::DK_Warning:
204 Kind = DS_Warning;
205 break;
206 case SourceMgr::DK_Note:
207 Kind = DS_Note;
208 break;
209 }
210 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
211}
212
213static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
214 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
215}
216
217std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000218 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000219 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000220 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000221
222 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000223 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000224 return nullptr;
225 // Create an empty module when the MIR file is empty.
226 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000227 }
228
Alex Lorenz78d78312015-05-28 22:41:12 +0000229 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000230 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000231 // Parse the block scalar manually so that we can return unique pointer
232 // without having to go trough YAML traits.
233 if (const auto *BSN =
234 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000235 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000236 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000237 Context, &IRSlots);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000238 if (!M) {
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000239 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000240 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000241 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000242 In.nextDocument();
243 if (!In.setCurrentDocument())
244 return M;
245 } else {
246 // Create an new, empty module.
247 M = llvm::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000248 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000249 }
250
251 // Parse the machine functions.
252 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000253 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000254 return nullptr;
255 In.nextDocument();
256 } while (In.setCurrentDocument());
257
258 return M;
259}
260
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000261bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
262 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000263 auto MF = llvm::make_unique<yaml::MachineFunction>();
264 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000265 if (In.error())
266 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000267 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000268 if (Functions.find(FunctionName) != Functions.end())
269 return error(Twine("redefinition of machine function '") + FunctionName +
270 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000271 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000272 if (NoLLVMIR)
273 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000274 else if (!M.getFunction(FunctionName))
275 return error(Twine("function '") + FunctionName +
276 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000277 return false;
278}
279
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000280void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
281 auto &Context = M.getContext();
282 Function *F = cast<Function>(M.getOrInsertFunction(
283 Name, FunctionType::get(Type::getVoidTy(Context), false)));
284 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
285 new UnreachableInst(Context, BB);
286}
287
Alex Lorenz735c47e2015-06-15 20:30:22 +0000288bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
289 auto It = Functions.find(MF.getName());
290 if (It == Functions.end())
291 return error(Twine("no machine function information for function '") +
292 MF.getName() + "' in the MIR file");
293 // TODO: Recreate the machine function.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000294 const yaml::MachineFunction &YamlMF = *It->getValue();
295 if (YamlMF.Alignment)
296 MF.setAlignment(YamlMF.Alignment);
297 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
298 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
Derek Schuffad154c82016-03-28 17:05:30 +0000299 if (YamlMF.AllVRegsAllocated)
300 MF.getProperties().set(MachineFunctionProperties::Property::AllVRegsAllocated);
Alex Lorenz53464512015-07-10 22:51:20 +0000301 PerFunctionMIParsingState PFS;
Alex Lorenzdb07c402015-07-28 16:48:37 +0000302 if (initializeRegisterInfo(MF, YamlMF, PFS))
Alex Lorenz54565cf2015-06-24 19:56:10 +0000303 return true;
Alex Lorenzab980492015-07-20 20:51:18 +0000304 if (!YamlMF.Constants.empty()) {
305 auto *ConstantPool = MF.getConstantPool();
306 assert(ConstantPool && "Constant pool must be created");
307 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
308 PFS.ConstantPoolSlots))
309 return true;
310 }
Alex Lorenz54565cf2015-06-24 19:56:10 +0000311
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000312 SMDiagnostic Error;
313 if (parseMachineBasicBlockDefinitions(MF, YamlMF.Body.Value.Value, PFS,
314 IRSlots, Error)) {
315 reportDiagnostic(
316 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
317 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000318 }
319
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000320 if (MF.empty())
Alex Lorenzc8704b02015-07-09 21:21:33 +0000321 return error(Twine("machine function '") + Twine(MF.getName()) +
322 "' requires at least one machine basic block in its body");
Alex Lorenza6f9a372015-07-29 21:09:09 +0000323 // Initialize the frame information after creating all the MBBs so that the
324 // MBB references in the frame information can be resolved.
325 if (initializeFrameInfo(MF, YamlMF, PFS))
326 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000327 // Initialize the jump table after creating all the MBBs so that the MBB
328 // references can be resolved.
329 if (!YamlMF.JumpTableInfo.Entries.empty() &&
330 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
331 return true;
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000332 // Parse the machine instructions after creating all of the MBBs so that the
333 // parser can resolve the MBB references.
334 if (parseMachineInstructions(MF, YamlMF.Body.Value.Value, PFS, IRSlots,
335 Error)) {
336 reportDiagnostic(
337 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
338 return true;
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000339 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000340 inferRegisterInfo(MF, YamlMF);
Alex Lorenzc7bf2042015-07-24 17:44:49 +0000341 // FIXME: This is a temporary workaround until the reserved registers can be
342 // serialized.
343 MF.getRegInfo().freezeReservedRegs(MF);
344 MF.verify();
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000345 return false;
346}
347
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000348bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000349 const yaml::MachineFunction &YamlMF,
350 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000351 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Alex Lorenz54565cf2015-06-24 19:56:10 +0000352 assert(RegInfo.isSSA());
353 if (!YamlMF.IsSSA)
354 RegInfo.leaveSSA();
355 assert(RegInfo.tracksLiveness());
356 if (!YamlMF.TracksRegLiveness)
357 RegInfo.invalidateLiveness();
358 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000359
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000360 SMDiagnostic Error;
Alex Lorenz28148ba2015-07-09 22:23:13 +0000361 // Parse the virtual register information.
362 for (const auto &VReg : YamlMF.VirtualRegisters) {
Quentin Colombet050b2112016-03-08 01:17:03 +0000363 unsigned Reg;
364 if (StringRef(VReg.Class.Value).equals("_")) {
365 // This is a generic virtual register.
366 // The size will be set appropriately when we reach the definition.
367 Reg = RegInfo.createGenericVirtualRegister(/*Size*/ 1);
Quentin Colombet2c646962016-06-08 23:27:46 +0000368 PFS.GenericVRegs.insert(Reg);
Quentin Colombet050b2112016-03-08 01:17:03 +0000369 } else {
370 const auto *RC = getRegClass(MF, VReg.Class.Value);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000371 if (RC) {
372 Reg = RegInfo.createVirtualRegister(RC);
373 } else {
374 const auto *RegBank = getRegBank(MF, VReg.Class.Value);
375 if (!RegBank)
376 return error(
377 VReg.Class.SourceRange.Start,
378 Twine("use of undefined register class or register bank '") +
379 VReg.Class.Value + "'");
380 Reg = RegInfo.createGenericVirtualRegister(/*Size*/ 1);
381 RegInfo.setRegBank(Reg, *RegBank);
Quentin Colombet2c646962016-06-08 23:27:46 +0000382 PFS.GenericVRegs.insert(Reg);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000383 }
Quentin Colombet050b2112016-03-08 01:17:03 +0000384 }
Alex Lorenza06c0c62015-07-30 21:54:10 +0000385 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
386 .second)
387 return error(VReg.ID.SourceRange.Start,
388 Twine("redefinition of virtual register '%") +
389 Twine(VReg.ID.Value) + "'");
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000390 if (!VReg.PreferredRegister.Value.empty()) {
391 unsigned PreferredReg = 0;
392 if (parseNamedRegisterReference(PreferredReg, SM, MF,
393 VReg.PreferredRegister.Value, PFS,
394 IRSlots, Error))
395 return error(Error, VReg.PreferredRegister.SourceRange);
396 RegInfo.setSimpleHint(Reg, PreferredReg);
397 }
Alex Lorenz28148ba2015-07-09 22:23:13 +0000398 }
Alex Lorenz12045a42015-07-27 17:42:45 +0000399
400 // Parse the liveins.
401 for (const auto &LiveIn : YamlMF.LiveIns) {
402 unsigned Reg = 0;
403 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
404 IRSlots, Error))
405 return error(Error, LiveIn.Register.SourceRange);
406 unsigned VReg = 0;
407 if (!LiveIn.VirtualRegister.Value.empty()) {
408 if (parseVirtualRegisterReference(
409 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
410 return error(Error, LiveIn.VirtualRegister.SourceRange);
411 }
412 RegInfo.addLiveIn(Reg, VReg);
413 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000414
415 // Parse the callee saved register mask.
416 BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
417 if (!YamlMF.CalleeSavedRegisters)
418 return false;
419 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
420 unsigned Reg = 0;
421 if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
422 Error))
423 return error(Error, RegSource.SourceRange);
424 CalleeSavedRegisterMask[Reg] = true;
425 }
426 RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
Alex Lorenz54565cf2015-06-24 19:56:10 +0000427 return false;
428}
429
Alex Lorenzc4838082015-08-11 00:32:49 +0000430void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
431 const yaml::MachineFunction &YamlMF) {
432 if (YamlMF.CalleeSavedRegisters)
433 return;
434 for (const MachineBasicBlock &MBB : MF) {
435 for (const MachineInstr &MI : MBB) {
436 for (const MachineOperand &MO : MI.operands()) {
437 if (!MO.isRegMask())
438 continue;
439 MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
440 }
441 }
442 }
443}
444
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000445bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000446 const yaml::MachineFunction &YamlMF,
447 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000448 MachineFrameInfo &MFI = *MF.getFrameInfo();
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000449 const Function &F = *MF.getFunction();
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000450 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
Alex Lorenz60541c12015-07-09 19:55:27 +0000451 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
452 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
453 MFI.setHasStackMap(YamlMFI.HasStackMap);
454 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
455 MFI.setStackSize(YamlMFI.StackSize);
456 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
457 if (YamlMFI.MaxAlignment)
458 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
459 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
460 MFI.setHasCalls(YamlMFI.HasCalls);
461 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
462 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
463 MFI.setHasVAStart(YamlMFI.HasVAStart);
464 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
Alex Lorenza6f9a372015-07-29 21:09:09 +0000465 if (!YamlMFI.SavePoint.Value.empty()) {
466 MachineBasicBlock *MBB = nullptr;
467 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
468 return true;
469 MFI.setSavePoint(MBB);
470 }
471 if (!YamlMFI.RestorePoint.Value.empty()) {
472 MachineBasicBlock *MBB = nullptr;
473 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
474 return true;
475 MFI.setRestorePoint(MBB);
476 }
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000477
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000478 std::vector<CalleeSavedInfo> CSIInfo;
Alex Lorenzde491f02015-07-13 18:07:26 +0000479 // Initialize the fixed frame objects.
480 for (const auto &Object : YamlMF.FixedStackObjects) {
481 int ObjectIdx;
482 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
483 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
484 Object.IsImmutable, Object.IsAliased);
485 else
486 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
487 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
Alex Lorenz1d9a3032015-08-10 23:45:02 +0000488 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
489 ObjectIdx))
490 .second)
491 return error(Object.ID.SourceRange.Start,
492 Twine("redefinition of fixed stack object '%fixed-stack.") +
493 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000494 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
495 ObjectIdx))
496 return true;
Alex Lorenzde491f02015-07-13 18:07:26 +0000497 }
498
499 // Initialize the ordinary frame objects.
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000500 for (const auto &Object : YamlMF.StackObjects) {
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000501 int ObjectIdx;
Alex Lorenz37643a02015-07-15 22:14:49 +0000502 const AllocaInst *Alloca = nullptr;
503 const yaml::StringValue &Name = Object.Name;
504 if (!Name.Value.empty()) {
505 Alloca = dyn_cast_or_null<AllocaInst>(
506 F.getValueSymbolTable().lookup(Name.Value));
507 if (!Alloca)
508 return error(Name.SourceRange.Start,
509 "alloca instruction named '" + Name.Value +
510 "' isn't defined in the function '" + F.getName() +
511 "'");
512 }
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000513 if (Object.Type == yaml::MachineStackObject::VariableSized)
Alex Lorenz37643a02015-07-15 22:14:49 +0000514 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000515 else
516 ObjectIdx = MFI.CreateStackObject(
517 Object.Size, Object.Alignment,
Alex Lorenz37643a02015-07-15 22:14:49 +0000518 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000519 MFI.setObjectOffset(ObjectIdx, Object.Offset);
Alex Lorenzc5d35ba2015-08-10 23:50:41 +0000520 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
521 .second)
522 return error(Object.ID.SourceRange.Start,
523 Twine("redefinition of stack object '%stack.") +
524 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000525 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
526 ObjectIdx))
527 return true;
Alex Lorenza56ba6a2015-08-17 22:17:42 +0000528 if (Object.LocalOffset)
529 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000530 if (parseStackObjectsDebugInfo(MF, PFS, Object, ObjectIdx))
531 return true;
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000532 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000533 MFI.setCalleeSavedInfo(CSIInfo);
534 if (!CSIInfo.empty())
535 MFI.setCalleeSavedInfoValid(true);
Alex Lorenza314d812015-08-18 22:26:26 +0000536
537 // Initialize the various stack object references after initializing the
538 // stack objects.
539 if (!YamlMFI.StackProtector.Value.empty()) {
540 SMDiagnostic Error;
541 int FI;
542 if (parseStackObjectReference(FI, SM, MF, YamlMFI.StackProtector.Value, PFS,
543 IRSlots, Error))
544 return error(Error, YamlMFI.StackProtector.SourceRange);
545 MFI.setStackProtectorIndex(FI);
546 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000547 return false;
548}
549
550bool MIRParserImpl::parseCalleeSavedRegister(
551 MachineFunction &MF, PerFunctionMIParsingState &PFS,
552 std::vector<CalleeSavedInfo> &CSIInfo,
553 const yaml::StringValue &RegisterSource, int FrameIdx) {
554 if (RegisterSource.Value.empty())
555 return false;
556 unsigned Reg = 0;
557 SMDiagnostic Error;
558 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
559 IRSlots, Error))
560 return error(Error, RegisterSource.SourceRange);
561 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
Alex Lorenz60541c12015-07-09 19:55:27 +0000562 return false;
563}
564
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000565/// Verify that given node is of a certain type. Return true on error.
566template <typename T>
567static bool typecheckMDNode(T *&Result, MDNode *Node,
568 const yaml::StringValue &Source,
569 StringRef TypeString, MIRParserImpl &Parser) {
570 if (!Node)
571 return false;
572 Result = dyn_cast<T>(Node);
573 if (!Result)
574 return Parser.error(Source.SourceRange.Start,
575 "expected a reference to a '" + TypeString +
576 "' metadata node");
577 return false;
578}
579
580bool MIRParserImpl::parseStackObjectsDebugInfo(
581 MachineFunction &MF, PerFunctionMIParsingState &PFS,
582 const yaml::MachineStackObject &Object, int FrameIdx) {
583 // Debug information can only be attached to stack objects; Fixed stack
584 // objects aren't supported.
585 assert(FrameIdx >= 0 && "Expected a stack object frame index");
586 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
587 if (parseMDNode(Var, Object.DebugVar, MF, PFS) ||
588 parseMDNode(Expr, Object.DebugExpr, MF, PFS) ||
589 parseMDNode(Loc, Object.DebugLoc, MF, PFS))
590 return true;
591 if (!Var && !Expr && !Loc)
592 return false;
593 DILocalVariable *DIVar = nullptr;
594 DIExpression *DIExpr = nullptr;
595 DILocation *DILoc = nullptr;
596 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
597 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
598 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
599 return true;
600 MF.getMMI().setVariableDbgInfo(DIVar, DIExpr, unsigned(FrameIdx), DILoc);
601 return false;
602}
603
604bool MIRParserImpl::parseMDNode(MDNode *&Node, const yaml::StringValue &Source,
605 MachineFunction &MF,
606 const PerFunctionMIParsingState &PFS) {
607 if (Source.Value.empty())
608 return false;
609 SMDiagnostic Error;
610 if (llvm::parseMDNode(Node, SM, MF, Source.Value, PFS, IRSlots, Error))
611 return error(Error, Source.SourceRange);
612 return false;
613}
614
Alex Lorenzab980492015-07-20 20:51:18 +0000615bool MIRParserImpl::initializeConstantPool(
616 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
617 const MachineFunction &MF,
618 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
619 const auto &M = *MF.getFunction()->getParent();
620 SMDiagnostic Error;
621 for (const auto &YamlConstant : YamlMF.Constants) {
622 const Constant *Value = dyn_cast_or_null<Constant>(
623 parseConstantValue(YamlConstant.Value.Value, Error, M));
624 if (!Value)
625 return error(Error, YamlConstant.Value.SourceRange);
626 unsigned Alignment =
627 YamlConstant.Alignment
628 ? YamlConstant.Alignment
629 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
Alex Lorenz60bf5992015-07-30 22:00:17 +0000630 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
631 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
632 .second)
633 return error(YamlConstant.ID.SourceRange.Start,
634 Twine("redefinition of constant pool item '%const.") +
635 Twine(YamlConstant.ID.Value) + "'");
Alex Lorenzab980492015-07-20 20:51:18 +0000636 }
637 return false;
638}
639
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000640bool MIRParserImpl::initializeJumpTableInfo(
641 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000642 PerFunctionMIParsingState &PFS) {
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000643 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000644 for (const auto &Entry : YamlJTI.Entries) {
645 std::vector<MachineBasicBlock *> Blocks;
646 for (const auto &MBBSource : Entry.Blocks) {
647 MachineBasicBlock *MBB = nullptr;
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000648 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
649 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000650 Blocks.push_back(MBB);
651 }
Alex Lorenz31d70682015-07-15 23:38:35 +0000652 unsigned Index = JTI->createJumpTableIndex(Blocks);
Alex Lorenz59ed5912015-07-31 23:13:23 +0000653 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
654 .second)
655 return error(Entry.ID.SourceRange.Start,
656 Twine("redefinition of jump table entry '%jump-table.") +
657 Twine(Entry.ID.Value) + "'");
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000658 }
659 return false;
660}
661
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000662bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
663 const yaml::StringValue &Source,
664 MachineFunction &MF,
665 const PerFunctionMIParsingState &PFS) {
666 SMDiagnostic Error;
667 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
668 return error(Error, Source.SourceRange);
669 return false;
670}
671
Alex Lorenz51af1602015-06-23 22:39:23 +0000672SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
673 SMRange SourceRange) {
674 assert(SourceRange.isValid() && "Invalid source range");
675 SMLoc Loc = SourceRange.Start;
676 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
677 *Loc.getPointer() == '\'';
678 // Translate the location of the error from the location in the MI string to
679 // the corresponding location in the MIR file.
680 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
681 (HasQuote ? 1 : 0));
682
683 // TODO: Translate any source ranges as well.
684 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
685 Error.getFixIts());
686}
687
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000688SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
689 SMRange SourceRange) {
Alex Lorenz09b832c2015-05-29 17:05:41 +0000690 assert(SourceRange.isValid());
691
692 // Translate the location of the error from the location in the llvm IR string
693 // to the corresponding location in the MIR file.
694 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
695 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
696 unsigned Column = Error.getColumnNo();
697 StringRef LineStr = Error.getLineContents();
698 SMLoc Loc = Error.getLoc();
699
700 // Get the full line and adjust the column number by taking the indentation of
701 // LLVM IR into account.
702 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
703 L != E; ++L) {
704 if (L.line_number() == Line) {
705 LineStr = *L;
706 Loc = SMLoc::getFromPointer(LineStr.data());
707 auto Indent = LineStr.find(Error.getLineContents());
708 if (Indent != StringRef::npos)
709 Column += Indent;
710 break;
711 }
712 }
713
714 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
715 Error.getMessage(), LineStr, Error.getRanges(),
716 Error.getFixIts());
717}
718
Alex Lorenz28148ba2015-07-09 22:23:13 +0000719void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
720 if (!Names2RegClasses.empty())
721 return;
722 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
723 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
724 const auto *RC = TRI->getRegClass(I);
725 Names2RegClasses.insert(
726 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
727 }
728}
729
Quentin Colombet876ddf82016-04-08 16:40:43 +0000730void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) {
731 if (!Names2RegBanks.empty())
732 return;
733 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
734 // If the target does not support GlobalISel, we may not have a
735 // register bank info.
736 if (!RBI)
737 return;
738 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
739 const auto &RegBank = RBI->getRegBank(I);
740 Names2RegBanks.insert(
741 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
742 }
743}
744
Alex Lorenz28148ba2015-07-09 22:23:13 +0000745const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
746 StringRef Name) {
747 initNames2RegClasses(MF);
748 auto RegClassInfo = Names2RegClasses.find(Name);
749 if (RegClassInfo == Names2RegClasses.end())
750 return nullptr;
751 return RegClassInfo->getValue();
752}
753
Quentin Colombet876ddf82016-04-08 16:40:43 +0000754const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF,
755 StringRef Name) {
756 initNames2RegBanks(MF);
757 auto RegBankInfo = Names2RegBanks.find(Name);
758 if (RegBankInfo == Names2RegBanks.end())
759 return nullptr;
760 return RegBankInfo->getValue();
761}
762
Alex Lorenz735c47e2015-06-15 20:30:22 +0000763MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
764 : Impl(std::move(Impl)) {}
765
766MIRParser::~MIRParser() {}
767
768std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
769
770bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
771 return Impl->initializeMachineFunction(MF);
772}
773
774std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
775 SMDiagnostic &Error,
776 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000777 auto FileOrErr = MemoryBuffer::getFile(Filename);
778 if (std::error_code EC = FileOrErr.getError()) {
779 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
780 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000781 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000782 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000783 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000784}
785
Alex Lorenz735c47e2015-06-15 20:30:22 +0000786std::unique_ptr<MIRParser>
787llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
788 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000789 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000790 return llvm::make_unique<MIRParser>(
791 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000792}