1 //===-- MipsAsmParser.cpp - Parse Mips assembly to MCInst instructions ----===//
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 #include "MCTargetDesc/MipsMCTargetDesc.h"
11 #include "MipsRegisterInfo.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCSubtargetInfo.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCParser/MCAsmLexer.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/MC/MCTargetAsmParser.h"
22 #include "llvm/Support/TargetRegistry.h"
28 class MipsAsmParser : public MCTargetAsmParser {
33 #define GET_ASSEMBLER_HEADER
34 #include "MipsGenAsmMatcher.inc"
36 bool MatchAndEmitInstruction(SMLoc IDLoc,
37 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
40 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
42 bool ParseInstruction(StringRef Name, SMLoc NameLoc,
43 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
45 bool ParseDirective(AsmToken DirectiveID);
47 MipsAsmParser::OperandMatchResultTy
48 parseMemOperand(SmallVectorImpl<MCParsedAsmOperand*>&);
51 getMCInstOperandNum(unsigned Kind, MCInst &Inst,
52 const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
53 unsigned OperandNum, unsigned &NumMCOperands);
55 bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &,
58 int tryParseRegister(StringRef Mnemonic);
60 bool tryParseRegisterOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
63 bool parseMemOffset(const MCExpr *&Res);
64 bool parseRelocOperand(const MCExpr *&Res);
65 MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
66 bool isMips64() const {
67 return (STI.getFeatureBits() & Mips::FeatureMips64) != 0;
70 int matchRegisterName(StringRef Symbol);
72 int matchRegisterByNumber(unsigned RegNum, StringRef Mnemonic);
74 unsigned getReg(int RC,int RegNo);
77 MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
78 : MCTargetAsmParser(), STI(sti), Parser(parser) {
79 // Initialize the set of available features.
80 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
83 MCAsmParser &getParser() const { return Parser; }
84 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
91 /// MipsOperand - Instances of this class represent a parsed Mips machine
93 class MipsOperand : public MCParsedAsmOperand {
105 MipsOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
127 SMLoc StartLoc, EndLoc;
130 void addRegOperands(MCInst &Inst, unsigned N) const {
131 assert(N == 1 && "Invalid number of operands!");
132 Inst.addOperand(MCOperand::CreateReg(getReg()));
135 void addExpr(MCInst &Inst, const MCExpr *Expr) const{
136 // Add as immediate when possible. Null MCExpr = 0.
138 Inst.addOperand(MCOperand::CreateImm(0));
139 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
140 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
142 Inst.addOperand(MCOperand::CreateExpr(Expr));
145 void addImmOperands(MCInst &Inst, unsigned N) const {
146 assert(N == 1 && "Invalid number of operands!");
147 const MCExpr *Expr = getImm();
151 void addMemOperands(MCInst &Inst, unsigned N) const {
152 assert(N == 2 && "Invalid number of operands!");
154 Inst.addOperand(MCOperand::CreateReg(getMemBase()));
156 const MCExpr *Expr = getMemOff();
160 bool isReg() const { return Kind == k_Register; }
161 bool isImm() const { return Kind == k_Immediate; }
162 bool isToken() const { return Kind == k_Token; }
163 bool isMem() const { return Kind == k_Memory; }
165 StringRef getToken() const {
166 assert(Kind == k_Token && "Invalid access!");
167 return StringRef(Tok.Data, Tok.Length);
170 unsigned getReg() const {
171 assert((Kind == k_Register) && "Invalid access!");
175 const MCExpr *getImm() const {
176 assert((Kind == k_Immediate) && "Invalid access!");
180 unsigned getMemBase() const {
181 assert((Kind == k_Memory) && "Invalid access!");
185 const MCExpr *getMemOff() const {
186 assert((Kind == k_Memory) && "Invalid access!");
190 static MipsOperand *CreateToken(StringRef Str, SMLoc S) {
191 MipsOperand *Op = new MipsOperand(k_Token);
192 Op->Tok.Data = Str.data();
193 Op->Tok.Length = Str.size();
199 static MipsOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
200 MipsOperand *Op = new MipsOperand(k_Register);
201 Op->Reg.RegNum = RegNum;
207 static MipsOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
208 MipsOperand *Op = new MipsOperand(k_Immediate);
215 static MipsOperand *CreateMem(unsigned Base, const MCExpr *Off,
217 MipsOperand *Op = new MipsOperand(k_Memory);
225 /// getStartLoc - Get the location of the first token of this operand.
226 SMLoc getStartLoc() const { return StartLoc; }
227 /// getEndLoc - Get the location of the last token of this operand.
228 SMLoc getEndLoc() const { return EndLoc; }
230 virtual void print(raw_ostream &OS) const {
231 llvm_unreachable("unimplemented!");
236 unsigned MipsAsmParser::
237 getMCInstOperandNum(unsigned Kind, MCInst &Inst,
238 const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
239 unsigned OperandNum, unsigned &NumMCOperands) {
240 assert (0 && "getMCInstOperandNum() not supported by the Mips target.");
241 // The Mips backend doesn't currently include the matcher implementation, so
242 // the getMCInstOperandNumImpl() is undefined. This is a temporary
249 MatchAndEmitInstruction(SMLoc IDLoc,
250 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
255 unsigned MatchResult = MatchInstructionImpl(Operands, Kind, Inst, ErrorInfo);
257 switch (MatchResult) {
259 case Match_Success: {
261 Out.EmitInstruction(Inst);
264 case Match_MissingFeature:
265 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
267 case Match_InvalidOperand: {
268 SMLoc ErrorLoc = IDLoc;
269 if (ErrorInfo != ~0U) {
270 if (ErrorInfo >= Operands.size())
271 return Error(IDLoc, "too few operands for instruction");
273 ErrorLoc = ((MipsOperand*)Operands[ErrorInfo])->getStartLoc();
274 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
277 return Error(ErrorLoc, "invalid operand for instruction");
279 case Match_MnemonicFail:
280 return Error(IDLoc, "invalid instruction");
285 int MipsAsmParser::matchRegisterName(StringRef Name) {
287 int CC = StringSwitch<unsigned>(Name)
288 .Case("zero", Mips::ZERO)
289 .Case("a0", Mips::A0)
290 .Case("a1", Mips::A1)
291 .Case("a2", Mips::A2)
292 .Case("a3", Mips::A3)
293 .Case("v0", Mips::V0)
294 .Case("v1", Mips::V1)
295 .Case("s0", Mips::S0)
296 .Case("s1", Mips::S1)
297 .Case("s2", Mips::S2)
298 .Case("s3", Mips::S3)
299 .Case("s4", Mips::S4)
300 .Case("s5", Mips::S5)
301 .Case("s6", Mips::S6)
302 .Case("s7", Mips::S7)
303 .Case("k0", Mips::K0)
304 .Case("k1", Mips::K1)
305 .Case("sp", Mips::SP)
306 .Case("fp", Mips::FP)
307 .Case("gp", Mips::GP)
308 .Case("ra", Mips::RA)
309 .Case("t0", Mips::T0)
310 .Case("t1", Mips::T1)
311 .Case("t2", Mips::T2)
312 .Case("t3", Mips::T3)
313 .Case("t4", Mips::T4)
314 .Case("t5", Mips::T5)
315 .Case("t6", Mips::T6)
316 .Case("t7", Mips::T7)
317 .Case("t8", Mips::T8)
318 .Case("t9", Mips::T9)
319 .Case("at", Mips::AT)
320 .Case("fcc0", Mips::FCC0)
324 //64 bit register in Mips are following 32 bit definitions.
333 unsigned MipsAsmParser::getReg(int RC,int RegNo){
334 return *(getContext().getRegisterInfo().getRegClass(RC).begin() + RegNo);
337 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum,StringRef Mnemonic) {
339 if (Mnemonic.lower() == "rdhwr") {
340 //at the moment only hwreg29 is supported
349 return getReg(Mips::CPURegsRegClassID,RegNum);
352 int MipsAsmParser::tryParseRegister(StringRef Mnemonic) {
353 const AsmToken &Tok = Parser.getTok();
356 if (Tok.is(AsmToken::Identifier)) {
357 std::string lowerCase = Tok.getString().lower();
358 RegNum = matchRegisterName(lowerCase);
359 } else if (Tok.is(AsmToken::Integer))
360 RegNum = matchRegisterByNumber(static_cast<unsigned> (Tok.getIntVal()),
366 tryParseRegisterOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
369 SMLoc S = Parser.getTok().getLoc();
371 RegNo = tryParseRegister(Mnemonic);
375 Operands.push_back(MipsOperand::CreateReg(RegNo, S,
376 Parser.getTok().getLoc()));
377 Parser.Lex(); // Eat register token.
381 bool MipsAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*>&Operands,
382 StringRef Mnemonic) {
383 //Check if the current operand has a custom associated parser, if so, try to
384 //custom parse the operand, or fallback to the general approach.
385 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
386 if (ResTy == MatchOperand_Success)
388 // If there wasn't a custom match, try the generic matcher below. Otherwise,
389 // there was a match, but an error occurred, in which case, just return that
390 // the operand parsing failed.
391 if (ResTy == MatchOperand_ParseFail)
394 switch (getLexer().getKind()) {
396 Error(Parser.getTok().getLoc(), "unexpected token in operand");
398 case AsmToken::Dollar: {
400 SMLoc S = Parser.getTok().getLoc();
401 Parser.Lex(); // Eat dollar token.
402 //parse register operand
403 if (!tryParseRegisterOperand(Operands,Mnemonic)) {
404 if (getLexer().is(AsmToken::LParen)) {
405 //check if it is indexed addressing operand
406 Operands.push_back(MipsOperand::CreateToken("(", S));
407 Parser.Lex(); //eat parenthesis
408 if (getLexer().isNot(AsmToken::Dollar))
411 Parser.Lex(); //eat dollar
412 if (tryParseRegisterOperand(Operands,Mnemonic))
415 if (!getLexer().is(AsmToken::RParen))
418 S = Parser.getTok().getLoc();
419 Operands.push_back(MipsOperand::CreateToken(")", S));
424 //maybe it is a symbol reference
425 StringRef Identifier;
426 if (Parser.ParseIdentifier(Identifier))
429 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
431 StringRef Id = StringRef("$" + Identifier.str());
432 MCSymbol *Sym = getContext().GetOrCreateSymbol(Id);
434 // Otherwise create a symbol ref.
435 const MCExpr *Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
438 Operands.push_back(MipsOperand::CreateImm(Res, S, E));
441 case AsmToken::Identifier:
442 case AsmToken::LParen:
443 case AsmToken::Minus:
445 case AsmToken::Integer:
446 case AsmToken::String: {
447 // quoted label names
449 SMLoc S = Parser.getTok().getLoc();
450 if (getParser().ParseExpression(IdVal))
452 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
453 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
456 case AsmToken::Percent: {
457 //it is a symbol reference or constant expression
459 SMLoc S = Parser.getTok().getLoc(); //start location of the operand
460 if (parseRelocOperand(IdVal))
463 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
465 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
467 }//case AsmToken::Percent
468 }//switch(getLexer().getKind())
472 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
474 Parser.Lex(); //eat % token
475 const AsmToken &Tok = Parser.getTok(); //get next token, operation
476 if (Tok.isNot(AsmToken::Identifier))
479 StringRef Str = Tok.getIdentifier();
481 Parser.Lex(); //eat identifier
482 //now make expression from the rest of the operand
486 if (getLexer().getKind() == AsmToken::LParen) {
488 Parser.Lex(); //eat '(' token
489 if (getLexer().getKind() == AsmToken::Percent) {
490 Parser.Lex(); //eat % token
491 const AsmToken &nextTok = Parser.getTok();
492 if (nextTok.isNot(AsmToken::Identifier))
494 Str = StringRef(Str.str() + "(%" + nextTok.getIdentifier().str());
495 Parser.Lex(); //eat identifier
496 if (getLexer().getKind() != AsmToken::LParen)
501 if (getParser().ParseParenExpression(IdVal,EndLoc))
504 while (getLexer().getKind() == AsmToken::RParen)
505 Parser.Lex(); //eat ')' token
508 return true; //parenthesis must follow reloc operand
510 //Check the type of the expression
511 if (MCConstantExpr::classof(IdVal)) {
512 //it's a constant, evaluate lo or hi value
513 int Val = ((const MCConstantExpr*)IdVal)->getValue();
516 } else if (Str == "hi") {
517 Val = (Val & 0xffff0000) >> 16;
519 Res = MCConstantExpr::Create(Val, getContext());
523 if (MCSymbolRefExpr::classof(IdVal)) {
524 //it's a symbol, create symbolic expression from symbol
525 StringRef Symbol = ((const MCSymbolRefExpr*)IdVal)->getSymbol().getName();
526 MCSymbolRefExpr::VariantKind VK = getVariantKind(Str);
527 Res = MCSymbolRefExpr::Create(Symbol,VK,getContext());
533 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
536 StartLoc = Parser.getTok().getLoc();
537 RegNo = tryParseRegister("");
538 EndLoc = Parser.getTok().getLoc();
539 return (RegNo == (unsigned)-1);
542 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res) {
546 switch(getLexer().getKind()) {
549 case AsmToken::Integer:
550 case AsmToken::Minus:
552 return (getParser().ParseExpression(Res));
553 case AsmToken::Percent: {
554 return parseRelocOperand(Res);
556 case AsmToken::LParen:
557 return false; //it's probably assuming 0
562 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMemOperand(
563 SmallVectorImpl<MCParsedAsmOperand*>&Operands) {
565 const MCExpr *IdVal = 0;
567 //first operand is the offset
568 S = Parser.getTok().getLoc();
570 if (parseMemOffset(IdVal))
571 return MatchOperand_ParseFail;
573 const AsmToken &Tok = Parser.getTok(); //get next token
574 if (Tok.isNot(AsmToken::LParen)) {
575 Error(Parser.getTok().getLoc(), "'(' expected");
576 return MatchOperand_ParseFail;
579 Parser.Lex(); // Eat '(' token.
581 const AsmToken &Tok1 = Parser.getTok(); //get next token
582 if (Tok1.is(AsmToken::Dollar)) {
583 Parser.Lex(); // Eat '$' token.
584 if (tryParseRegisterOperand(Operands,"")) {
585 Error(Parser.getTok().getLoc(), "unexpected token in operand");
586 return MatchOperand_ParseFail;
590 Error(Parser.getTok().getLoc(),"unexpected token in operand");
591 return MatchOperand_ParseFail;
594 const AsmToken &Tok2 = Parser.getTok(); //get next token
595 if (Tok2.isNot(AsmToken::RParen)) {
596 Error(Parser.getTok().getLoc(), "')' expected");
597 return MatchOperand_ParseFail;
600 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
602 Parser.Lex(); // Eat ')' token.
605 IdVal = MCConstantExpr::Create(0, getContext());
607 //now replace register operand with the mem operand
608 MipsOperand* op = static_cast<MipsOperand*>(Operands.back());
609 int RegNo = op->getReg();
610 //remove register from operands
612 //and add memory operand
613 Operands.push_back(MipsOperand::CreateMem(RegNo, IdVal, S, E));
615 return MatchOperand_Success;
618 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
620 MCSymbolRefExpr::VariantKind VK
621 = StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
622 .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
623 .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
624 .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
625 .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
626 .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
627 .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
628 .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
629 .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
630 .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
631 .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
632 .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
633 .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
634 .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
635 .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
636 .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
637 .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
638 .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
639 .Default(MCSymbolRefExpr::VK_None);
645 ParseInstruction(StringRef Name, SMLoc NameLoc,
646 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
648 //first operand is a instruction mnemonic
649 Operands.push_back(MipsOperand::CreateToken(Name, NameLoc));
651 // Read the remaining operands.
652 if (getLexer().isNot(AsmToken::EndOfStatement)) {
653 // Read the first operand.
654 if (ParseOperand(Operands, Name)) {
655 SMLoc Loc = getLexer().getLoc();
656 Parser.EatToEndOfStatement();
657 return Error(Loc, "unexpected token in argument list");
660 while (getLexer().is(AsmToken::Comma) ) {
661 Parser.Lex(); // Eat the comma.
663 // Parse and remember the operand.
664 if (ParseOperand(Operands, Name)) {
665 SMLoc Loc = getLexer().getLoc();
666 Parser.EatToEndOfStatement();
667 return Error(Loc, "unexpected token in argument list");
672 if (getLexer().isNot(AsmToken::EndOfStatement)) {
673 SMLoc Loc = getLexer().getLoc();
674 Parser.EatToEndOfStatement();
675 return Error(Loc, "unexpected token in argument list");
678 Parser.Lex(); // Consume the EndOfStatement
683 ParseDirective(AsmToken DirectiveID) {
687 extern "C" void LLVMInitializeMipsAsmParser() {
688 RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
689 RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
690 RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
691 RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
694 #define GET_REGISTER_MATCHER
695 #define GET_MATCHER_IMPLEMENTATION
696 #include "MipsGenAsmMatcher.inc"