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/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Target/TargetSubtargetInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
33 StringRef Source, CurrentSource;
35 /// Maps from basic block numbers to MBBs.
36 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
37 /// Maps from instruction names to op codes.
38 StringMap<unsigned> Names2InstrOpCodes;
39 /// Maps from register names to registers.
40 StringMap<unsigned> Names2Regs;
43 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
45 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
49 /// Report an error at the current location with the given message.
51 /// This function always return true.
52 bool error(const Twine &Msg);
54 /// Report an error at the given location with the given message.
56 /// This function always return true.
57 bool error(StringRef::iterator Loc, const Twine &Msg);
59 MachineInstr *parse();
61 bool parseRegister(unsigned &Reg);
62 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
63 bool parseImmediateOperand(MachineOperand &Dest);
64 bool parseMBBOperand(MachineOperand &Dest);
65 bool parseMachineOperand(MachineOperand &Dest);
68 /// Convert the integer literal in the current token into an unsigned integer.
70 /// Return true if an error occurred.
71 bool getUnsigned(unsigned &Result);
73 void initNames2InstrOpCodes();
75 /// Try to convert an instruction name to an opcode. Return true if the
76 /// instruction name is invalid.
77 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
79 bool parseInstruction(unsigned &OpCode);
81 void initNames2Regs();
83 /// Try to convert a register name to a register number. Return true if the
84 /// register name is invalid.
85 bool getRegisterByName(StringRef RegName, unsigned &Reg);
88 } // end anonymous namespace
90 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
92 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots)
93 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
94 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots) {}
96 void MIParser::lex() {
97 CurrentSource = lexMIToken(
99 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
102 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
104 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
105 // TODO: Get the proper location in the MIR file, not just a location inside
107 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
108 Error = SMDiagnostic(
110 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
111 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
115 MachineInstr *MIParser::parse() {
118 // Parse any register operands before '='
119 // TODO: Allow parsing of multiple operands before '='
120 MachineOperand MO = MachineOperand::CreateImm(0);
121 SmallVector<MachineOperand, 8> Operands;
122 if (Token.isRegister()) {
123 if (parseRegisterOperand(MO, /*IsDef=*/true))
125 Operands.push_back(MO);
126 if (Token.isNot(MIToken::equal)) {
127 error("expected '='");
134 if (Token.isError() || parseInstruction(OpCode))
137 // TODO: Parse the instruction flags and memory operands.
139 // Parse the remaining machine operands.
140 while (Token.isNot(MIToken::Eof)) {
141 if (parseMachineOperand(MO))
143 Operands.push_back(MO);
144 if (Token.is(MIToken::Eof))
146 if (Token.isNot(MIToken::comma)) {
147 error("expected ',' before the next machine operand");
153 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
155 // Verify machine operands.
156 if (!MCID.isVariadic()) {
157 for (size_t I = 0, E = Operands.size(); I < E; ++I) {
158 if (I < MCID.getNumOperands())
160 // Mark this register as implicit to prevent an assertion when it's added
161 // to an instruction. This is a temporary workaround until the implicit
162 // register flag can be parsed.
163 Operands[I].setImplicit();
167 // TODO: Determine the implicit behaviour when implicit register flags are
169 auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
170 for (const auto &Operand : Operands)
171 MI->addOperand(MF, Operand);
175 bool MIParser::parseInstruction(unsigned &OpCode) {
176 if (Token.isNot(MIToken::Identifier))
177 return error("expected a machine instruction");
178 StringRef InstrName = Token.stringValue();
179 if (parseInstrName(InstrName, OpCode))
180 return error(Twine("unknown machine instruction name '") + InstrName + "'");
185 bool MIParser::parseRegister(unsigned &Reg) {
186 switch (Token.kind()) {
187 case MIToken::underscore:
190 case MIToken::NamedRegister: {
191 StringRef Name = Token.stringValue();
192 if (getRegisterByName(Name, Reg))
193 return error(Twine("unknown register name '") + Name + "'");
196 // TODO: Parse other register kinds.
198 llvm_unreachable("The current token should be a register");
203 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
205 // TODO: Parse register flags.
206 if (parseRegister(Reg))
209 // TODO: Parse subregister.
210 Dest = MachineOperand::CreateReg(Reg, IsDef);
214 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
215 assert(Token.is(MIToken::IntegerLiteral));
216 const APSInt &Int = Token.integerValue();
217 if (Int.getMinSignedBits() > 64)
218 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
219 llvm_unreachable("Can't parse large integer literals yet!");
220 Dest = MachineOperand::CreateImm(Int.getExtValue());
225 bool MIParser::getUnsigned(unsigned &Result) {
226 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
227 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
228 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
230 return error("expected 32-bit integer (too large)");
235 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
236 assert(Token.is(MIToken::MachineBasicBlock));
238 if (getUnsigned(Number))
240 auto MBBInfo = MBBSlots.find(Number);
241 if (MBBInfo == MBBSlots.end())
242 return error(Twine("use of undefined machine basic block #") +
244 MachineBasicBlock *MBB = MBBInfo->second;
245 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
246 return error(Twine("the name of machine basic block #") + Twine(Number) +
247 " isn't '" + Token.stringValue() + "'");
248 Dest = MachineOperand::CreateMBB(MBB);
253 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
254 switch (Token.kind()) {
255 case MIToken::underscore:
256 case MIToken::NamedRegister:
257 return parseRegisterOperand(Dest);
258 case MIToken::IntegerLiteral:
259 return parseImmediateOperand(Dest);
260 case MIToken::MachineBasicBlock:
261 return parseMBBOperand(Dest);
265 // TODO: parse the other machine operands.
266 return error("expected a machine operand");
271 void MIParser::initNames2InstrOpCodes() {
272 if (!Names2InstrOpCodes.empty())
274 const auto *TII = MF.getSubtarget().getInstrInfo();
275 assert(TII && "Expected target instruction info");
276 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
277 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
280 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
281 initNames2InstrOpCodes();
282 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
283 if (InstrInfo == Names2InstrOpCodes.end())
285 OpCode = InstrInfo->getValue();
289 void MIParser::initNames2Regs() {
290 if (!Names2Regs.empty())
292 // The '%noreg' register is the register 0.
293 Names2Regs.insert(std::make_pair("noreg", 0));
294 const auto *TRI = MF.getSubtarget().getRegisterInfo();
295 assert(TRI && "Expected target register info");
296 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
298 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
301 assert(WasInserted && "Expected registers to be unique case-insensitively");
305 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
307 auto RegInfo = Names2Regs.find(RegName);
308 if (RegInfo == Names2Regs.end())
310 Reg = RegInfo->getValue();
315 llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
316 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
317 SMDiagnostic &Error) {
318 return MIParser(SM, MF, Error, Src, MBBSlots).parse();