1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the parsing of machine instructions.
12 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/AsmParser/SlotMapping.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
35 StringRef Source, CurrentSource;
37 /// Maps from basic block numbers to MBBs.
38 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
39 /// Maps from indices to unnamed global values and metadata nodes.
40 const SlotMapping &IRSlots;
41 /// Maps from instruction names to op codes.
42 StringMap<unsigned> Names2InstrOpCodes;
43 /// Maps from register names to registers.
44 StringMap<unsigned> Names2Regs;
47 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
49 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
50 const SlotMapping &IRSlots);
54 /// Report an error at the current location with the given message.
56 /// This function always return true.
57 bool error(const Twine &Msg);
59 /// Report an error at the given location with the given message.
61 /// This function always return true.
62 bool error(StringRef::iterator Loc, const Twine &Msg);
64 MachineInstr *parse();
66 bool parseRegister(unsigned &Reg);
67 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
68 bool parseImmediateOperand(MachineOperand &Dest);
69 bool parseMBBOperand(MachineOperand &Dest);
70 bool parseGlobalAddressOperand(MachineOperand &Dest);
71 bool parseMachineOperand(MachineOperand &Dest);
74 /// Convert the integer literal in the current token into an unsigned integer.
76 /// Return true if an error occurred.
77 bool getUnsigned(unsigned &Result);
79 void initNames2InstrOpCodes();
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);
85 bool parseInstruction(unsigned &OpCode);
87 void initNames2Regs();
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);
94 } // end anonymous namespace
96 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
98 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
99 const SlotMapping &IRSlots)
100 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
101 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
104 void MIParser::lex() {
105 CurrentSource = lexMIToken(
106 CurrentSource, Token,
107 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
110 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
112 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
113 // TODO: Get the proper location in the MIR file, not just a location inside
115 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
116 Error = SMDiagnostic(
118 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
119 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
123 MachineInstr *MIParser::parse() {
126 // 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))
133 Operands.push_back(MO);
134 if (Token.isNot(MIToken::equal)) {
135 error("expected '='");
142 if (Token.isError() || parseInstruction(OpCode))
145 // TODO: Parse the instruction flags and memory operands.
147 // Parse the remaining machine operands.
148 while (Token.isNot(MIToken::Eof)) {
149 if (parseMachineOperand(MO))
151 Operands.push_back(MO);
152 if (Token.is(MIToken::Eof))
154 if (Token.isNot(MIToken::comma)) {
155 error("expected ',' before the next machine operand");
161 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
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())
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();
175 // TODO: Determine the implicit behaviour when implicit register flags are
177 auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
178 for (const auto &Operand : Operands)
179 MI->addOperand(MF, Operand);
183 bool 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 + "'");
193 bool MIParser::parseRegister(unsigned &Reg) {
194 switch (Token.kind()) {
195 case MIToken::underscore:
198 case MIToken::NamedRegister: {
199 StringRef Name = Token.stringValue();
200 if (getRegisterByName(Name, Reg))
201 return error(Twine("unknown register name '") + Name + "'");
204 // TODO: Parse other register kinds.
206 llvm_unreachable("The current token should be a register");
211 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
213 // TODO: Parse register flags.
214 if (parseRegister(Reg))
217 // TODO: Parse subregister.
218 Dest = MachineOperand::CreateReg(Reg, IsDef);
222 bool 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());
233 bool 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);
238 return error("expected 32-bit integer (too large)");
243 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
244 assert(Token.is(MIToken::MachineBasicBlock));
246 if (getUnsigned(Number))
248 auto MBBInfo = MBBSlots.find(Number);
249 if (MBBInfo == MBBSlots.end())
250 return error(Twine("use of undefined machine basic block #") +
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);
261 bool 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);
270 return error(Twine("use of undefined global value '@") + Name + "'");
272 case MIToken::GlobalValue: {
274 if (getUnsigned(GVIdx))
276 if (GVIdx >= IRSlots.GlobalValues.size())
277 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
279 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
284 llvm_unreachable("The current token should be a global value");
286 // TODO: Parse offset and target flags.
291 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
292 switch (Token.kind()) {
293 case MIToken::underscore:
294 case MIToken::NamedRegister:
295 return parseRegisterOperand(Dest);
296 case MIToken::IntegerLiteral:
297 return parseImmediateOperand(Dest);
298 case MIToken::MachineBasicBlock:
299 return parseMBBOperand(Dest);
300 case MIToken::GlobalValue:
301 case MIToken::NamedGlobalValue:
302 return parseGlobalAddressOperand(Dest);
306 // TODO: parse the other machine operands.
307 return error("expected a machine operand");
312 void MIParser::initNames2InstrOpCodes() {
313 if (!Names2InstrOpCodes.empty())
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));
321 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
322 initNames2InstrOpCodes();
323 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
324 if (InstrInfo == Names2InstrOpCodes.end())
326 OpCode = InstrInfo->getValue();
330 void MIParser::initNames2Regs() {
331 if (!Names2Regs.empty())
333 // The '%noreg' register is the register 0.
334 Names2Regs.insert(std::make_pair("noreg", 0));
335 const auto *TRI = MF.getSubtarget().getRegisterInfo();
336 assert(TRI && "Expected target register info");
337 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
339 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
342 assert(WasInserted && "Expected registers to be unique case-insensitively");
346 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
348 auto RegInfo = Names2Regs.find(RegName);
349 if (RegInfo == Names2Regs.end())
351 Reg = RegInfo->getValue();
356 llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
357 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
358 const SlotMapping &IRSlots, SMDiagnostic &Error) {
359 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse();