blob: f30b1143a4934ffb6b9b000e0913532b0afbfe67 [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 Lorenz8e0a1b42015-06-22 17:02:30 +000045
46public:
47 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
Alex Lorenz33f0aef2015-06-26 16:46:11 +000048 StringRef Source,
Alex Lorenz5d6108e2015-06-26 22:56:48 +000049 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
50 const SlotMapping &IRSlots);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000051
Alex Lorenz91370c52015-06-22 20:37:46 +000052 void lex();
53
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000054 /// Report an error at the current location with the given message.
55 ///
56 /// This function always return true.
57 bool error(const Twine &Msg);
58
Alex Lorenz91370c52015-06-22 20:37:46 +000059 /// Report an error at the given location with the given message.
60 ///
61 /// This function always return true.
62 bool error(StringRef::iterator Loc, const Twine &Msg);
63
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000064 MachineInstr *parse();
65
Alex Lorenzf3db51de2015-06-23 16:35:26 +000066 bool parseRegister(unsigned &Reg);
67 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
Alex Lorenz240fc1e2015-06-23 23:42:28 +000068 bool parseImmediateOperand(MachineOperand &Dest);
Alex Lorenz33f0aef2015-06-26 16:46:11 +000069 bool parseMBBOperand(MachineOperand &Dest);
Alex Lorenz5d6108e2015-06-26 22:56:48 +000070 bool parseGlobalAddressOperand(MachineOperand &Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +000071 bool parseMachineOperand(MachineOperand &Dest);
72
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000073private:
Alex Lorenz33f0aef2015-06-26 16:46:11 +000074 /// Convert the integer literal in the current token into an unsigned integer.
75 ///
76 /// Return true if an error occurred.
77 bool getUnsigned(unsigned &Result);
78
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000079 void initNames2InstrOpCodes();
80
81 /// Try to convert an instruction name to an opcode. Return true if the
82 /// instruction name is invalid.
83 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
Alex Lorenz91370c52015-06-22 20:37:46 +000084
85 bool parseInstruction(unsigned &OpCode);
Alex Lorenzf3db51de2015-06-23 16:35:26 +000086
87 void initNames2Regs();
88
89 /// Try to convert a register name to a register number. Return true if the
90 /// register name is invalid.
91 bool getRegisterByName(StringRef RegName, unsigned &Reg);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000092};
93
94} // end anonymous namespace
95
96MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
Alex Lorenz33f0aef2015-06-26 16:46:11 +000097 StringRef Source,
Alex Lorenz5d6108e2015-06-26 22:56:48 +000098 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
99 const SlotMapping &IRSlots)
Alex Lorenz91370c52015-06-22 20:37:46 +0000100 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000101 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
102}
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000103
Alex Lorenz91370c52015-06-22 20:37:46 +0000104void MIParser::lex() {
105 CurrentSource = lexMIToken(
106 CurrentSource, Token,
107 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
108}
109
110bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
111
112bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000113 // TODO: Get the proper location in the MIR file, not just a location inside
114 // the string.
Alex Lorenz91370c52015-06-22 20:37:46 +0000115 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
116 Error = SMDiagnostic(
117 SM, SMLoc(),
118 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
119 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000120 return true;
121}
122
123MachineInstr *MIParser::parse() {
Alex Lorenz91370c52015-06-22 20:37:46 +0000124 lex();
125
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000126 // Parse any register operands before '='
127 // TODO: Allow parsing of multiple operands before '='
128 MachineOperand MO = MachineOperand::CreateImm(0);
129 SmallVector<MachineOperand, 8> Operands;
130 if (Token.isRegister()) {
131 if (parseRegisterOperand(MO, /*IsDef=*/true))
132 return nullptr;
133 Operands.push_back(MO);
134 if (Token.isNot(MIToken::equal)) {
135 error("expected '='");
136 return nullptr;
137 }
138 lex();
139 }
140
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000141 unsigned OpCode;
Alex Lorenz91370c52015-06-22 20:37:46 +0000142 if (Token.isError() || parseInstruction(OpCode))
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000143 return nullptr;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000144
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000145 // TODO: Parse the instruction flags and memory operands.
146
147 // Parse the remaining machine operands.
148 while (Token.isNot(MIToken::Eof)) {
149 if (parseMachineOperand(MO))
150 return nullptr;
151 Operands.push_back(MO);
152 if (Token.is(MIToken::Eof))
153 break;
154 if (Token.isNot(MIToken::comma)) {
155 error("expected ',' before the next machine operand");
156 return nullptr;
157 }
158 lex();
159 }
160
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000161 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000162
163 // Verify machine operands.
164 if (!MCID.isVariadic()) {
165 for (size_t I = 0, E = Operands.size(); I < E; ++I) {
166 if (I < MCID.getNumOperands())
167 continue;
168 // Mark this register as implicit to prevent an assertion when it's added
169 // to an instruction. This is a temporary workaround until the implicit
170 // register flag can be parsed.
171 Operands[I].setImplicit();
172 }
173 }
174
175 // TODO: Determine the implicit behaviour when implicit register flags are
176 // parsed.
177 auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
178 for (const auto &Operand : Operands)
179 MI->addOperand(MF, Operand);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000180 return MI;
181}
182
Alex Lorenz91370c52015-06-22 20:37:46 +0000183bool MIParser::parseInstruction(unsigned &OpCode) {
184 if (Token.isNot(MIToken::Identifier))
185 return error("expected a machine instruction");
186 StringRef InstrName = Token.stringValue();
187 if (parseInstrName(InstrName, OpCode))
188 return error(Twine("unknown machine instruction name '") + InstrName + "'");
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000189 lex();
190 return false;
191}
192
193bool MIParser::parseRegister(unsigned &Reg) {
194 switch (Token.kind()) {
Alex Lorenz12b554e2015-06-24 17:34:58 +0000195 case MIToken::underscore:
196 Reg = 0;
197 break;
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000198 case MIToken::NamedRegister: {
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000199 StringRef Name = Token.stringValue();
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000200 if (getRegisterByName(Name, Reg))
201 return error(Twine("unknown register name '") + Name + "'");
202 break;
203 }
204 // TODO: Parse other register kinds.
205 default:
206 llvm_unreachable("The current token should be a register");
207 }
208 return false;
209}
210
211bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
212 unsigned Reg;
213 // TODO: Parse register flags.
214 if (parseRegister(Reg))
215 return true;
216 lex();
217 // TODO: Parse subregister.
218 Dest = MachineOperand::CreateReg(Reg, IsDef);
219 return false;
220}
221
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000222bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
223 assert(Token.is(MIToken::IntegerLiteral));
224 const APSInt &Int = Token.integerValue();
225 if (Int.getMinSignedBits() > 64)
226 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
227 llvm_unreachable("Can't parse large integer literals yet!");
228 Dest = MachineOperand::CreateImm(Int.getExtValue());
229 lex();
230 return false;
231}
232
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000233bool MIParser::getUnsigned(unsigned &Result) {
234 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
235 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
236 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
237 if (Val64 == Limit)
238 return error("expected 32-bit integer (too large)");
239 Result = Val64;
240 return false;
241}
242
243bool MIParser::parseMBBOperand(MachineOperand &Dest) {
244 assert(Token.is(MIToken::MachineBasicBlock));
245 unsigned Number;
246 if (getUnsigned(Number))
247 return true;
248 auto MBBInfo = MBBSlots.find(Number);
249 if (MBBInfo == MBBSlots.end())
250 return error(Twine("use of undefined machine basic block #") +
251 Twine(Number));
252 MachineBasicBlock *MBB = MBBInfo->second;
253 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
254 return error(Twine("the name of machine basic block #") + Twine(Number) +
255 " isn't '" + Token.stringValue() + "'");
256 Dest = MachineOperand::CreateMBB(MBB);
257 lex();
258 return false;
259}
260
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000261bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
262 switch (Token.kind()) {
263 case MIToken::NamedGlobalValue: {
264 auto Name = Token.stringValue();
265 const Module *M = MF.getFunction()->getParent();
266 if (const auto *GV = M->getNamedValue(Name)) {
267 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
268 break;
269 }
270 return error(Twine("use of undefined global value '@") + Name + "'");
271 }
272 case MIToken::GlobalValue: {
273 unsigned GVIdx;
274 if (getUnsigned(GVIdx))
275 return true;
276 if (GVIdx >= IRSlots.GlobalValues.size())
277 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
278 "'");
279 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
280 /*Offset=*/0);
281 break;
282 }
283 default:
284 llvm_unreachable("The current token should be a global value");
285 }
286 // TODO: Parse offset and target flags.
287 lex();
288 return false;
289}
290
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000291bool MIParser::parseMachineOperand(MachineOperand &Dest) {
292 switch (Token.kind()) {
Alex Lorenz12b554e2015-06-24 17:34:58 +0000293 case MIToken::underscore:
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000294 case MIToken::NamedRegister:
295 return parseRegisterOperand(Dest);
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000296 case MIToken::IntegerLiteral:
297 return parseImmediateOperand(Dest);
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000298 case MIToken::MachineBasicBlock:
299 return parseMBBOperand(Dest);
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000300 case MIToken::GlobalValue:
301 case MIToken::NamedGlobalValue:
302 return parseGlobalAddressOperand(Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000303 case MIToken::Error:
304 return true;
305 default:
306 // TODO: parse the other machine operands.
307 return error("expected a machine operand");
308 }
Alex Lorenz91370c52015-06-22 20:37:46 +0000309 return false;
310}
311
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000312void MIParser::initNames2InstrOpCodes() {
313 if (!Names2InstrOpCodes.empty())
314 return;
315 const auto *TII = MF.getSubtarget().getInstrInfo();
316 assert(TII && "Expected target instruction info");
317 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
318 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
319}
320
321bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
322 initNames2InstrOpCodes();
323 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
324 if (InstrInfo == Names2InstrOpCodes.end())
325 return true;
326 OpCode = InstrInfo->getValue();
327 return false;
328}
329
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000330void MIParser::initNames2Regs() {
331 if (!Names2Regs.empty())
332 return;
Alex Lorenz12b554e2015-06-24 17:34:58 +0000333 // The '%noreg' register is the register 0.
334 Names2Regs.insert(std::make_pair("noreg", 0));
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000335 const auto *TRI = MF.getSubtarget().getRegisterInfo();
336 assert(TRI && "Expected target register info");
337 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
338 bool WasInserted =
339 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
340 .second;
341 (void)WasInserted;
342 assert(WasInserted && "Expected registers to be unique case-insensitively");
343 }
344}
345
346bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
347 initNames2Regs();
348 auto RegInfo = Names2Regs.find(RegName);
349 if (RegInfo == Names2Regs.end())
350 return true;
351 Reg = RegInfo->getValue();
352 return false;
353}
354
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000355MachineInstr *
356llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
357 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000358 const SlotMapping &IRSlots, SMDiagnostic &Error) {
359 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse();
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000360}