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/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
34 /// A wrapper struct around the 'MachineOperand' struct that includes a source
36 struct MachineOperandWithLocation {
37 MachineOperand Operand;
38 StringRef::iterator Begin;
39 StringRef::iterator End;
41 MachineOperandWithLocation(const MachineOperand &Operand,
42 StringRef::iterator Begin, StringRef::iterator End)
43 : Operand(Operand), Begin(Begin), End(End) {}
50 StringRef Source, CurrentSource;
52 const PerFunctionMIParsingState &PFS;
53 /// Maps from indices to unnamed global values and metadata nodes.
54 const SlotMapping &IRSlots;
55 /// Maps from instruction names to op codes.
56 StringMap<unsigned> Names2InstrOpCodes;
57 /// Maps from register names to registers.
58 StringMap<unsigned> Names2Regs;
59 /// Maps from register mask names to register masks.
60 StringMap<const uint32_t *> Names2RegMasks;
61 /// Maps from subregister names to subregister indices.
62 StringMap<unsigned> Names2SubRegIndices;
65 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
66 StringRef Source, const PerFunctionMIParsingState &PFS,
67 const SlotMapping &IRSlots);
71 /// Report an error at the current location with the given message.
73 /// This function always return true.
74 bool error(const Twine &Msg);
76 /// Report an error at the given location with the given message.
78 /// This function always return true.
79 bool error(StringRef::iterator Loc, const Twine &Msg);
81 bool parse(MachineInstr *&MI);
82 bool parseMBB(MachineBasicBlock *&MBB);
83 bool parseNamedRegister(unsigned &Reg);
85 bool parseRegister(unsigned &Reg);
86 bool parseRegisterFlag(unsigned &Flags);
87 bool parseSubRegisterIndex(unsigned &SubReg);
88 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
89 bool parseImmediateOperand(MachineOperand &Dest);
90 bool parseMBBReference(MachineBasicBlock *&MBB);
91 bool parseMBBOperand(MachineOperand &Dest);
92 bool parseStackObjectOperand(MachineOperand &Dest);
93 bool parseFixedStackObjectOperand(MachineOperand &Dest);
94 bool parseGlobalAddressOperand(MachineOperand &Dest);
95 bool parseJumpTableIndexOperand(MachineOperand &Dest);
96 bool parseMachineOperand(MachineOperand &Dest);
99 /// Convert the integer literal in the current token into an unsigned integer.
101 /// Return true if an error occurred.
102 bool getUnsigned(unsigned &Result);
104 void initNames2InstrOpCodes();
106 /// Try to convert an instruction name to an opcode. Return true if the
107 /// instruction name is invalid.
108 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
110 bool parseInstruction(unsigned &OpCode);
112 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
113 const MCInstrDesc &MCID);
115 void initNames2Regs();
117 /// Try to convert a register name to a register number. Return true if the
118 /// register name is invalid.
119 bool getRegisterByName(StringRef RegName, unsigned &Reg);
121 void initNames2RegMasks();
123 /// Check if the given identifier is a name of a register mask.
125 /// Return null if the identifier isn't a register mask.
126 const uint32_t *getRegMask(StringRef Identifier);
128 void initNames2SubRegIndices();
130 /// Check if the given identifier is a name of a subregister index.
132 /// Return 0 if the name isn't a subregister index class.
133 unsigned getSubRegIndex(StringRef Name);
136 } // end anonymous namespace
138 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
139 StringRef Source, const PerFunctionMIParsingState &PFS,
140 const SlotMapping &IRSlots)
141 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
142 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
144 void MIParser::lex() {
145 CurrentSource = lexMIToken(
146 CurrentSource, Token,
147 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
150 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
152 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
153 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
154 Error = SMDiagnostic(
156 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
157 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
161 bool MIParser::parse(MachineInstr *&MI) {
164 // Parse any register operands before '='
165 // TODO: Allow parsing of multiple operands before '='
166 MachineOperand MO = MachineOperand::CreateImm(0);
167 SmallVector<MachineOperandWithLocation, 8> Operands;
168 if (Token.isRegister() || Token.isRegisterFlag()) {
169 auto Loc = Token.location();
170 if (parseRegisterOperand(MO, /*IsDef=*/true))
172 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
173 if (Token.isNot(MIToken::equal))
174 return error("expected '='");
179 if (Token.isError() || parseInstruction(OpCode))
182 // TODO: Parse the instruction flags and memory operands.
184 // Parse the remaining machine operands.
185 while (Token.isNot(MIToken::Eof)) {
186 auto Loc = Token.location();
187 if (parseMachineOperand(MO))
189 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
190 if (Token.is(MIToken::Eof))
192 if (Token.isNot(MIToken::comma))
193 return error("expected ',' before the next machine operand");
197 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
198 if (!MCID.isVariadic()) {
199 // FIXME: Move the implicit operand verification to the machine verifier.
200 if (verifyImplicitOperands(Operands, MCID))
204 // TODO: Check for extraneous machine operands.
205 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
206 for (const auto &Operand : Operands)
207 MI->addOperand(MF, Operand.Operand);
211 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
213 if (Token.isNot(MIToken::MachineBasicBlock))
214 return error("expected a machine basic block reference");
215 if (parseMBBReference(MBB))
218 if (Token.isNot(MIToken::Eof))
220 "expected end of string after the machine basic block reference");
224 bool MIParser::parseNamedRegister(unsigned &Reg) {
226 if (Token.isNot(MIToken::NamedRegister))
227 return error("expected a named register");
228 if (parseRegister(Reg))
231 if (Token.isNot(MIToken::Eof))
232 return error("expected end of string after the register reference");
236 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
237 assert(MO.isImplicit());
238 return MO.isDef() ? "implicit-def" : "implicit";
241 static std::string getRegisterName(const TargetRegisterInfo *TRI,
243 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
244 return StringRef(TRI->getName(Reg)).lower();
247 bool MIParser::verifyImplicitOperands(
248 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
250 // We can't verify call instructions as they can contain arbitrary implicit
251 // register and register mask operands.
254 // Gather all the expected implicit operands.
255 SmallVector<MachineOperand, 4> ImplicitOperands;
256 if (MCID.ImplicitDefs)
257 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
258 ImplicitOperands.push_back(
259 MachineOperand::CreateReg(*ImpDefs, true, true));
260 if (MCID.ImplicitUses)
261 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
262 ImplicitOperands.push_back(
263 MachineOperand::CreateReg(*ImpUses, false, true));
265 const auto *TRI = MF.getSubtarget().getRegisterInfo();
266 assert(TRI && "Expected target register info");
267 size_t I = ImplicitOperands.size(), J = Operands.size();
272 const auto &ImplicitOperand = ImplicitOperands[I];
273 const auto &Operand = Operands[J].Operand;
274 if (ImplicitOperand.isIdenticalTo(Operand))
276 if (Operand.isReg() && Operand.isImplicit()) {
277 return error(Operands[J].Begin,
278 Twine("expected an implicit register operand '") +
279 printImplicitRegisterFlag(ImplicitOperand) + " %" +
280 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
283 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
284 // insead of reporting an error at this location:
287 // report the error at the following location:
290 return error(J < Operands.size() ? Operands[J].End : Token.location(),
291 Twine("missing implicit register operand '") +
292 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
293 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
298 bool MIParser::parseInstruction(unsigned &OpCode) {
299 if (Token.isNot(MIToken::Identifier))
300 return error("expected a machine instruction");
301 StringRef InstrName = Token.stringValue();
302 if (parseInstrName(InstrName, OpCode))
303 return error(Twine("unknown machine instruction name '") + InstrName + "'");
308 bool MIParser::parseRegister(unsigned &Reg) {
309 switch (Token.kind()) {
310 case MIToken::underscore:
313 case MIToken::NamedRegister: {
314 StringRef Name = Token.stringValue();
315 if (getRegisterByName(Name, Reg))
316 return error(Twine("unknown register name '") + Name + "'");
319 case MIToken::VirtualRegister: {
323 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
324 if (RegInfo == PFS.VirtualRegisterSlots.end())
325 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
327 Reg = RegInfo->second;
330 // TODO: Parse other register kinds.
332 llvm_unreachable("The current token should be a register");
337 bool MIParser::parseRegisterFlag(unsigned &Flags) {
338 switch (Token.kind()) {
339 case MIToken::kw_implicit:
340 Flags |= RegState::Implicit;
342 case MIToken::kw_implicit_define:
343 Flags |= RegState::ImplicitDefine;
345 case MIToken::kw_dead:
346 Flags |= RegState::Dead;
348 case MIToken::kw_killed:
349 Flags |= RegState::Kill;
351 case MIToken::kw_undef:
352 Flags |= RegState::Undef;
354 // TODO: report an error when we specify the same flag more than once.
355 // TODO: parse the other register flags.
357 llvm_unreachable("The current token should be a register flag");
363 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
364 assert(Token.is(MIToken::colon));
366 if (Token.isNot(MIToken::Identifier))
367 return error("expected a subregister index after ':'");
368 auto Name = Token.stringValue();
369 SubReg = getSubRegIndex(Name);
371 return error(Twine("use of unknown subregister index '") + Name + "'");
376 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
378 unsigned Flags = IsDef ? RegState::Define : 0;
379 while (Token.isRegisterFlag()) {
380 if (parseRegisterFlag(Flags))
383 if (!Token.isRegister())
384 return error("expected a register after register flags");
385 if (parseRegister(Reg))
389 if (Token.is(MIToken::colon)) {
390 if (parseSubRegisterIndex(SubReg))
393 Dest = MachineOperand::CreateReg(
394 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
395 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
396 /*isEarlyClobber=*/false, SubReg);
400 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
401 assert(Token.is(MIToken::IntegerLiteral));
402 const APSInt &Int = Token.integerValue();
403 if (Int.getMinSignedBits() > 64)
404 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
405 llvm_unreachable("Can't parse large integer literals yet!");
406 Dest = MachineOperand::CreateImm(Int.getExtValue());
411 bool MIParser::getUnsigned(unsigned &Result) {
412 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
413 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
414 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
416 return error("expected 32-bit integer (too large)");
421 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
422 assert(Token.is(MIToken::MachineBasicBlock));
424 if (getUnsigned(Number))
426 auto MBBInfo = PFS.MBBSlots.find(Number);
427 if (MBBInfo == PFS.MBBSlots.end())
428 return error(Twine("use of undefined machine basic block #") +
430 MBB = MBBInfo->second;
431 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
432 return error(Twine("the name of machine basic block #") + Twine(Number) +
433 " isn't '" + Token.stringValue() + "'");
437 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
438 MachineBasicBlock *MBB;
439 if (parseMBBReference(MBB))
441 Dest = MachineOperand::CreateMBB(MBB);
446 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
447 assert(Token.is(MIToken::StackObject));
451 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
452 if (ObjectInfo == PFS.StackObjectSlots.end())
453 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
456 if (const auto *Alloca =
457 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
458 Name = Alloca->getName();
459 if (!Token.stringValue().empty() && Token.stringValue() != Name)
460 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
461 "' isn't '" + Token.stringValue() + "'");
463 Dest = MachineOperand::CreateFI(ObjectInfo->second);
467 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
468 assert(Token.is(MIToken::FixedStackObject));
472 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
473 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
474 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
477 Dest = MachineOperand::CreateFI(ObjectInfo->second);
481 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
482 switch (Token.kind()) {
483 case MIToken::NamedGlobalValue: {
484 auto Name = Token.stringValue();
485 const Module *M = MF.getFunction()->getParent();
486 if (const auto *GV = M->getNamedValue(Name)) {
487 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
490 return error(Twine("use of undefined global value '@") + Name + "'");
492 case MIToken::GlobalValue: {
494 if (getUnsigned(GVIdx))
496 if (GVIdx >= IRSlots.GlobalValues.size())
497 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
499 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
504 llvm_unreachable("The current token should be a global value");
506 // TODO: Parse offset and target flags.
511 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
512 assert(Token.is(MIToken::JumpTableIndex));
516 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
517 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
518 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
520 // TODO: Parse target flags.
521 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
525 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
526 switch (Token.kind()) {
527 case MIToken::kw_implicit:
528 case MIToken::kw_implicit_define:
529 case MIToken::kw_dead:
530 case MIToken::kw_killed:
531 case MIToken::kw_undef:
532 case MIToken::underscore:
533 case MIToken::NamedRegister:
534 case MIToken::VirtualRegister:
535 return parseRegisterOperand(Dest);
536 case MIToken::IntegerLiteral:
537 return parseImmediateOperand(Dest);
538 case MIToken::MachineBasicBlock:
539 return parseMBBOperand(Dest);
540 case MIToken::StackObject:
541 return parseStackObjectOperand(Dest);
542 case MIToken::FixedStackObject:
543 return parseFixedStackObjectOperand(Dest);
544 case MIToken::GlobalValue:
545 case MIToken::NamedGlobalValue:
546 return parseGlobalAddressOperand(Dest);
547 case MIToken::JumpTableIndex:
548 return parseJumpTableIndexOperand(Dest);
551 case MIToken::Identifier:
552 if (const auto *RegMask = getRegMask(Token.stringValue())) {
553 Dest = MachineOperand::CreateRegMask(RegMask);
559 // TODO: parse the other machine operands.
560 return error("expected a machine operand");
565 void MIParser::initNames2InstrOpCodes() {
566 if (!Names2InstrOpCodes.empty())
568 const auto *TII = MF.getSubtarget().getInstrInfo();
569 assert(TII && "Expected target instruction info");
570 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
571 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
574 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
575 initNames2InstrOpCodes();
576 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
577 if (InstrInfo == Names2InstrOpCodes.end())
579 OpCode = InstrInfo->getValue();
583 void MIParser::initNames2Regs() {
584 if (!Names2Regs.empty())
586 // The '%noreg' register is the register 0.
587 Names2Regs.insert(std::make_pair("noreg", 0));
588 const auto *TRI = MF.getSubtarget().getRegisterInfo();
589 assert(TRI && "Expected target register info");
590 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
592 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
595 assert(WasInserted && "Expected registers to be unique case-insensitively");
599 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
601 auto RegInfo = Names2Regs.find(RegName);
602 if (RegInfo == Names2Regs.end())
604 Reg = RegInfo->getValue();
608 void MIParser::initNames2RegMasks() {
609 if (!Names2RegMasks.empty())
611 const auto *TRI = MF.getSubtarget().getRegisterInfo();
612 assert(TRI && "Expected target register info");
613 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
614 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
615 assert(RegMasks.size() == RegMaskNames.size());
616 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
617 Names2RegMasks.insert(
618 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
621 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
622 initNames2RegMasks();
623 auto RegMaskInfo = Names2RegMasks.find(Identifier);
624 if (RegMaskInfo == Names2RegMasks.end())
626 return RegMaskInfo->getValue();
629 void MIParser::initNames2SubRegIndices() {
630 if (!Names2SubRegIndices.empty())
632 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
633 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
634 Names2SubRegIndices.insert(
635 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
638 unsigned MIParser::getSubRegIndex(StringRef Name) {
639 initNames2SubRegIndices();
640 auto SubRegInfo = Names2SubRegIndices.find(Name);
641 if (SubRegInfo == Names2SubRegIndices.end())
643 return SubRegInfo->getValue();
646 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
647 MachineFunction &MF, StringRef Src,
648 const PerFunctionMIParsingState &PFS,
649 const SlotMapping &IRSlots, SMDiagnostic &Error) {
650 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
653 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
654 MachineFunction &MF, StringRef Src,
655 const PerFunctionMIParsingState &PFS,
656 const SlotMapping &IRSlots, SMDiagnostic &Error) {
657 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseMBB(MBB);
660 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
661 MachineFunction &MF, StringRef Src,
662 const PerFunctionMIParsingState &PFS,
663 const SlotMapping &IRSlots,
664 SMDiagnostic &Error) {
665 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseNamedRegister(Reg);