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 instruction names to op codes.
36 StringMap<unsigned> Names2InstrOpCodes;
37 /// Maps from register names to registers.
38 StringMap<unsigned> Names2Regs;
41 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
46 /// Report an error at the current location with the given message.
48 /// This function always return true.
49 bool error(const Twine &Msg);
51 /// Report an error at the given location with the given message.
53 /// This function always return true.
54 bool error(StringRef::iterator Loc, const Twine &Msg);
56 MachineInstr *parse();
58 bool parseRegister(unsigned &Reg);
59 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
60 bool parseImmediateOperand(MachineOperand &Dest);
61 bool parseMachineOperand(MachineOperand &Dest);
64 void initNames2InstrOpCodes();
66 /// Try to convert an instruction name to an opcode. Return true if the
67 /// instruction name is invalid.
68 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
70 bool parseInstruction(unsigned &OpCode);
72 void initNames2Regs();
74 /// Try to convert a register name to a register number. Return true if the
75 /// register name is invalid.
76 bool getRegisterByName(StringRef RegName, unsigned &Reg);
79 } // end anonymous namespace
81 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
83 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
84 Token(MIToken::Error, StringRef()) {}
86 void MIParser::lex() {
87 CurrentSource = lexMIToken(
89 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
92 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
94 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
95 // TODO: Get the proper location in the MIR file, not just a location inside
97 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
100 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
101 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
105 MachineInstr *MIParser::parse() {
108 // Parse any register operands before '='
109 // TODO: Allow parsing of multiple operands before '='
110 MachineOperand MO = MachineOperand::CreateImm(0);
111 SmallVector<MachineOperand, 8> Operands;
112 if (Token.isRegister()) {
113 if (parseRegisterOperand(MO, /*IsDef=*/true))
115 Operands.push_back(MO);
116 if (Token.isNot(MIToken::equal)) {
117 error("expected '='");
124 if (Token.isError() || parseInstruction(OpCode))
127 // TODO: Parse the instruction flags and memory operands.
129 // Parse the remaining machine operands.
130 while (Token.isNot(MIToken::Eof)) {
131 if (parseMachineOperand(MO))
133 Operands.push_back(MO);
134 if (Token.is(MIToken::Eof))
136 if (Token.isNot(MIToken::comma)) {
137 error("expected ',' before the next machine operand");
143 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
145 // Verify machine operands.
146 if (!MCID.isVariadic()) {
147 for (size_t I = 0, E = Operands.size(); I < E; ++I) {
148 if (I < MCID.getNumOperands())
150 // Mark this register as implicit to prevent an assertion when it's added
151 // to an instruction. This is a temporary workaround until the implicit
152 // register flag can be parsed.
153 Operands[I].setImplicit();
157 // TODO: Determine the implicit behaviour when implicit register flags are
159 auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
160 for (const auto &Operand : Operands)
161 MI->addOperand(MF, Operand);
165 bool MIParser::parseInstruction(unsigned &OpCode) {
166 if (Token.isNot(MIToken::Identifier))
167 return error("expected a machine instruction");
168 StringRef InstrName = Token.stringValue();
169 if (parseInstrName(InstrName, OpCode))
170 return error(Twine("unknown machine instruction name '") + InstrName + "'");
175 bool MIParser::parseRegister(unsigned &Reg) {
176 switch (Token.kind()) {
177 case MIToken::underscore:
180 case MIToken::NamedRegister: {
181 StringRef Name = Token.stringValue().drop_front(1); // Drop the '%'
182 if (getRegisterByName(Name, Reg))
183 return error(Twine("unknown register name '") + Name + "'");
186 // TODO: Parse other register kinds.
188 llvm_unreachable("The current token should be a register");
193 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
195 // TODO: Parse register flags.
196 if (parseRegister(Reg))
199 // TODO: Parse subregister.
200 Dest = MachineOperand::CreateReg(Reg, IsDef);
204 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
205 assert(Token.is(MIToken::IntegerLiteral));
206 const APSInt &Int = Token.integerValue();
207 if (Int.getMinSignedBits() > 64)
208 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
209 llvm_unreachable("Can't parse large integer literals yet!");
210 Dest = MachineOperand::CreateImm(Int.getExtValue());
215 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
216 switch (Token.kind()) {
217 case MIToken::underscore:
218 case MIToken::NamedRegister:
219 return parseRegisterOperand(Dest);
220 case MIToken::IntegerLiteral:
221 return parseImmediateOperand(Dest);
225 // TODO: parse the other machine operands.
226 return error("expected a machine operand");
231 void MIParser::initNames2InstrOpCodes() {
232 if (!Names2InstrOpCodes.empty())
234 const auto *TII = MF.getSubtarget().getInstrInfo();
235 assert(TII && "Expected target instruction info");
236 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
237 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
240 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
241 initNames2InstrOpCodes();
242 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
243 if (InstrInfo == Names2InstrOpCodes.end())
245 OpCode = InstrInfo->getValue();
249 void MIParser::initNames2Regs() {
250 if (!Names2Regs.empty())
252 // The '%noreg' register is the register 0.
253 Names2Regs.insert(std::make_pair("noreg", 0));
254 const auto *TRI = MF.getSubtarget().getRegisterInfo();
255 assert(TRI && "Expected target register info");
256 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
258 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
261 assert(WasInserted && "Expected registers to be unique case-insensitively");
265 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
267 auto RegInfo = Names2Regs.find(RegName);
268 if (RegInfo == Names2Regs.end())
270 Reg = RegInfo->getValue();
274 MachineInstr *llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF,
275 StringRef Src, SMDiagnostic &Error) {
276 return MIParser(SM, MF, Error, Src).parse();