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;
45 /// Maps from register mask names to register masks.
46 StringMap<const uint32_t *> Names2RegMasks;
49 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
51 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
52 const SlotMapping &IRSlots);
56 /// Report an error at the current location with the given message.
58 /// This function always return true.
59 bool error(const Twine &Msg);
61 /// Report an error at the given location with the given message.
63 /// This function always return true.
64 bool error(StringRef::iterator Loc, const Twine &Msg);
66 MachineInstr *parse();
68 bool parseRegister(unsigned &Reg);
69 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
70 bool parseImmediateOperand(MachineOperand &Dest);
71 bool parseMBBOperand(MachineOperand &Dest);
72 bool parseGlobalAddressOperand(MachineOperand &Dest);
73 bool parseMachineOperand(MachineOperand &Dest);
76 /// Convert the integer literal in the current token into an unsigned integer.
78 /// Return true if an error occurred.
79 bool getUnsigned(unsigned &Result);
81 void initNames2InstrOpCodes();
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);
87 bool parseInstruction(unsigned &OpCode);
89 void initNames2Regs();
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);
95 void initNames2RegMasks();
97 /// Check if the given identifier is a name of a register mask.
99 /// Return null if the identifier isn't a register mask.
100 const uint32_t *getRegMask(StringRef Identifier);
103 } // end anonymous namespace
105 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
107 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
108 const SlotMapping &IRSlots)
109 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
110 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
113 void MIParser::lex() {
114 CurrentSource = lexMIToken(
115 CurrentSource, Token,
116 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
119 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
121 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
122 // TODO: Get the proper location in the MIR file, not just a location inside
124 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
125 Error = SMDiagnostic(
127 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
128 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
132 MachineInstr *MIParser::parse() {
135 // 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))
142 Operands.push_back(MO);
143 if (Token.isNot(MIToken::equal)) {
144 error("expected '='");
151 if (Token.isError() || parseInstruction(OpCode))
154 // TODO: Parse the instruction flags and memory operands.
156 // Parse the remaining machine operands.
157 while (Token.isNot(MIToken::Eof)) {
158 if (parseMachineOperand(MO))
160 Operands.push_back(MO);
161 if (Token.is(MIToken::Eof))
163 if (Token.isNot(MIToken::comma)) {
164 error("expected ',' before the next machine operand");
170 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
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())
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.
180 if (Operands[I].isReg())
181 Operands[I].setImplicit();
185 // TODO: Determine the implicit behaviour when implicit register flags are
187 auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
188 for (const auto &Operand : Operands)
189 MI->addOperand(MF, Operand);
193 bool 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 + "'");
203 bool MIParser::parseRegister(unsigned &Reg) {
204 switch (Token.kind()) {
205 case MIToken::underscore:
208 case MIToken::NamedRegister: {
209 StringRef Name = Token.stringValue();
210 if (getRegisterByName(Name, Reg))
211 return error(Twine("unknown register name '") + Name + "'");
214 // TODO: Parse other register kinds.
216 llvm_unreachable("The current token should be a register");
221 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
223 // TODO: Parse register flags.
224 if (parseRegister(Reg))
227 // TODO: Parse subregister.
228 Dest = MachineOperand::CreateReg(Reg, IsDef);
232 bool 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());
243 bool 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);
248 return error("expected 32-bit integer (too large)");
253 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
254 assert(Token.is(MIToken::MachineBasicBlock));
256 if (getUnsigned(Number))
258 auto MBBInfo = MBBSlots.find(Number);
259 if (MBBInfo == MBBSlots.end())
260 return error(Twine("use of undefined machine basic block #") +
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);
271 bool 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);
280 return error(Twine("use of undefined global value '@") + Name + "'");
282 case MIToken::GlobalValue: {
284 if (getUnsigned(GVIdx))
286 if (GVIdx >= IRSlots.GlobalValues.size())
287 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
289 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
294 llvm_unreachable("The current token should be a global value");
296 // TODO: Parse offset and target flags.
301 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
302 switch (Token.kind()) {
303 case MIToken::underscore:
304 case MIToken::NamedRegister:
305 return parseRegisterOperand(Dest);
306 case MIToken::IntegerLiteral:
307 return parseImmediateOperand(Dest);
308 case MIToken::MachineBasicBlock:
309 return parseMBBOperand(Dest);
310 case MIToken::GlobalValue:
311 case MIToken::NamedGlobalValue:
312 return parseGlobalAddressOperand(Dest);
315 case MIToken::Identifier:
316 if (const auto *RegMask = getRegMask(Token.stringValue())) {
317 Dest = MachineOperand::CreateRegMask(RegMask);
323 // TODO: parse the other machine operands.
324 return error("expected a machine operand");
329 void MIParser::initNames2InstrOpCodes() {
330 if (!Names2InstrOpCodes.empty())
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));
338 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
339 initNames2InstrOpCodes();
340 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
341 if (InstrInfo == Names2InstrOpCodes.end())
343 OpCode = InstrInfo->getValue();
347 void MIParser::initNames2Regs() {
348 if (!Names2Regs.empty())
350 // The '%noreg' register is the register 0.
351 Names2Regs.insert(std::make_pair("noreg", 0));
352 const auto *TRI = MF.getSubtarget().getRegisterInfo();
353 assert(TRI && "Expected target register info");
354 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
356 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
359 assert(WasInserted && "Expected registers to be unique case-insensitively");
363 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
365 auto RegInfo = Names2Regs.find(RegName);
366 if (RegInfo == Names2Regs.end())
368 Reg = RegInfo->getValue();
372 void MIParser::initNames2RegMasks() {
373 if (!Names2RegMasks.empty())
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]));
385 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
386 initNames2RegMasks();
387 auto RegMaskInfo = Names2RegMasks.find(Identifier);
388 if (RegMaskInfo == Names2RegMasks.end())
390 return RegMaskInfo->getValue();
394 llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
395 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
396 const SlotMapping &IRSlots, SMDiagnostic &Error) {
397 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse();