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/MipsMCExpr.h"
11 #include "MCTargetDesc/MipsMCTargetDesc.h"
12 #include "MipsRegisterInfo.h"
13 #include "MipsTargetStreamer.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCInstBuilder.h"
20 #include "llvm/MC/MCParser/MCAsmLexer.h"
21 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/MC/MCTargetAsmParser.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/TargetRegistry.h"
32 #define DEBUG_TYPE "mips-asm-parser"
39 class MipsAssemblerOptions {
41 MipsAssemblerOptions() : aTReg(1), reorder(true), macro(true) {}
43 unsigned getATRegNum() { return aTReg; }
44 bool setATReg(unsigned Reg);
46 bool isReorder() { return reorder; }
47 void setReorder() { reorder = true; }
48 void setNoreorder() { reorder = false; }
50 bool isMacro() { return macro; }
51 void setMacro() { macro = true; }
52 void setNomacro() { macro = false; }
62 class MipsAsmParser : public MCTargetAsmParser {
63 MipsTargetStreamer &getTargetStreamer() {
64 MCTargetStreamer &TS = *Parser.getStreamer().getTargetStreamer();
65 return static_cast<MipsTargetStreamer &>(TS);
70 MipsAssemblerOptions Options;
72 #define GET_ASSEMBLER_HEADER
73 #include "MipsGenAsmMatcher.inc"
75 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
77 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
78 OperandVector &Operands, MCStreamer &Out,
80 bool MatchingInlineAsm) override;
82 /// Parse a register as used in CFI directives
83 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
85 bool ParseParenSuffix(StringRef Name, OperandVector &Operands);
87 bool ParseBracketSuffix(StringRef Name, OperandVector &Operands);
89 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
90 SMLoc NameLoc, OperandVector &Operands) override;
92 bool ParseDirective(AsmToken DirectiveID) override;
94 MipsAsmParser::OperandMatchResultTy parseMemOperand(OperandVector &Operands);
96 MipsAsmParser::OperandMatchResultTy
97 MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
98 StringRef Identifier, SMLoc S);
100 MipsAsmParser::OperandMatchResultTy
101 MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S);
103 MipsAsmParser::OperandMatchResultTy ParseAnyRegister(OperandVector &Operands);
105 MipsAsmParser::OperandMatchResultTy ParseImm(OperandVector &Operands);
107 MipsAsmParser::OperandMatchResultTy ParseJumpTarget(OperandVector &Operands);
109 MipsAsmParser::OperandMatchResultTy parseInvNum(OperandVector &Operands);
111 MipsAsmParser::OperandMatchResultTy ParseLSAImm(OperandVector &Operands);
113 bool searchSymbolAlias(OperandVector &Operands);
115 bool ParseOperand(OperandVector &, StringRef Mnemonic);
117 bool needsExpansion(MCInst &Inst);
119 void expandInstruction(MCInst &Inst, SMLoc IDLoc,
120 SmallVectorImpl<MCInst> &Instructions);
121 void expandLoadImm(MCInst &Inst, SMLoc IDLoc,
122 SmallVectorImpl<MCInst> &Instructions);
123 void expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
124 SmallVectorImpl<MCInst> &Instructions);
125 void expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
126 SmallVectorImpl<MCInst> &Instructions);
127 void expandMemInst(MCInst &Inst, SMLoc IDLoc,
128 SmallVectorImpl<MCInst> &Instructions, bool isLoad,
130 bool reportParseError(StringRef ErrorMsg);
131 bool reportParseError(SMLoc Loc, StringRef ErrorMsg);
133 bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
134 bool parseRelocOperand(const MCExpr *&Res);
136 const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
138 bool isEvaluated(const MCExpr *Expr);
139 bool parseSetFeature(uint64_t Feature);
140 bool parseDirectiveCPLoad(SMLoc Loc);
141 bool parseDirectiveCPSetup();
142 bool parseDirectiveNaN();
143 bool parseDirectiveSet();
144 bool parseDirectiveOption();
146 bool parseSetAtDirective();
147 bool parseSetNoAtDirective();
148 bool parseSetMacroDirective();
149 bool parseSetNoMacroDirective();
150 bool parseSetReorderDirective();
151 bool parseSetNoReorderDirective();
152 bool parseSetNoMips16Directive();
154 bool parseSetAssignment();
156 bool parseDataDirective(unsigned Size, SMLoc L);
157 bool parseDirectiveGpWord();
158 bool parseDirectiveGpDWord();
160 MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
162 bool isGP64() const {
163 return (STI.getFeatureBits() & Mips::FeatureGP64Bit) != 0;
166 bool isFP64() const {
167 return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
170 bool isN32() const { return STI.getFeatureBits() & Mips::FeatureN32; }
171 bool isN64() const { return STI.getFeatureBits() & Mips::FeatureN64; }
173 bool isMicroMips() const {
174 return STI.getFeatureBits() & Mips::FeatureMicroMips;
177 bool hasMips4() const { return STI.getFeatureBits() & Mips::FeatureMips4; }
178 bool hasMips32() const { return STI.getFeatureBits() & Mips::FeatureMips32; }
179 bool hasMips32r6() const {
180 return STI.getFeatureBits() & Mips::FeatureMips32r6;
182 bool hasMips64r6() const {
183 return STI.getFeatureBits() & Mips::FeatureMips64r6;
186 bool parseRegister(unsigned &RegNum);
188 bool eatComma(StringRef ErrorStr);
190 int matchCPURegisterName(StringRef Symbol);
192 int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
194 int matchFPURegisterName(StringRef Name);
196 int matchFCCRegisterName(StringRef Name);
198 int matchACRegisterName(StringRef Name);
200 int matchMSA128RegisterName(StringRef Name);
202 int matchMSA128CtrlRegisterName(StringRef Name);
204 unsigned getReg(int RC, int RegNo);
206 unsigned getGPR(int RegNo);
210 bool processInstruction(MCInst &Inst, SMLoc IDLoc,
211 SmallVectorImpl<MCInst> &Instructions);
213 // Helper function that checks if the value of a vector index is within the
214 // boundaries of accepted values for each RegisterKind
215 // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
216 bool validateMSAIndex(int Val, int RegKind);
218 void setFeatureBits(unsigned Feature, StringRef FeatureString) {
219 if (!(STI.getFeatureBits() & Feature)) {
220 setAvailableFeatures(
221 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
225 void clearFeatureBits(unsigned Feature, StringRef FeatureString) {
226 if (STI.getFeatureBits() & Feature) {
227 setAvailableFeatures(
228 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
233 enum MipsMatchResultTy {
234 Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY
235 #define GET_OPERAND_DIAGNOSTIC_TYPES
236 #include "MipsGenAsmMatcher.inc"
237 #undef GET_OPERAND_DIAGNOSTIC_TYPES
241 MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
242 const MCInstrInfo &MII,
243 const MCTargetOptions &Options)
244 : MCTargetAsmParser(), STI(sti), Parser(parser) {
245 // Initialize the set of available features.
246 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
248 // Assert exactly one ABI was chosen.
249 assert((((STI.getFeatureBits() & Mips::FeatureO32) != 0) +
250 ((STI.getFeatureBits() & Mips::FeatureEABI) != 0) +
251 ((STI.getFeatureBits() & Mips::FeatureN32) != 0) +
252 ((STI.getFeatureBits() & Mips::FeatureN64) != 0)) == 1);
255 MCAsmParser &getParser() const { return Parser; }
256 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
258 /// True if all of $fcc0 - $fcc7 exist for the current ISA.
259 bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
261 /// Warn if RegNo is the current assembler temporary.
262 void WarnIfAssemblerTemporary(int RegNo, SMLoc Loc);
268 /// MipsOperand - Instances of this class represent a parsed Mips machine
270 class MipsOperand : public MCParsedAsmOperand {
272 /// Broad categories of register classes
273 /// The exact class is finalized by the render method.
275 RegKind_GPR = 1, /// GPR32 and GPR64 (depending on isGP64())
276 RegKind_FGR = 2, /// FGR32, FGR64, AFGR64 (depending on context and
278 RegKind_FCC = 4, /// FCC
279 RegKind_MSA128 = 8, /// MSA128[BHWD] (makes no difference which)
280 RegKind_MSACtrl = 16, /// MSA control registers
281 RegKind_COP2 = 32, /// COP2
282 RegKind_ACC = 64, /// HI32DSP, LO32DSP, and ACC64DSP (depending on
284 RegKind_CCR = 128, /// CCR
285 RegKind_HWRegs = 256, /// HWRegs
286 RegKind_COP3 = 512, /// COP3
288 /// Potentially any (e.g. $1)
289 RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
290 RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
291 RegKind_CCR | RegKind_HWRegs | RegKind_COP3
296 k_Immediate, /// An immediate (possibly involving symbol references)
297 k_Memory, /// Base + Offset Memory Address
298 k_PhysRegister, /// A physical register from the Mips namespace
299 k_RegisterIndex, /// A register index in one or more RegKind.
300 k_Token /// A simple token
304 MipsOperand(KindTy K, MipsAsmParser &Parser)
305 : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
308 /// For diagnostics, and checking the assembler temporary
309 MipsAsmParser &AsmParser;
317 unsigned Num; /// Register Number
321 unsigned Index; /// Index into the register class
322 RegKind Kind; /// Bitfield of the kinds it could possibly be
323 const MCRegisterInfo *RegInfo;
337 struct PhysRegOp PhysReg;
338 struct RegIdxOp RegIdx;
343 SMLoc StartLoc, EndLoc;
345 /// Internal constructor for register kinds
346 static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
347 const MCRegisterInfo *RegInfo,
349 MipsAsmParser &Parser) {
350 auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
351 Op->RegIdx.Index = Index;
352 Op->RegIdx.RegInfo = RegInfo;
353 Op->RegIdx.Kind = RegKind;
360 /// Coerce the register to GPR32 and return the real register for the current
362 unsigned getGPR32Reg() const {
363 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
364 AsmParser.WarnIfAssemblerTemporary(RegIdx.Index, StartLoc);
365 unsigned ClassID = Mips::GPR32RegClassID;
366 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
369 /// Coerce the register to GPR64 and return the real register for the current
371 unsigned getGPR64Reg() const {
372 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
373 unsigned ClassID = Mips::GPR64RegClassID;
374 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
378 /// Coerce the register to AFGR64 and return the real register for the current
380 unsigned getAFGR64Reg() const {
381 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
382 if (RegIdx.Index % 2 != 0)
383 AsmParser.Warning(StartLoc, "Float register should be even.");
384 return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
385 .getRegister(RegIdx.Index / 2);
388 /// Coerce the register to FGR64 and return the real register for the current
390 unsigned getFGR64Reg() const {
391 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
392 return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
393 .getRegister(RegIdx.Index);
396 /// Coerce the register to FGR32 and return the real register for the current
398 unsigned getFGR32Reg() const {
399 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
400 return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
401 .getRegister(RegIdx.Index);
404 /// Coerce the register to FGRH32 and return the real register for the current
406 unsigned getFGRH32Reg() const {
407 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
408 return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
409 .getRegister(RegIdx.Index);
412 /// Coerce the register to FCC and return the real register for the current
414 unsigned getFCCReg() const {
415 assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
416 return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
417 .getRegister(RegIdx.Index);
420 /// Coerce the register to MSA128 and return the real register for the current
422 unsigned getMSA128Reg() const {
423 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
424 // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
426 unsigned ClassID = Mips::MSA128BRegClassID;
427 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
430 /// Coerce the register to MSACtrl and return the real register for the
432 unsigned getMSACtrlReg() const {
433 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
434 unsigned ClassID = Mips::MSACtrlRegClassID;
435 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
438 /// Coerce the register to COP2 and return the real register for the
440 unsigned getCOP2Reg() const {
441 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
442 unsigned ClassID = Mips::COP2RegClassID;
443 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
446 /// Coerce the register to COP3 and return the real register for the
448 unsigned getCOP3Reg() const {
449 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
450 unsigned ClassID = Mips::COP3RegClassID;
451 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
454 /// Coerce the register to ACC64DSP and return the real register for the
456 unsigned getACC64DSPReg() const {
457 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
458 unsigned ClassID = Mips::ACC64DSPRegClassID;
459 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
462 /// Coerce the register to HI32DSP and return the real register for the
464 unsigned getHI32DSPReg() const {
465 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
466 unsigned ClassID = Mips::HI32DSPRegClassID;
467 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
470 /// Coerce the register to LO32DSP and return the real register for the
472 unsigned getLO32DSPReg() const {
473 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
474 unsigned ClassID = Mips::LO32DSPRegClassID;
475 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
478 /// Coerce the register to CCR and return the real register for the
480 unsigned getCCRReg() const {
481 assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
482 unsigned ClassID = Mips::CCRRegClassID;
483 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
486 /// Coerce the register to HWRegs and return the real register for the
488 unsigned getHWRegsReg() const {
489 assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
490 unsigned ClassID = Mips::HWRegsRegClassID;
491 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
495 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
496 // Add as immediate when possible. Null MCExpr = 0.
498 Inst.addOperand(MCOperand::CreateImm(0));
499 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
500 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
502 Inst.addOperand(MCOperand::CreateExpr(Expr));
505 void addRegOperands(MCInst &Inst, unsigned N) const {
506 llvm_unreachable("Use a custom parser instead");
509 /// Render the operand to an MCInst as a GPR32
510 /// Asserts if the wrong number of operands are requested, or the operand
511 /// is not a k_RegisterIndex compatible with RegKind_GPR
512 void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
513 assert(N == 1 && "Invalid number of operands!");
514 Inst.addOperand(MCOperand::CreateReg(getGPR32Reg()));
517 /// Render the operand to an MCInst as a GPR64
518 /// Asserts if the wrong number of operands are requested, or the operand
519 /// is not a k_RegisterIndex compatible with RegKind_GPR
520 void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
521 assert(N == 1 && "Invalid number of operands!");
522 Inst.addOperand(MCOperand::CreateReg(getGPR64Reg()));
525 void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
526 assert(N == 1 && "Invalid number of operands!");
527 Inst.addOperand(MCOperand::CreateReg(getAFGR64Reg()));
530 void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
531 assert(N == 1 && "Invalid number of operands!");
532 Inst.addOperand(MCOperand::CreateReg(getFGR64Reg()));
535 void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
536 assert(N == 1 && "Invalid number of operands!");
537 Inst.addOperand(MCOperand::CreateReg(getFGR32Reg()));
540 void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
541 assert(N == 1 && "Invalid number of operands!");
542 Inst.addOperand(MCOperand::CreateReg(getFGRH32Reg()));
545 void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
546 assert(N == 1 && "Invalid number of operands!");
547 Inst.addOperand(MCOperand::CreateReg(getFCCReg()));
550 void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
551 assert(N == 1 && "Invalid number of operands!");
552 Inst.addOperand(MCOperand::CreateReg(getMSA128Reg()));
555 void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
556 assert(N == 1 && "Invalid number of operands!");
557 Inst.addOperand(MCOperand::CreateReg(getMSACtrlReg()));
560 void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
561 assert(N == 1 && "Invalid number of operands!");
562 Inst.addOperand(MCOperand::CreateReg(getCOP2Reg()));
565 void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
566 assert(N == 1 && "Invalid number of operands!");
567 Inst.addOperand(MCOperand::CreateReg(getCOP3Reg()));
570 void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
571 assert(N == 1 && "Invalid number of operands!");
572 Inst.addOperand(MCOperand::CreateReg(getACC64DSPReg()));
575 void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
576 assert(N == 1 && "Invalid number of operands!");
577 Inst.addOperand(MCOperand::CreateReg(getHI32DSPReg()));
580 void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
581 assert(N == 1 && "Invalid number of operands!");
582 Inst.addOperand(MCOperand::CreateReg(getLO32DSPReg()));
585 void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
586 assert(N == 1 && "Invalid number of operands!");
587 Inst.addOperand(MCOperand::CreateReg(getCCRReg()));
590 void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
591 assert(N == 1 && "Invalid number of operands!");
592 Inst.addOperand(MCOperand::CreateReg(getHWRegsReg()));
595 void addImmOperands(MCInst &Inst, unsigned N) const {
596 assert(N == 1 && "Invalid number of operands!");
597 const MCExpr *Expr = getImm();
601 void addMemOperands(MCInst &Inst, unsigned N) const {
602 assert(N == 2 && "Invalid number of operands!");
604 Inst.addOperand(MCOperand::CreateReg(getMemBase()->getGPR32Reg()));
606 const MCExpr *Expr = getMemOff();
610 bool isReg() const override {
611 // As a special case until we sort out the definition of div/divu, pretend
612 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
613 if (isGPRAsmReg() && RegIdx.Index == 0)
616 return Kind == k_PhysRegister;
618 bool isRegIdx() const { return Kind == k_RegisterIndex; }
619 bool isImm() const override { return Kind == k_Immediate; }
620 bool isConstantImm() const {
621 return isImm() && dyn_cast<MCConstantExpr>(getImm());
623 bool isToken() const override {
624 // Note: It's not possible to pretend that other operand kinds are tokens.
625 // The matcher emitter checks tokens first.
626 return Kind == k_Token;
628 bool isMem() const override { return Kind == k_Memory; }
629 bool isConstantMemOff() const {
630 return isMem() && dyn_cast<MCConstantExpr>(getMemOff());
632 template <unsigned Bits> bool isMemWithSimmOffset() const {
633 return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff());
635 bool isInvNum() const { return Kind == k_Immediate; }
636 bool isLSAImm() const {
637 if (!isConstantImm())
639 int64_t Val = getConstantImm();
640 return 1 <= Val && Val <= 4;
643 StringRef getToken() const {
644 assert(Kind == k_Token && "Invalid access!");
645 return StringRef(Tok.Data, Tok.Length);
648 unsigned getReg() const override {
649 // As a special case until we sort out the definition of div/divu, pretend
650 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
651 if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
652 RegIdx.Kind & RegKind_GPR)
653 return getGPR32Reg(); // FIXME: GPR64 too
655 assert(Kind == k_PhysRegister && "Invalid access!");
659 const MCExpr *getImm() const {
660 assert((Kind == k_Immediate) && "Invalid access!");
664 int64_t getConstantImm() const {
665 const MCExpr *Val = getImm();
666 return static_cast<const MCConstantExpr *>(Val)->getValue();
669 MipsOperand *getMemBase() const {
670 assert((Kind == k_Memory) && "Invalid access!");
674 const MCExpr *getMemOff() const {
675 assert((Kind == k_Memory) && "Invalid access!");
679 int64_t getConstantMemOff() const {
680 return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
683 static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
684 MipsAsmParser &Parser) {
685 auto Op = make_unique<MipsOperand>(k_Token, Parser);
686 Op->Tok.Data = Str.data();
687 Op->Tok.Length = Str.size();
693 /// Create a numeric register (e.g. $1). The exact register remains
694 /// unresolved until an instruction successfully matches
695 static std::unique_ptr<MipsOperand>
696 CreateNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
697 SMLoc E, MipsAsmParser &Parser) {
698 DEBUG(dbgs() << "CreateNumericReg(" << Index << ", ...)\n");
699 return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
702 /// Create a register that is definitely a GPR.
703 /// This is typically only used for named registers such as $gp.
704 static std::unique_ptr<MipsOperand>
705 CreateGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
706 MipsAsmParser &Parser) {
707 return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
710 /// Create a register that is definitely a FGR.
711 /// This is typically only used for named registers such as $f0.
712 static std::unique_ptr<MipsOperand>
713 CreateFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
714 MipsAsmParser &Parser) {
715 return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
718 /// Create a register that is definitely an FCC.
719 /// This is typically only used for named registers such as $fcc0.
720 static std::unique_ptr<MipsOperand>
721 CreateFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
722 MipsAsmParser &Parser) {
723 return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
726 /// Create a register that is definitely an ACC.
727 /// This is typically only used for named registers such as $ac0.
728 static std::unique_ptr<MipsOperand>
729 CreateACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
730 MipsAsmParser &Parser) {
731 return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
734 /// Create a register that is definitely an MSA128.
735 /// This is typically only used for named registers such as $w0.
736 static std::unique_ptr<MipsOperand>
737 CreateMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
738 SMLoc E, MipsAsmParser &Parser) {
739 return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
742 /// Create a register that is definitely an MSACtrl.
743 /// This is typically only used for named registers such as $msaaccess.
744 static std::unique_ptr<MipsOperand>
745 CreateMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
746 SMLoc E, MipsAsmParser &Parser) {
747 return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
750 static std::unique_ptr<MipsOperand>
751 CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
752 auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
759 static std::unique_ptr<MipsOperand>
760 CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
761 SMLoc E, MipsAsmParser &Parser) {
762 auto Op = make_unique<MipsOperand>(k_Memory, Parser);
763 Op->Mem.Base = Base.release();
770 bool isGPRAsmReg() const {
771 return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
773 bool isFGRAsmReg() const {
774 // AFGR64 is $0-$15 but we handle this in getAFGR64()
775 return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
777 bool isHWRegsAsmReg() const {
778 return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
780 bool isCCRAsmReg() const {
781 return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
783 bool isFCCAsmReg() const {
784 if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
786 if (!AsmParser.hasEightFccRegisters())
787 return RegIdx.Index == 0;
788 return RegIdx.Index <= 7;
790 bool isACCAsmReg() const {
791 return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
793 bool isCOP2AsmReg() const {
794 return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
796 bool isCOP3AsmReg() const {
797 return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
799 bool isMSA128AsmReg() const {
800 return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
802 bool isMSACtrlAsmReg() const {
803 return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
806 /// getStartLoc - Get the location of the first token of this operand.
807 SMLoc getStartLoc() const override { return StartLoc; }
808 /// getEndLoc - Get the location of the last token of this operand.
809 SMLoc getEndLoc() const override { return EndLoc; }
811 virtual ~MipsOperand() {
819 case k_RegisterIndex:
825 void print(raw_ostream &OS) const override {
840 OS << "PhysReg<" << PhysReg.Num << ">";
842 case k_RegisterIndex:
843 OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
850 }; // class MipsOperand
854 extern const MCInstrDesc MipsInsts[];
856 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
857 return MipsInsts[Opcode];
860 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
861 SmallVectorImpl<MCInst> &Instructions) {
862 const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
866 if (MCID.isBranch() || MCID.isCall()) {
867 const unsigned Opcode = Inst.getOpcode();
877 assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
878 Offset = Inst.getOperand(2);
880 break; // We'll deal with this situation later on when applying fixups.
881 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
882 return Error(IDLoc, "branch target out of range");
883 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
884 return Error(IDLoc, "branch to misaligned address");
898 case Mips::BGEZAL_MM:
899 case Mips::BLTZAL_MM:
902 assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
903 Offset = Inst.getOperand(1);
905 break; // We'll deal with this situation later on when applying fixups.
906 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
907 return Error(IDLoc, "branch target out of range");
908 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
909 return Error(IDLoc, "branch to misaligned address");
914 // SSNOP is deprecated on MIPS32r6/MIPS64r6
915 // We still accept it but it is a normal nop.
916 if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
917 std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
918 Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
922 if (MCID.hasDelaySlot() && Options.isReorder()) {
923 // If this instruction has a delay slot and .set reorder is active,
924 // emit a NOP after it.
925 Instructions.push_back(Inst);
927 NopInst.setOpcode(Mips::SLL);
928 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
929 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
930 NopInst.addOperand(MCOperand::CreateImm(0));
931 Instructions.push_back(NopInst);
935 if (MCID.mayLoad() || MCID.mayStore()) {
936 // Check the offset of memory operand, if it is a symbol
937 // reference or immediate we may have to expand instructions.
938 for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
939 const MCOperandInfo &OpInfo = MCID.OpInfo[i];
940 if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
941 (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
942 MCOperand &Op = Inst.getOperand(i);
944 int MemOffset = Op.getImm();
945 if (MemOffset < -32768 || MemOffset > 32767) {
946 // Offset can't exceed 16bit value.
947 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
950 } else if (Op.isExpr()) {
951 const MCExpr *Expr = Op.getExpr();
952 if (Expr->getKind() == MCExpr::SymbolRef) {
953 const MCSymbolRefExpr *SR =
954 static_cast<const MCSymbolRefExpr *>(Expr);
955 if (SR->getKind() == MCSymbolRefExpr::VK_None) {
957 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
960 } else if (!isEvaluated(Expr)) {
961 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
969 if (needsExpansion(Inst))
970 expandInstruction(Inst, IDLoc, Instructions);
972 Instructions.push_back(Inst);
977 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
979 switch (Inst.getOpcode()) {
980 case Mips::LoadImm32Reg:
981 case Mips::LoadAddr32Imm:
982 case Mips::LoadAddr32Reg:
989 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
990 SmallVectorImpl<MCInst> &Instructions) {
991 switch (Inst.getOpcode()) {
992 case Mips::LoadImm32Reg:
993 return expandLoadImm(Inst, IDLoc, Instructions);
994 case Mips::LoadAddr32Imm:
995 return expandLoadAddressImm(Inst, IDLoc, Instructions);
996 case Mips::LoadAddr32Reg:
997 return expandLoadAddressReg(Inst, IDLoc, Instructions);
1001 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
1002 SmallVectorImpl<MCInst> &Instructions) {
1004 const MCOperand &ImmOp = Inst.getOperand(1);
1005 assert(ImmOp.isImm() && "expected immediate operand kind");
1006 const MCOperand &RegOp = Inst.getOperand(0);
1007 assert(RegOp.isReg() && "expected register operand kind");
1009 int ImmValue = ImmOp.getImm();
1010 tmpInst.setLoc(IDLoc);
1011 if (0 <= ImmValue && ImmValue <= 65535) {
1012 // For 0 <= j <= 65535.
1013 // li d,j => ori d,$zero,j
1014 tmpInst.setOpcode(Mips::ORi);
1015 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1016 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1017 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1018 Instructions.push_back(tmpInst);
1019 } else if (ImmValue < 0 && ImmValue >= -32768) {
1020 // For -32768 <= j < 0.
1021 // li d,j => addiu d,$zero,j
1022 tmpInst.setOpcode(Mips::ADDiu);
1023 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1024 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1025 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1026 Instructions.push_back(tmpInst);
1028 // For any other value of j that is representable as a 32-bit integer.
1029 // li d,j => lui d,hi16(j)
1031 tmpInst.setOpcode(Mips::LUi);
1032 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1033 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1034 Instructions.push_back(tmpInst);
1036 tmpInst.setOpcode(Mips::ORi);
1037 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1038 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1039 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1040 tmpInst.setLoc(IDLoc);
1041 Instructions.push_back(tmpInst);
1046 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
1047 SmallVectorImpl<MCInst> &Instructions) {
1049 const MCOperand &ImmOp = Inst.getOperand(2);
1050 assert(ImmOp.isImm() && "expected immediate operand kind");
1051 const MCOperand &SrcRegOp = Inst.getOperand(1);
1052 assert(SrcRegOp.isReg() && "expected register operand kind");
1053 const MCOperand &DstRegOp = Inst.getOperand(0);
1054 assert(DstRegOp.isReg() && "expected register operand kind");
1055 int ImmValue = ImmOp.getImm();
1056 if (-32768 <= ImmValue && ImmValue <= 65535) {
1057 // For -32768 <= j <= 65535.
1058 // la d,j(s) => addiu d,s,j
1059 tmpInst.setOpcode(Mips::ADDiu);
1060 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1061 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1062 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1063 Instructions.push_back(tmpInst);
1065 // For any other value of j that is representable as a 32-bit integer.
1066 // la d,j(s) => lui d,hi16(j)
1069 tmpInst.setOpcode(Mips::LUi);
1070 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1071 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1072 Instructions.push_back(tmpInst);
1074 tmpInst.setOpcode(Mips::ORi);
1075 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1076 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1077 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1078 Instructions.push_back(tmpInst);
1080 tmpInst.setOpcode(Mips::ADDu);
1081 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1082 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1083 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1084 Instructions.push_back(tmpInst);
1089 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
1090 SmallVectorImpl<MCInst> &Instructions) {
1092 const MCOperand &ImmOp = Inst.getOperand(1);
1093 assert(ImmOp.isImm() && "expected immediate operand kind");
1094 const MCOperand &RegOp = Inst.getOperand(0);
1095 assert(RegOp.isReg() && "expected register operand kind");
1096 int ImmValue = ImmOp.getImm();
1097 if (-32768 <= ImmValue && ImmValue <= 65535) {
1098 // For -32768 <= j <= 65535.
1099 // la d,j => addiu d,$zero,j
1100 tmpInst.setOpcode(Mips::ADDiu);
1101 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1102 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1103 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1104 Instructions.push_back(tmpInst);
1106 // For any other value of j that is representable as a 32-bit integer.
1107 // la d,j => lui d,hi16(j)
1109 tmpInst.setOpcode(Mips::LUi);
1110 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1111 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1112 Instructions.push_back(tmpInst);
1114 tmpInst.setOpcode(Mips::ORi);
1115 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1116 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1117 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1118 Instructions.push_back(tmpInst);
1122 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
1123 SmallVectorImpl<MCInst> &Instructions,
1124 bool isLoad, bool isImmOpnd) {
1125 const MCSymbolRefExpr *SR;
1127 unsigned ImmOffset, HiOffset, LoOffset;
1128 const MCExpr *ExprOffset;
1130 unsigned AtRegNum = getReg(
1131 (isGP64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
1132 // 1st operand is either the source or destination register.
1133 assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1134 unsigned RegOpNum = Inst.getOperand(0).getReg();
1135 // 2nd operand is the base register.
1136 assert(Inst.getOperand(1).isReg() && "expected register operand kind");
1137 unsigned BaseRegNum = Inst.getOperand(1).getReg();
1138 // 3rd operand is either an immediate or expression.
1140 assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
1141 ImmOffset = Inst.getOperand(2).getImm();
1142 LoOffset = ImmOffset & 0x0000ffff;
1143 HiOffset = (ImmOffset & 0xffff0000) >> 16;
1144 // If msb of LoOffset is 1(negative number) we must increment HiOffset.
1145 if (LoOffset & 0x8000)
1148 ExprOffset = Inst.getOperand(2).getExpr();
1149 // All instructions will have the same location.
1150 TempInst.setLoc(IDLoc);
1151 // 1st instruction in expansion is LUi. For load instruction we can use
1152 // the dst register as a temporary if base and dst are different,
1153 // but for stores we must use $at.
1154 TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
1155 TempInst.setOpcode(Mips::LUi);
1156 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1158 TempInst.addOperand(MCOperand::CreateImm(HiOffset));
1160 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1161 SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
1162 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
1163 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
1165 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1167 const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
1168 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1171 // Add the instruction to the list.
1172 Instructions.push_back(TempInst);
1173 // Prepare TempInst for next instruction.
1175 // Add temp register to base.
1176 TempInst.setOpcode(Mips::ADDu);
1177 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1178 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1179 TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
1180 Instructions.push_back(TempInst);
1182 // And finally, create original instruction with low part
1183 // of offset and new base.
1184 TempInst.setOpcode(Inst.getOpcode());
1185 TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
1186 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1188 TempInst.addOperand(MCOperand::CreateImm(LoOffset));
1190 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1191 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
1192 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
1194 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1196 const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
1197 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1200 Instructions.push_back(TempInst);
1204 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1205 // As described by the Mips32r2 spec, the registers Rd and Rs for
1206 // jalr.hb must be different.
1207 unsigned Opcode = Inst.getOpcode();
1209 if (Opcode == Mips::JALR_HB &&
1210 (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()))
1211 return Match_RequiresDifferentSrcAndDst;
1213 return Match_Success;
1216 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1217 OperandVector &Operands,
1219 unsigned &ErrorInfo,
1220 bool MatchingInlineAsm) {
1223 SmallVector<MCInst, 8> Instructions;
1224 unsigned MatchResult =
1225 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
1227 switch (MatchResult) {
1230 case Match_Success: {
1231 if (processInstruction(Inst, IDLoc, Instructions))
1233 for (unsigned i = 0; i < Instructions.size(); i++)
1234 Out.EmitInstruction(Instructions[i], STI);
1237 case Match_MissingFeature:
1238 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1240 case Match_InvalidOperand: {
1241 SMLoc ErrorLoc = IDLoc;
1242 if (ErrorInfo != ~0U) {
1243 if (ErrorInfo >= Operands.size())
1244 return Error(IDLoc, "too few operands for instruction");
1246 ErrorLoc = ((MipsOperand &)*Operands[ErrorInfo]).getStartLoc();
1247 if (ErrorLoc == SMLoc())
1251 return Error(ErrorLoc, "invalid operand for instruction");
1253 case Match_MnemonicFail:
1254 return Error(IDLoc, "invalid instruction");
1255 case Match_RequiresDifferentSrcAndDst:
1256 return Error(IDLoc, "source and destination must be different");
1261 void MipsAsmParser::WarnIfAssemblerTemporary(int RegIndex, SMLoc Loc) {
1262 if ((RegIndex != 0) && ((int)Options.getATRegNum() == RegIndex)) {
1264 Warning(Loc, "Used $at without \".set noat\"");
1266 Warning(Loc, Twine("Used $") + Twine(RegIndex) + " with \".set at=$" +
1267 Twine(RegIndex) + "\"");
1271 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
1274 CC = StringSwitch<unsigned>(Name)
1310 if (isN32() || isN64()) {
1311 // Although SGI documentation just cuts out t0-t3 for n32/n64,
1312 // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
1313 // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
1314 if (8 <= CC && CC <= 11)
1318 CC = StringSwitch<unsigned>(Name)
1331 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
1333 if (Name[0] == 'f') {
1334 StringRef NumString = Name.substr(1);
1336 if (NumString.getAsInteger(10, IntVal))
1337 return -1; // This is not an integer.
1338 if (IntVal > 31) // Maximum index for fpu register.
1345 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1347 if (Name.startswith("fcc")) {
1348 StringRef NumString = Name.substr(3);
1350 if (NumString.getAsInteger(10, IntVal))
1351 return -1; // This is not an integer.
1352 if (IntVal > 7) // There are only 8 fcc registers.
1359 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1361 if (Name.startswith("ac")) {
1362 StringRef NumString = Name.substr(2);
1364 if (NumString.getAsInteger(10, IntVal))
1365 return -1; // This is not an integer.
1366 if (IntVal > 3) // There are only 3 acc registers.
1373 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1376 if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1385 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1388 CC = StringSwitch<unsigned>(Name)
1391 .Case("msaaccess", 2)
1393 .Case("msamodify", 4)
1394 .Case("msarequest", 5)
1396 .Case("msaunmap", 7)
1402 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1410 int MipsAsmParser::getATReg() {
1411 int AT = Options.getATRegNum();
1413 TokError("Pseudo instruction requires $at, which is not available");
1417 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1418 return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1421 unsigned MipsAsmParser::getGPR(int RegNo) {
1422 return getReg(isGP64() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1426 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1428 getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1431 return getReg(RegClass, RegNum);
1434 bool MipsAsmParser::ParseOperand(OperandVector &Operands, StringRef Mnemonic) {
1435 DEBUG(dbgs() << "ParseOperand\n");
1437 // Check if the current operand has a custom associated parser, if so, try to
1438 // custom parse the operand, or fallback to the general approach.
1439 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1440 if (ResTy == MatchOperand_Success)
1442 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1443 // there was a match, but an error occurred, in which case, just return that
1444 // the operand parsing failed.
1445 if (ResTy == MatchOperand_ParseFail)
1448 DEBUG(dbgs() << ".. Generic Parser\n");
1450 switch (getLexer().getKind()) {
1452 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1454 case AsmToken::Dollar: {
1455 // Parse the register.
1456 SMLoc S = Parser.getTok().getLoc();
1458 // Almost all registers have been parsed by custom parsers. There is only
1459 // one exception to this. $zero (and it's alias $0) will reach this point
1460 // for div, divu, and similar instructions because it is not an operand
1461 // to the instruction definition but an explicit register. Special case
1462 // this situation for now.
1463 if (ParseAnyRegister(Operands) != MatchOperand_NoMatch)
1466 // Maybe it is a symbol reference.
1467 StringRef Identifier;
1468 if (Parser.parseIdentifier(Identifier))
1471 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1472 MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1473 // Otherwise create a symbol reference.
1475 MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1477 Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
1480 // Else drop to expression parsing.
1481 case AsmToken::LParen:
1482 case AsmToken::Minus:
1483 case AsmToken::Plus:
1484 case AsmToken::Integer:
1485 case AsmToken::String: {
1486 DEBUG(dbgs() << ".. generic integer\n");
1487 OperandMatchResultTy ResTy = ParseImm(Operands);
1488 return ResTy != MatchOperand_Success;
1490 case AsmToken::Percent: {
1491 // It is a symbol reference or constant expression.
1492 const MCExpr *IdVal;
1493 SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1494 if (parseRelocOperand(IdVal))
1497 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1499 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1501 } // case AsmToken::Percent
1502 } // switch(getLexer().getKind())
1506 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1507 StringRef RelocStr) {
1509 // Check the type of the expression.
1510 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1511 // It's a constant, evaluate reloc value.
1513 switch (getVariantKind(RelocStr)) {
1514 case MCSymbolRefExpr::VK_Mips_ABS_LO:
1515 // Get the 1st 16-bits.
1516 Val = MCE->getValue() & 0xffff;
1518 case MCSymbolRefExpr::VK_Mips_ABS_HI:
1519 // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
1520 // 16 bits being negative.
1521 Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
1523 case MCSymbolRefExpr::VK_Mips_HIGHER:
1524 // Get the 3rd 16-bits.
1525 Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
1527 case MCSymbolRefExpr::VK_Mips_HIGHEST:
1528 // Get the 4th 16-bits.
1529 Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
1532 report_fatal_error("Unsupported reloc value!");
1534 return MCConstantExpr::Create(Val, getContext());
1537 if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1538 // It's a symbol, create a symbolic expression from the symbol.
1539 StringRef Symbol = MSRE->getSymbol().getName();
1540 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1541 Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1545 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1546 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1548 // Try to create target expression.
1549 if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
1550 return MipsMCExpr::Create(VK, Expr, getContext());
1552 const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1553 const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1554 Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1558 if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1559 const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1560 Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1563 // Just return the original expression.
1567 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1569 switch (Expr->getKind()) {
1570 case MCExpr::Constant:
1572 case MCExpr::SymbolRef:
1573 return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1574 case MCExpr::Binary:
1575 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1576 if (!isEvaluated(BE->getLHS()))
1578 return isEvaluated(BE->getRHS());
1581 return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1582 case MCExpr::Target:
1588 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1589 Parser.Lex(); // Eat the % token.
1590 const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1591 if (Tok.isNot(AsmToken::Identifier))
1594 std::string Str = Tok.getIdentifier().str();
1596 Parser.Lex(); // Eat the identifier.
1597 // Now make an expression from the rest of the operand.
1598 const MCExpr *IdVal;
1601 if (getLexer().getKind() == AsmToken::LParen) {
1603 Parser.Lex(); // Eat the '(' token.
1604 if (getLexer().getKind() == AsmToken::Percent) {
1605 Parser.Lex(); // Eat the % token.
1606 const AsmToken &nextTok = Parser.getTok();
1607 if (nextTok.isNot(AsmToken::Identifier))
1610 Str += nextTok.getIdentifier();
1611 Parser.Lex(); // Eat the identifier.
1612 if (getLexer().getKind() != AsmToken::LParen)
1617 if (getParser().parseParenExpression(IdVal, EndLoc))
1620 while (getLexer().getKind() == AsmToken::RParen)
1621 Parser.Lex(); // Eat the ')' token.
1624 return true; // Parenthesis must follow the relocation operand.
1626 Res = evaluateRelocExpr(IdVal, Str);
1630 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1632 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
1633 OperandMatchResultTy ResTy = ParseAnyRegister(Operands);
1634 if (ResTy == MatchOperand_Success) {
1635 assert(Operands.size() == 1);
1636 MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
1637 StartLoc = Operand.getStartLoc();
1638 EndLoc = Operand.getEndLoc();
1640 // AFAIK, we only support numeric registers and named GPR's in CFI
1642 // Don't worry about eating tokens before failing. Using an unrecognised
1643 // register is a parse error.
1644 if (Operand.isGPRAsmReg()) {
1645 // Resolve to GPR32 or GPR64 appropriately.
1646 RegNo = isGP64() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
1649 return (RegNo == (unsigned)-1);
1652 assert(Operands.size() == 0);
1653 return (RegNo == (unsigned)-1);
1656 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1660 while (getLexer().getKind() == AsmToken::LParen)
1663 switch (getLexer().getKind()) {
1666 case AsmToken::Identifier:
1667 case AsmToken::LParen:
1668 case AsmToken::Integer:
1669 case AsmToken::Minus:
1670 case AsmToken::Plus:
1672 Result = getParser().parseParenExpression(Res, S);
1674 Result = (getParser().parseExpression(Res));
1675 while (getLexer().getKind() == AsmToken::RParen)
1678 case AsmToken::Percent:
1679 Result = parseRelocOperand(Res);
1684 MipsAsmParser::OperandMatchResultTy
1685 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
1686 DEBUG(dbgs() << "parseMemOperand\n");
1687 const MCExpr *IdVal = nullptr;
1689 bool isParenExpr = false;
1690 MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1691 // First operand is the offset.
1692 S = Parser.getTok().getLoc();
1694 if (getLexer().getKind() == AsmToken::LParen) {
1699 if (getLexer().getKind() != AsmToken::Dollar) {
1700 if (parseMemOffset(IdVal, isParenExpr))
1701 return MatchOperand_ParseFail;
1703 const AsmToken &Tok = Parser.getTok(); // Get the next token.
1704 if (Tok.isNot(AsmToken::LParen)) {
1705 MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
1706 if (Mnemonic.getToken() == "la") {
1708 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1709 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1710 return MatchOperand_Success;
1712 if (Tok.is(AsmToken::EndOfStatement)) {
1714 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1716 // Zero register assumed, add a memory operand with ZERO as its base.
1717 // "Base" will be managed by k_Memory.
1718 auto Base = MipsOperand::CreateGPRReg(0, getContext().getRegisterInfo(),
1721 MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
1722 return MatchOperand_Success;
1724 Error(Parser.getTok().getLoc(), "'(' expected");
1725 return MatchOperand_ParseFail;
1728 Parser.Lex(); // Eat the '(' token.
1731 Res = ParseAnyRegister(Operands);
1732 if (Res != MatchOperand_Success)
1735 if (Parser.getTok().isNot(AsmToken::RParen)) {
1736 Error(Parser.getTok().getLoc(), "')' expected");
1737 return MatchOperand_ParseFail;
1740 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1742 Parser.Lex(); // Eat the ')' token.
1745 IdVal = MCConstantExpr::Create(0, getContext());
1747 // Replace the register operand with the memory operand.
1748 std::unique_ptr<MipsOperand> op(
1749 static_cast<MipsOperand *>(Operands.back().release()));
1750 // Remove the register from the operands.
1751 // "op" will be managed by k_Memory.
1752 Operands.pop_back();
1753 // Add the memory operand.
1754 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1756 if (IdVal->EvaluateAsAbsolute(Imm))
1757 IdVal = MCConstantExpr::Create(Imm, getContext());
1758 else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1759 IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1763 Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
1764 return MatchOperand_Success;
1767 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
1769 MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
1771 SMLoc S = Parser.getTok().getLoc();
1773 if (Sym->isVariable())
1774 Expr = Sym->getVariableValue();
1777 if (Expr->getKind() == MCExpr::SymbolRef) {
1778 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
1779 const StringRef DefSymbol = Ref->getSymbol().getName();
1780 if (DefSymbol.startswith("$")) {
1781 OperandMatchResultTy ResTy =
1782 MatchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
1783 if (ResTy == MatchOperand_Success) {
1786 } else if (ResTy == MatchOperand_ParseFail)
1787 llvm_unreachable("Should never ParseFail");
1790 } else if (Expr->getKind() == MCExpr::Constant) {
1792 const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
1794 MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
1801 MipsAsmParser::OperandMatchResultTy
1802 MipsAsmParser::MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
1803 StringRef Identifier,
1805 int Index = matchCPURegisterName(Identifier);
1807 Operands.push_back(MipsOperand::CreateGPRReg(
1808 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1809 return MatchOperand_Success;
1812 Index = matchFPURegisterName(Identifier);
1814 Operands.push_back(MipsOperand::CreateFGRReg(
1815 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1816 return MatchOperand_Success;
1819 Index = matchFCCRegisterName(Identifier);
1821 Operands.push_back(MipsOperand::CreateFCCReg(
1822 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1823 return MatchOperand_Success;
1826 Index = matchACRegisterName(Identifier);
1828 Operands.push_back(MipsOperand::CreateACCReg(
1829 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1830 return MatchOperand_Success;
1833 Index = matchMSA128RegisterName(Identifier);
1835 Operands.push_back(MipsOperand::CreateMSA128Reg(
1836 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1837 return MatchOperand_Success;
1840 Index = matchMSA128CtrlRegisterName(Identifier);
1842 Operands.push_back(MipsOperand::CreateMSACtrlReg(
1843 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1844 return MatchOperand_Success;
1847 return MatchOperand_NoMatch;
1850 MipsAsmParser::OperandMatchResultTy
1851 MipsAsmParser::MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
1852 auto Token = Parser.getLexer().peekTok(false);
1854 if (Token.is(AsmToken::Identifier)) {
1855 DEBUG(dbgs() << ".. identifier\n");
1856 StringRef Identifier = Token.getIdentifier();
1857 OperandMatchResultTy ResTy =
1858 MatchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
1860 } else if (Token.is(AsmToken::Integer)) {
1861 DEBUG(dbgs() << ".. integer\n");
1862 Operands.push_back(MipsOperand::CreateNumericReg(
1863 Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
1865 return MatchOperand_Success;
1868 DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
1870 return MatchOperand_NoMatch;
1873 MipsAsmParser::OperandMatchResultTy
1874 MipsAsmParser::ParseAnyRegister(OperandVector &Operands) {
1875 DEBUG(dbgs() << "ParseAnyRegister\n");
1877 auto Token = Parser.getTok();
1879 SMLoc S = Token.getLoc();
1881 if (Token.isNot(AsmToken::Dollar)) {
1882 DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
1883 if (Token.is(AsmToken::Identifier)) {
1884 if (searchSymbolAlias(Operands))
1885 return MatchOperand_Success;
1887 DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
1888 return MatchOperand_NoMatch;
1890 DEBUG(dbgs() << ".. $\n");
1892 OperandMatchResultTy ResTy = MatchAnyRegisterWithoutDollar(Operands, S);
1893 if (ResTy == MatchOperand_Success) {
1895 Parser.Lex(); // identifier
1900 MipsAsmParser::OperandMatchResultTy
1901 MipsAsmParser::ParseImm(OperandVector &Operands) {
1902 switch (getLexer().getKind()) {
1904 return MatchOperand_NoMatch;
1905 case AsmToken::LParen:
1906 case AsmToken::Minus:
1907 case AsmToken::Plus:
1908 case AsmToken::Integer:
1909 case AsmToken::String:
1913 const MCExpr *IdVal;
1914 SMLoc S = Parser.getTok().getLoc();
1915 if (getParser().parseExpression(IdVal))
1916 return MatchOperand_ParseFail;
1918 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1919 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1920 return MatchOperand_Success;
1923 MipsAsmParser::OperandMatchResultTy
1924 MipsAsmParser::ParseJumpTarget(OperandVector &Operands) {
1925 DEBUG(dbgs() << "ParseJumpTarget\n");
1927 SMLoc S = getLexer().getLoc();
1929 // Integers and expressions are acceptable
1930 OperandMatchResultTy ResTy = ParseImm(Operands);
1931 if (ResTy != MatchOperand_NoMatch)
1934 // Registers are a valid target and have priority over symbols.
1935 ResTy = ParseAnyRegister(Operands);
1936 if (ResTy != MatchOperand_NoMatch)
1939 const MCExpr *Expr = nullptr;
1940 if (Parser.parseExpression(Expr)) {
1941 // We have no way of knowing if a symbol was consumed so we must ParseFail
1942 return MatchOperand_ParseFail;
1945 MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
1946 return MatchOperand_Success;
1949 MipsAsmParser::OperandMatchResultTy
1950 MipsAsmParser::parseInvNum(OperandVector &Operands) {
1951 const MCExpr *IdVal;
1952 // If the first token is '$' we may have register operand.
1953 if (Parser.getTok().is(AsmToken::Dollar))
1954 return MatchOperand_NoMatch;
1955 SMLoc S = Parser.getTok().getLoc();
1956 if (getParser().parseExpression(IdVal))
1957 return MatchOperand_ParseFail;
1958 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
1959 assert(MCE && "Unexpected MCExpr type.");
1960 int64_t Val = MCE->getValue();
1961 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1962 Operands.push_back(MipsOperand::CreateImm(
1963 MCConstantExpr::Create(0 - Val, getContext()), S, E, *this));
1964 return MatchOperand_Success;
1967 MipsAsmParser::OperandMatchResultTy
1968 MipsAsmParser::ParseLSAImm(OperandVector &Operands) {
1969 switch (getLexer().getKind()) {
1971 return MatchOperand_NoMatch;
1972 case AsmToken::LParen:
1973 case AsmToken::Plus:
1974 case AsmToken::Minus:
1975 case AsmToken::Integer:
1980 SMLoc S = Parser.getTok().getLoc();
1982 if (getParser().parseExpression(Expr))
1983 return MatchOperand_ParseFail;
1986 if (!Expr->EvaluateAsAbsolute(Val)) {
1987 Error(S, "expected immediate value");
1988 return MatchOperand_ParseFail;
1991 // The LSA instruction allows a 2-bit unsigned immediate. For this reason
1992 // and because the CPU always adds one to the immediate field, the allowed
1993 // range becomes 1..4. We'll only check the range here and will deal
1994 // with the addition/subtraction when actually decoding/encoding
1996 if (Val < 1 || Val > 4) {
1997 Error(S, "immediate not in range (1..4)");
1998 return MatchOperand_ParseFail;
2002 MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
2003 return MatchOperand_Success;
2006 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
2008 MCSymbolRefExpr::VariantKind VK =
2009 StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
2010 .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
2011 .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
2012 .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
2013 .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
2014 .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
2015 .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
2016 .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
2017 .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
2018 .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
2019 .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
2020 .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
2021 .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
2022 .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
2023 .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
2024 .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
2025 .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
2026 .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
2027 .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
2028 .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
2029 .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
2030 .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
2031 .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
2032 .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
2033 .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
2034 .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
2035 .Default(MCSymbolRefExpr::VK_None);
2037 assert(VK != MCSymbolRefExpr::VK_None);
2042 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
2044 /// ::= '(', register, ')'
2045 /// handle it before we iterate so we don't get tripped up by the lack of
2047 bool MipsAsmParser::ParseParenSuffix(StringRef Name, OperandVector &Operands) {
2048 if (getLexer().is(AsmToken::LParen)) {
2050 MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
2052 if (ParseOperand(Operands, Name)) {
2053 SMLoc Loc = getLexer().getLoc();
2054 Parser.eatToEndOfStatement();
2055 return Error(Loc, "unexpected token in argument list");
2057 if (Parser.getTok().isNot(AsmToken::RParen)) {
2058 SMLoc Loc = getLexer().getLoc();
2059 Parser.eatToEndOfStatement();
2060 return Error(Loc, "unexpected token, expected ')'");
2063 MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
2069 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
2070 /// either one of these.
2071 /// ::= '[', register, ']'
2072 /// ::= '[', integer, ']'
2073 /// handle it before we iterate so we don't get tripped up by the lack of
2075 bool MipsAsmParser::ParseBracketSuffix(StringRef Name,
2076 OperandVector &Operands) {
2077 if (getLexer().is(AsmToken::LBrac)) {
2079 MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
2081 if (ParseOperand(Operands, Name)) {
2082 SMLoc Loc = getLexer().getLoc();
2083 Parser.eatToEndOfStatement();
2084 return Error(Loc, "unexpected token in argument list");
2086 if (Parser.getTok().isNot(AsmToken::RBrac)) {
2087 SMLoc Loc = getLexer().getLoc();
2088 Parser.eatToEndOfStatement();
2089 return Error(Loc, "unexpected token, expected ']'");
2092 MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
2098 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2099 SMLoc NameLoc, OperandVector &Operands) {
2100 DEBUG(dbgs() << "ParseInstruction\n");
2101 // Check if we have valid mnemonic
2102 if (!mnemonicIsValid(Name, 0)) {
2103 Parser.eatToEndOfStatement();
2104 return Error(NameLoc, "Unknown instruction");
2106 // First operand in MCInst is instruction mnemonic.
2107 Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
2109 // Read the remaining operands.
2110 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2111 // Read the first operand.
2112 if (ParseOperand(Operands, Name)) {
2113 SMLoc Loc = getLexer().getLoc();
2114 Parser.eatToEndOfStatement();
2115 return Error(Loc, "unexpected token in argument list");
2117 if (getLexer().is(AsmToken::LBrac) && ParseBracketSuffix(Name, Operands))
2119 // AFAIK, parenthesis suffixes are never on the first operand
2121 while (getLexer().is(AsmToken::Comma)) {
2122 Parser.Lex(); // Eat the comma.
2123 // Parse and remember the operand.
2124 if (ParseOperand(Operands, Name)) {
2125 SMLoc Loc = getLexer().getLoc();
2126 Parser.eatToEndOfStatement();
2127 return Error(Loc, "unexpected token in argument list");
2129 // Parse bracket and parenthesis suffixes before we iterate
2130 if (getLexer().is(AsmToken::LBrac)) {
2131 if (ParseBracketSuffix(Name, Operands))
2133 } else if (getLexer().is(AsmToken::LParen) &&
2134 ParseParenSuffix(Name, Operands))
2138 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2139 SMLoc Loc = getLexer().getLoc();
2140 Parser.eatToEndOfStatement();
2141 return Error(Loc, "unexpected token in argument list");
2143 Parser.Lex(); // Consume the EndOfStatement.
2147 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2148 SMLoc Loc = getLexer().getLoc();
2149 Parser.eatToEndOfStatement();
2150 return Error(Loc, ErrorMsg);
2153 bool MipsAsmParser::reportParseError(SMLoc Loc, StringRef ErrorMsg) {
2154 return Error(Loc, ErrorMsg);
2157 bool MipsAsmParser::parseSetNoAtDirective() {
2158 // Line should look like: ".set noat".
2160 Options.setATReg(0);
2163 // If this is not the end of the statement, report an error.
2164 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2165 reportParseError("unexpected token in statement");
2168 Parser.Lex(); // Consume the EndOfStatement.
2172 bool MipsAsmParser::parseSetAtDirective() {
2173 // Line can be .set at - defaults to $1
2177 if (getLexer().is(AsmToken::EndOfStatement)) {
2178 Options.setATReg(1);
2179 Parser.Lex(); // Consume the EndOfStatement.
2181 } else if (getLexer().is(AsmToken::Equal)) {
2182 getParser().Lex(); // Eat the '='.
2183 if (getLexer().isNot(AsmToken::Dollar)) {
2184 reportParseError("unexpected token in statement");
2187 Parser.Lex(); // Eat the '$'.
2188 const AsmToken &Reg = Parser.getTok();
2189 if (Reg.is(AsmToken::Identifier)) {
2190 AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2191 } else if (Reg.is(AsmToken::Integer)) {
2192 AtRegNo = Reg.getIntVal();
2194 reportParseError("unexpected token in statement");
2198 if (AtRegNo < 0 || AtRegNo > 31) {
2199 reportParseError("unexpected token in statement");
2203 if (!Options.setATReg(AtRegNo)) {
2204 reportParseError("unexpected token in statement");
2207 getParser().Lex(); // Eat the register.
2209 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2210 reportParseError("unexpected token in statement");
2213 Parser.Lex(); // Consume the EndOfStatement.
2216 reportParseError("unexpected token in statement");
2221 bool MipsAsmParser::parseSetReorderDirective() {
2223 // If this is not the end of the statement, report an error.
2224 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2225 reportParseError("unexpected token in statement");
2228 Options.setReorder();
2229 getTargetStreamer().emitDirectiveSetReorder();
2230 Parser.Lex(); // Consume the EndOfStatement.
2234 bool MipsAsmParser::parseSetNoReorderDirective() {
2236 // If this is not the end of the statement, report an error.
2237 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238 reportParseError("unexpected token in statement");
2241 Options.setNoreorder();
2242 getTargetStreamer().emitDirectiveSetNoReorder();
2243 Parser.Lex(); // Consume the EndOfStatement.
2247 bool MipsAsmParser::parseSetMacroDirective() {
2249 // If this is not the end of the statement, report an error.
2250 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2251 reportParseError("unexpected token in statement");
2255 Parser.Lex(); // Consume the EndOfStatement.
2259 bool MipsAsmParser::parseSetNoMacroDirective() {
2261 // If this is not the end of the statement, report an error.
2262 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2263 reportParseError("`noreorder' must be set before `nomacro'");
2266 if (Options.isReorder()) {
2267 reportParseError("`noreorder' must be set before `nomacro'");
2270 Options.setNomacro();
2271 Parser.Lex(); // Consume the EndOfStatement.
2275 bool MipsAsmParser::parseSetNoMips16Directive() {
2277 // If this is not the end of the statement, report an error.
2278 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2279 reportParseError("unexpected token in statement");
2282 // For now do nothing.
2283 Parser.Lex(); // Consume the EndOfStatement.
2287 bool MipsAsmParser::parseSetAssignment() {
2289 const MCExpr *Value;
2291 if (Parser.parseIdentifier(Name))
2292 reportParseError("expected identifier after .set");
2294 if (getLexer().isNot(AsmToken::Comma))
2295 return reportParseError("unexpected token in .set directive");
2298 if (Parser.parseExpression(Value))
2299 return reportParseError("expected valid expression after comma");
2301 // Check if the Name already exists as a symbol.
2302 MCSymbol *Sym = getContext().LookupSymbol(Name);
2304 return reportParseError("symbol already defined");
2305 Sym = getContext().GetOrCreateSymbol(Name);
2306 Sym->setVariableValue(Value);
2311 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2313 if (getLexer().isNot(AsmToken::EndOfStatement))
2314 return reportParseError("unexpected token in .set directive");
2318 llvm_unreachable("Unimplemented feature");
2319 case Mips::FeatureDSP:
2320 setFeatureBits(Mips::FeatureDSP, "dsp");
2321 getTargetStreamer().emitDirectiveSetDsp();
2323 case Mips::FeatureMicroMips:
2324 getTargetStreamer().emitDirectiveSetMicroMips();
2326 case Mips::FeatureMips16:
2327 getTargetStreamer().emitDirectiveSetMips16();
2329 case Mips::FeatureMips32r2:
2330 setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2331 getTargetStreamer().emitDirectiveSetMips32R2();
2333 case Mips::FeatureMips64:
2334 setFeatureBits(Mips::FeatureMips64, "mips64");
2335 getTargetStreamer().emitDirectiveSetMips64();
2337 case Mips::FeatureMips64r2:
2338 setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2339 getTargetStreamer().emitDirectiveSetMips64R2();
2345 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2346 if (!getLexer().is(AsmToken::Dollar))
2351 const AsmToken &Reg = Parser.getTok();
2352 if (Reg.is(AsmToken::Identifier)) {
2353 RegNum = matchCPURegisterName(Reg.getIdentifier());
2354 } else if (Reg.is(AsmToken::Integer)) {
2355 RegNum = Reg.getIntVal();
2364 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2365 if (getLexer().isNot(AsmToken::Comma)) {
2366 SMLoc Loc = getLexer().getLoc();
2367 Parser.eatToEndOfStatement();
2368 return Error(Loc, ErrorStr);
2371 Parser.Lex(); // Eat the comma.
2375 bool MipsAsmParser::parseDirectiveCPLoad(SMLoc Loc) {
2376 if (Options.isReorder())
2377 Warning(Loc, ".cpload in reorder section");
2379 // FIXME: Warn if cpload is used in Mips16 mode.
2381 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
2382 OperandMatchResultTy ResTy = ParseAnyRegister(Reg);
2383 if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
2384 reportParseError("expected register containing function address");
2388 MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
2389 if (!RegOpnd.isGPRAsmReg()) {
2390 reportParseError(RegOpnd.getStartLoc(), "invalid register");
2394 getTargetStreamer().emitDirectiveCpload(RegOpnd.getGPR32Reg());
2398 bool MipsAsmParser::parseDirectiveCPSetup() {
2401 bool SaveIsReg = true;
2403 if (!parseRegister(FuncReg))
2404 return reportParseError("expected register containing function address");
2405 FuncReg = getGPR(FuncReg);
2407 if (!eatComma("expected comma parsing directive"))
2410 if (!parseRegister(Save)) {
2411 const AsmToken &Tok = Parser.getTok();
2412 if (Tok.is(AsmToken::Integer)) {
2413 Save = Tok.getIntVal();
2417 return reportParseError("expected save register or stack offset");
2419 Save = getGPR(Save);
2421 if (!eatComma("expected comma parsing directive"))
2425 if (Parser.parseIdentifier(Name))
2426 reportParseError("expected identifier");
2427 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2429 getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, *Sym, SaveIsReg);
2433 bool MipsAsmParser::parseDirectiveNaN() {
2434 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2435 const AsmToken &Tok = Parser.getTok();
2437 if (Tok.getString() == "2008") {
2439 getTargetStreamer().emitDirectiveNaN2008();
2441 } else if (Tok.getString() == "legacy") {
2443 getTargetStreamer().emitDirectiveNaNLegacy();
2447 // If we don't recognize the option passed to the .nan
2448 // directive (e.g. no option or unknown option), emit an error.
2449 reportParseError("invalid option in .nan directive");
2453 bool MipsAsmParser::parseDirectiveSet() {
2455 // Get the next token.
2456 const AsmToken &Tok = Parser.getTok();
2458 if (Tok.getString() == "noat") {
2459 return parseSetNoAtDirective();
2460 } else if (Tok.getString() == "at") {
2461 return parseSetAtDirective();
2462 } else if (Tok.getString() == "reorder") {
2463 return parseSetReorderDirective();
2464 } else if (Tok.getString() == "noreorder") {
2465 return parseSetNoReorderDirective();
2466 } else if (Tok.getString() == "macro") {
2467 return parseSetMacroDirective();
2468 } else if (Tok.getString() == "nomacro") {
2469 return parseSetNoMacroDirective();
2470 } else if (Tok.getString() == "mips16") {
2471 return parseSetFeature(Mips::FeatureMips16);
2472 } else if (Tok.getString() == "nomips16") {
2473 return parseSetNoMips16Directive();
2474 } else if (Tok.getString() == "nomicromips") {
2475 getTargetStreamer().emitDirectiveSetNoMicroMips();
2476 Parser.eatToEndOfStatement();
2478 } else if (Tok.getString() == "micromips") {
2479 return parseSetFeature(Mips::FeatureMicroMips);
2480 } else if (Tok.getString() == "mips32r2") {
2481 return parseSetFeature(Mips::FeatureMips32r2);
2482 } else if (Tok.getString() == "mips64") {
2483 return parseSetFeature(Mips::FeatureMips64);
2484 } else if (Tok.getString() == "mips64r2") {
2485 return parseSetFeature(Mips::FeatureMips64r2);
2486 } else if (Tok.getString() == "dsp") {
2487 return parseSetFeature(Mips::FeatureDSP);
2489 // It is just an identifier, look for an assignment.
2490 parseSetAssignment();
2497 /// parseDataDirective
2498 /// ::= .word [ expression (, expression)* ]
2499 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2500 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2502 const MCExpr *Value;
2503 if (getParser().parseExpression(Value))
2506 getParser().getStreamer().EmitValue(Value, Size);
2508 if (getLexer().is(AsmToken::EndOfStatement))
2511 // FIXME: Improve diagnostic.
2512 if (getLexer().isNot(AsmToken::Comma))
2513 return Error(L, "unexpected token in directive");
2522 /// parseDirectiveGpWord
2523 /// ::= .gpword local_sym
2524 bool MipsAsmParser::parseDirectiveGpWord() {
2525 const MCExpr *Value;
2526 // EmitGPRel32Value requires an expression, so we are using base class
2527 // method to evaluate the expression.
2528 if (getParser().parseExpression(Value))
2530 getParser().getStreamer().EmitGPRel32Value(Value);
2532 if (getLexer().isNot(AsmToken::EndOfStatement))
2533 return Error(getLexer().getLoc(), "unexpected token in directive");
2534 Parser.Lex(); // Eat EndOfStatement token.
2538 /// parseDirectiveGpDWord
2539 /// ::= .gpdword local_sym
2540 bool MipsAsmParser::parseDirectiveGpDWord() {
2541 const MCExpr *Value;
2542 // EmitGPRel64Value requires an expression, so we are using base class
2543 // method to evaluate the expression.
2544 if (getParser().parseExpression(Value))
2546 getParser().getStreamer().EmitGPRel64Value(Value);
2548 if (getLexer().isNot(AsmToken::EndOfStatement))
2549 return Error(getLexer().getLoc(), "unexpected token in directive");
2550 Parser.Lex(); // Eat EndOfStatement token.
2554 bool MipsAsmParser::parseDirectiveOption() {
2555 // Get the option token.
2556 AsmToken Tok = Parser.getTok();
2557 // At the moment only identifiers are supported.
2558 if (Tok.isNot(AsmToken::Identifier)) {
2559 Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2560 Parser.eatToEndOfStatement();
2564 StringRef Option = Tok.getIdentifier();
2566 if (Option == "pic0") {
2567 getTargetStreamer().emitDirectiveOptionPic0();
2569 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2570 Error(Parser.getTok().getLoc(),
2571 "unexpected token in .option pic0 directive");
2572 Parser.eatToEndOfStatement();
2577 if (Option == "pic2") {
2578 getTargetStreamer().emitDirectiveOptionPic2();
2580 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2581 Error(Parser.getTok().getLoc(),
2582 "unexpected token in .option pic2 directive");
2583 Parser.eatToEndOfStatement();
2589 Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2590 Parser.eatToEndOfStatement();
2594 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2595 StringRef IDVal = DirectiveID.getString();
2597 if (IDVal == ".cpload")
2598 return parseDirectiveCPLoad(DirectiveID.getLoc());
2599 if (IDVal == ".dword") {
2600 parseDataDirective(8, DirectiveID.getLoc());
2604 if (IDVal == ".ent") {
2605 // Ignore this directive for now.
2610 if (IDVal == ".end") {
2611 // Ignore this directive for now.
2616 if (IDVal == ".frame") {
2617 // Ignore this directive for now.
2618 Parser.eatToEndOfStatement();
2622 if (IDVal == ".set") {
2623 return parseDirectiveSet();
2626 if (IDVal == ".fmask") {
2627 // Ignore this directive for now.
2628 Parser.eatToEndOfStatement();
2632 if (IDVal == ".mask") {
2633 // Ignore this directive for now.
2634 Parser.eatToEndOfStatement();
2638 if (IDVal == ".nan")
2639 return parseDirectiveNaN();
2641 if (IDVal == ".gpword") {
2642 parseDirectiveGpWord();
2646 if (IDVal == ".gpdword") {
2647 parseDirectiveGpDWord();
2651 if (IDVal == ".word") {
2652 parseDataDirective(4, DirectiveID.getLoc());
2656 if (IDVal == ".option")
2657 return parseDirectiveOption();
2659 if (IDVal == ".abicalls") {
2660 getTargetStreamer().emitDirectiveAbiCalls();
2661 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2662 Error(Parser.getTok().getLoc(), "unexpected token in directive");
2664 Parser.eatToEndOfStatement();
2669 if (IDVal == ".cpsetup")
2670 return parseDirectiveCPSetup();
2675 extern "C" void LLVMInitializeMipsAsmParser() {
2676 RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2677 RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2678 RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2679 RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2682 #define GET_REGISTER_MATCHER
2683 #define GET_MATCHER_IMPLEMENTATION
2684 #include "MipsGenAsmMatcher.inc"