blob: 44734661f47a532139c1e2bf3c2b90b732f6c181 [file] [log] [blame]
Alex Lorenz8e0a1b42015-06-22 17:02:30 +00001//===- MIParser.cpp - Machine instructions 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 parsing of machine instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MIParser.h"
Alex Lorenz91370c52015-06-22 20:37:46 +000015#include "MILexer.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000016#include "llvm/ADT/StringMap.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000017#include "llvm/AsmParser/SlotMapping.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000018#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineInstr.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000021#include "llvm/IR/Module.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000022#include "llvm/Support/raw_ostream.h"
23#include "llvm/Support/SourceMgr.h"
24#include "llvm/Target/TargetSubtargetInfo.h"
25#include "llvm/Target/TargetInstrInfo.h"
26
27using namespace llvm;
28
29namespace {
30
31class MIParser {
32 SourceMgr &SM;
33 MachineFunction &MF;
34 SMDiagnostic &Error;
Alex Lorenz91370c52015-06-22 20:37:46 +000035 StringRef Source, CurrentSource;
36 MIToken Token;
Alex Lorenz33f0aef2015-06-26 16:46:11 +000037 /// Maps from basic block numbers to MBBs.
38 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000039 /// Maps from indices to unnamed global values and metadata nodes.
40 const SlotMapping &IRSlots;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000041 /// Maps from instruction names to op codes.
42 StringMap<unsigned> Names2InstrOpCodes;
Alex Lorenzf3db51de2015-06-23 16:35:26 +000043 /// Maps from register names to registers.
44 StringMap<unsigned> Names2Regs;
Alex Lorenz8f6f4282015-06-29 16:57:06 +000045 /// Maps from register mask names to register masks.
46 StringMap<const uint32_t *> Names2RegMasks;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000047
48public:
49 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
Alex Lorenz33f0aef2015-06-26 16:46:11 +000050 StringRef Source,
Alex Lorenz5d6108e2015-06-26 22:56:48 +000051 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
52 const SlotMapping &IRSlots);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000053
Alex Lorenz91370c52015-06-22 20:37:46 +000054 void lex();
55
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000056 /// Report an error at the current location with the given message.
57 ///
58 /// This function always return true.
59 bool error(const Twine &Msg);
60
Alex Lorenz91370c52015-06-22 20:37:46 +000061 /// Report an error at the given location with the given message.
62 ///
63 /// This function always return true.
64 bool error(StringRef::iterator Loc, const Twine &Msg);
65
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000066 MachineInstr *parse();
67
Alex Lorenzf3db51de2015-06-23 16:35:26 +000068 bool parseRegister(unsigned &Reg);
69 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
Alex Lorenz240fc1e2015-06-23 23:42:28 +000070 bool parseImmediateOperand(MachineOperand &Dest);
Alex Lorenz33f0aef2015-06-26 16:46:11 +000071 bool parseMBBOperand(MachineOperand &Dest);
Alex Lorenz5d6108e2015-06-26 22:56:48 +000072 bool parseGlobalAddressOperand(MachineOperand &Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +000073 bool parseMachineOperand(MachineOperand &Dest);
74
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000075private:
Alex Lorenz33f0aef2015-06-26 16:46:11 +000076 /// Convert the integer literal in the current token into an unsigned integer.
77 ///
78 /// Return true if an error occurred.
79 bool getUnsigned(unsigned &Result);
80
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000081 void initNames2InstrOpCodes();
82
83 /// Try to convert an instruction name to an opcode. Return true if the
84 /// instruction name is invalid.
85 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
Alex Lorenz91370c52015-06-22 20:37:46 +000086
87 bool parseInstruction(unsigned &OpCode);
Alex Lorenzf3db51de2015-06-23 16:35:26 +000088
89 void initNames2Regs();
90
91 /// Try to convert a register name to a register number. Return true if the
92 /// register name is invalid.
93 bool getRegisterByName(StringRef RegName, unsigned &Reg);
Alex Lorenz8f6f4282015-06-29 16:57:06 +000094
95 void initNames2RegMasks();
96
97 /// Check if the given identifier is a name of a register mask.
98 ///
99 /// Return null if the identifier isn't a register mask.
100 const uint32_t *getRegMask(StringRef Identifier);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000101};
102
103} // end anonymous namespace
104
105MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000106 StringRef Source,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000107 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
108 const SlotMapping &IRSlots)
Alex Lorenz91370c52015-06-22 20:37:46 +0000109 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000110 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
111}
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000112
Alex Lorenz91370c52015-06-22 20:37:46 +0000113void MIParser::lex() {
114 CurrentSource = lexMIToken(
115 CurrentSource, Token,
116 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
117}
118
119bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
120
121bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000122 // TODO: Get the proper location in the MIR file, not just a location inside
123 // the string.
Alex Lorenz91370c52015-06-22 20:37:46 +0000124 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
125 Error = SMDiagnostic(
126 SM, SMLoc(),
127 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
128 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000129 return true;
130}
131
132MachineInstr *MIParser::parse() {
Alex Lorenz91370c52015-06-22 20:37:46 +0000133 lex();
134
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000135 // Parse any register operands before '='
136 // TODO: Allow parsing of multiple operands before '='
137 MachineOperand MO = MachineOperand::CreateImm(0);
138 SmallVector<MachineOperand, 8> Operands;
139 if (Token.isRegister()) {
140 if (parseRegisterOperand(MO, /*IsDef=*/true))
141 return nullptr;
142 Operands.push_back(MO);
143 if (Token.isNot(MIToken::equal)) {
144 error("expected '='");
145 return nullptr;
146 }
147 lex();
148 }
149
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000150 unsigned OpCode;
Alex Lorenz91370c52015-06-22 20:37:46 +0000151 if (Token.isError() || parseInstruction(OpCode))
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000152 return nullptr;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000153
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000154 // TODO: Parse the instruction flags and memory operands.
155
156 // Parse the remaining machine operands.
157 while (Token.isNot(MIToken::Eof)) {
158 if (parseMachineOperand(MO))
159 return nullptr;
160 Operands.push_back(MO);
161 if (Token.is(MIToken::Eof))
162 break;
163 if (Token.isNot(MIToken::comma)) {
164 error("expected ',' before the next machine operand");
165 return nullptr;
166 }
167 lex();
168 }
169
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000170 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000171
172 // Verify machine operands.
173 if (!MCID.isVariadic()) {
174 for (size_t I = 0, E = Operands.size(); I < E; ++I) {
175 if (I < MCID.getNumOperands())
176 continue;
177 // Mark this register as implicit to prevent an assertion when it's added
178 // to an instruction. This is a temporary workaround until the implicit
179 // register flag can be parsed.
Alex Lorenz8f6f4282015-06-29 16:57:06 +0000180 if (Operands[I].isReg())
181 Operands[I].setImplicit();
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000182 }
183 }
184
185 // TODO: Determine the implicit behaviour when implicit register flags are
186 // parsed.
187 auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
188 for (const auto &Operand : Operands)
189 MI->addOperand(MF, Operand);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000190 return MI;
191}
192
Alex Lorenz91370c52015-06-22 20:37:46 +0000193bool MIParser::parseInstruction(unsigned &OpCode) {
194 if (Token.isNot(MIToken::Identifier))
195 return error("expected a machine instruction");
196 StringRef InstrName = Token.stringValue();
197 if (parseInstrName(InstrName, OpCode))
198 return error(Twine("unknown machine instruction name '") + InstrName + "'");
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000199 lex();
200 return false;
201}
202
203bool MIParser::parseRegister(unsigned &Reg) {
204 switch (Token.kind()) {
Alex Lorenz12b554e2015-06-24 17:34:58 +0000205 case MIToken::underscore:
206 Reg = 0;
207 break;
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000208 case MIToken::NamedRegister: {
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000209 StringRef Name = Token.stringValue();
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000210 if (getRegisterByName(Name, Reg))
211 return error(Twine("unknown register name '") + Name + "'");
212 break;
213 }
214 // TODO: Parse other register kinds.
215 default:
216 llvm_unreachable("The current token should be a register");
217 }
218 return false;
219}
220
221bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
222 unsigned Reg;
223 // TODO: Parse register flags.
224 if (parseRegister(Reg))
225 return true;
226 lex();
227 // TODO: Parse subregister.
228 Dest = MachineOperand::CreateReg(Reg, IsDef);
229 return false;
230}
231
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000232bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
233 assert(Token.is(MIToken::IntegerLiteral));
234 const APSInt &Int = Token.integerValue();
235 if (Int.getMinSignedBits() > 64)
236 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
237 llvm_unreachable("Can't parse large integer literals yet!");
238 Dest = MachineOperand::CreateImm(Int.getExtValue());
239 lex();
240 return false;
241}
242
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000243bool MIParser::getUnsigned(unsigned &Result) {
244 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
245 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
246 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
247 if (Val64 == Limit)
248 return error("expected 32-bit integer (too large)");
249 Result = Val64;
250 return false;
251}
252
253bool MIParser::parseMBBOperand(MachineOperand &Dest) {
254 assert(Token.is(MIToken::MachineBasicBlock));
255 unsigned Number;
256 if (getUnsigned(Number))
257 return true;
258 auto MBBInfo = MBBSlots.find(Number);
259 if (MBBInfo == MBBSlots.end())
260 return error(Twine("use of undefined machine basic block #") +
261 Twine(Number));
262 MachineBasicBlock *MBB = MBBInfo->second;
263 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
264 return error(Twine("the name of machine basic block #") + Twine(Number) +
265 " isn't '" + Token.stringValue() + "'");
266 Dest = MachineOperand::CreateMBB(MBB);
267 lex();
268 return false;
269}
270
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000271bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
272 switch (Token.kind()) {
273 case MIToken::NamedGlobalValue: {
274 auto Name = Token.stringValue();
275 const Module *M = MF.getFunction()->getParent();
276 if (const auto *GV = M->getNamedValue(Name)) {
277 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
278 break;
279 }
280 return error(Twine("use of undefined global value '@") + Name + "'");
281 }
282 case MIToken::GlobalValue: {
283 unsigned GVIdx;
284 if (getUnsigned(GVIdx))
285 return true;
286 if (GVIdx >= IRSlots.GlobalValues.size())
287 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
288 "'");
289 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
290 /*Offset=*/0);
291 break;
292 }
293 default:
294 llvm_unreachable("The current token should be a global value");
295 }
296 // TODO: Parse offset and target flags.
297 lex();
298 return false;
299}
300
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000301bool MIParser::parseMachineOperand(MachineOperand &Dest) {
302 switch (Token.kind()) {
Alex Lorenz12b554e2015-06-24 17:34:58 +0000303 case MIToken::underscore:
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000304 case MIToken::NamedRegister:
305 return parseRegisterOperand(Dest);
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000306 case MIToken::IntegerLiteral:
307 return parseImmediateOperand(Dest);
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000308 case MIToken::MachineBasicBlock:
309 return parseMBBOperand(Dest);
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000310 case MIToken::GlobalValue:
311 case MIToken::NamedGlobalValue:
312 return parseGlobalAddressOperand(Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000313 case MIToken::Error:
314 return true;
Alex Lorenz8f6f4282015-06-29 16:57:06 +0000315 case MIToken::Identifier:
316 if (const auto *RegMask = getRegMask(Token.stringValue())) {
317 Dest = MachineOperand::CreateRegMask(RegMask);
318 lex();
319 break;
320 }
321 // fallthrough
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000322 default:
323 // TODO: parse the other machine operands.
324 return error("expected a machine operand");
325 }
Alex Lorenz91370c52015-06-22 20:37:46 +0000326 return false;
327}
328
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000329void MIParser::initNames2InstrOpCodes() {
330 if (!Names2InstrOpCodes.empty())
331 return;
332 const auto *TII = MF.getSubtarget().getInstrInfo();
333 assert(TII && "Expected target instruction info");
334 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
335 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
336}
337
338bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
339 initNames2InstrOpCodes();
340 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
341 if (InstrInfo == Names2InstrOpCodes.end())
342 return true;
343 OpCode = InstrInfo->getValue();
344 return false;
345}
346
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000347void MIParser::initNames2Regs() {
348 if (!Names2Regs.empty())
349 return;
Alex Lorenz12b554e2015-06-24 17:34:58 +0000350 // The '%noreg' register is the register 0.
351 Names2Regs.insert(std::make_pair("noreg", 0));
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000352 const auto *TRI = MF.getSubtarget().getRegisterInfo();
353 assert(TRI && "Expected target register info");
354 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
355 bool WasInserted =
356 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
357 .second;
358 (void)WasInserted;
359 assert(WasInserted && "Expected registers to be unique case-insensitively");
360 }
361}
362
363bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
364 initNames2Regs();
365 auto RegInfo = Names2Regs.find(RegName);
366 if (RegInfo == Names2Regs.end())
367 return true;
368 Reg = RegInfo->getValue();
369 return false;
370}
371
Alex Lorenz8f6f4282015-06-29 16:57:06 +0000372void MIParser::initNames2RegMasks() {
373 if (!Names2RegMasks.empty())
374 return;
375 const auto *TRI = MF.getSubtarget().getRegisterInfo();
376 assert(TRI && "Expected target register info");
377 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
378 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
379 assert(RegMasks.size() == RegMaskNames.size());
380 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
381 Names2RegMasks.insert(
382 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
383}
384
385const uint32_t *MIParser::getRegMask(StringRef Identifier) {
386 initNames2RegMasks();
387 auto RegMaskInfo = Names2RegMasks.find(Identifier);
388 if (RegMaskInfo == Names2RegMasks.end())
389 return nullptr;
390 return RegMaskInfo->getValue();
391}
392
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000393MachineInstr *
394llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
395 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000396 const SlotMapping &IRSlots, SMDiagnostic &Error) {
397 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse();
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000398}