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 parseRegister(unsigned &RegNum);
179 bool eatComma(StringRef ErrorStr);
181 int matchCPURegisterName(StringRef Symbol);
183 int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
185 int matchFPURegisterName(StringRef Name);
187 int matchFCCRegisterName(StringRef Name);
189 int matchACRegisterName(StringRef Name);
191 int matchMSA128RegisterName(StringRef Name);
193 int matchMSA128CtrlRegisterName(StringRef Name);
195 unsigned getReg(int RC, int RegNo);
197 unsigned getGPR(int RegNo);
201 bool processInstruction(MCInst &Inst, SMLoc IDLoc,
202 SmallVectorImpl<MCInst> &Instructions);
204 // Helper function that checks if the value of a vector index is within the
205 // boundaries of accepted values for each RegisterKind
206 // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
207 bool validateMSAIndex(int Val, int RegKind);
209 void setFeatureBits(unsigned Feature, StringRef FeatureString) {
210 if (!(STI.getFeatureBits() & Feature)) {
211 setAvailableFeatures(
212 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
216 void clearFeatureBits(unsigned Feature, StringRef FeatureString) {
217 if (STI.getFeatureBits() & Feature) {
218 setAvailableFeatures(
219 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
224 enum MipsMatchResultTy {
225 Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY
226 #define GET_OPERAND_DIAGNOSTIC_TYPES
227 #include "MipsGenAsmMatcher.inc"
228 #undef GET_OPERAND_DIAGNOSTIC_TYPES
232 MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
233 const MCInstrInfo &MII,
234 const MCTargetOptions &Options)
235 : MCTargetAsmParser(), STI(sti), Parser(parser) {
236 // Initialize the set of available features.
237 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
239 // Assert exactly one ABI was chosen.
240 assert((((STI.getFeatureBits() & Mips::FeatureO32) != 0) +
241 ((STI.getFeatureBits() & Mips::FeatureEABI) != 0) +
242 ((STI.getFeatureBits() & Mips::FeatureN32) != 0) +
243 ((STI.getFeatureBits() & Mips::FeatureN64) != 0)) == 1);
246 MCAsmParser &getParser() const { return Parser; }
247 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
249 /// Warn if RegNo is the current assembler temporary.
250 void WarnIfAssemblerTemporary(int RegNo, SMLoc Loc);
256 /// MipsOperand - Instances of this class represent a parsed Mips machine
258 class MipsOperand : public MCParsedAsmOperand {
260 /// Broad categories of register classes
261 /// The exact class is finalized by the render method.
263 RegKind_GPR = 1, /// GPR32 and GPR64 (depending on isGP64())
264 RegKind_FGR = 2, /// FGR32, FGR64, AFGR64 (depending on context and
266 RegKind_FCC = 4, /// FCC
267 RegKind_MSA128 = 8, /// MSA128[BHWD] (makes no difference which)
268 RegKind_MSACtrl = 16, /// MSA control registers
269 RegKind_COP2 = 32, /// COP2
270 RegKind_ACC = 64, /// HI32DSP, LO32DSP, and ACC64DSP (depending on
272 RegKind_CCR = 128, /// CCR
273 RegKind_HWRegs = 256, /// HWRegs
274 RegKind_COP3 = 512, /// COP3
276 /// Potentially any (e.g. $1)
277 RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
278 RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
279 RegKind_CCR | RegKind_HWRegs | RegKind_COP3
284 k_Immediate, /// An immediate (possibly involving symbol references)
285 k_Memory, /// Base + Offset Memory Address
286 k_PhysRegister, /// A physical register from the Mips namespace
287 k_RegisterIndex, /// A register index in one or more RegKind.
288 k_Token /// A simple token
292 MipsOperand(KindTy K, MipsAsmParser &Parser)
293 : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
296 /// For diagnostics, and checking the assembler temporary
297 MipsAsmParser &AsmParser;
305 unsigned Num; /// Register Number
309 unsigned Index; /// Index into the register class
310 RegKind Kind; /// Bitfield of the kinds it could possibly be
311 const MCRegisterInfo *RegInfo;
325 struct PhysRegOp PhysReg;
326 struct RegIdxOp RegIdx;
331 SMLoc StartLoc, EndLoc;
333 /// Internal constructor for register kinds
334 static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
335 const MCRegisterInfo *RegInfo,
337 MipsAsmParser &Parser) {
338 auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
339 Op->RegIdx.Index = Index;
340 Op->RegIdx.RegInfo = RegInfo;
341 Op->RegIdx.Kind = RegKind;
348 /// Coerce the register to GPR32 and return the real register for the current
350 unsigned getGPR32Reg() const {
351 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
352 AsmParser.WarnIfAssemblerTemporary(RegIdx.Index, StartLoc);
353 unsigned ClassID = Mips::GPR32RegClassID;
354 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
357 /// Coerce the register to GPR64 and return the real register for the current
359 unsigned getGPR64Reg() const {
360 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
361 unsigned ClassID = Mips::GPR64RegClassID;
362 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
366 /// Coerce the register to AFGR64 and return the real register for the current
368 unsigned getAFGR64Reg() const {
369 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
370 if (RegIdx.Index % 2 != 0)
371 AsmParser.Warning(StartLoc, "Float register should be even.");
372 return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
373 .getRegister(RegIdx.Index / 2);
376 /// Coerce the register to FGR64 and return the real register for the current
378 unsigned getFGR64Reg() const {
379 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
380 return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
381 .getRegister(RegIdx.Index);
384 /// Coerce the register to FGR32 and return the real register for the current
386 unsigned getFGR32Reg() const {
387 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
388 return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
389 .getRegister(RegIdx.Index);
392 /// Coerce the register to FGRH32 and return the real register for the current
394 unsigned getFGRH32Reg() const {
395 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
396 return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
397 .getRegister(RegIdx.Index);
400 /// Coerce the register to FCC and return the real register for the current
402 unsigned getFCCReg() const {
403 assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
404 return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
405 .getRegister(RegIdx.Index);
408 /// Coerce the register to MSA128 and return the real register for the current
410 unsigned getMSA128Reg() const {
411 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
412 // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
414 unsigned ClassID = Mips::MSA128BRegClassID;
415 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
418 /// Coerce the register to MSACtrl and return the real register for the
420 unsigned getMSACtrlReg() const {
421 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
422 unsigned ClassID = Mips::MSACtrlRegClassID;
423 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
426 /// Coerce the register to COP2 and return the real register for the
428 unsigned getCOP2Reg() const {
429 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
430 unsigned ClassID = Mips::COP2RegClassID;
431 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
434 /// Coerce the register to COP3 and return the real register for the
436 unsigned getCOP3Reg() const {
437 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
438 unsigned ClassID = Mips::COP3RegClassID;
439 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
442 /// Coerce the register to ACC64DSP and return the real register for the
444 unsigned getACC64DSPReg() const {
445 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
446 unsigned ClassID = Mips::ACC64DSPRegClassID;
447 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
450 /// Coerce the register to HI32DSP and return the real register for the
452 unsigned getHI32DSPReg() const {
453 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
454 unsigned ClassID = Mips::HI32DSPRegClassID;
455 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
458 /// Coerce the register to LO32DSP and return the real register for the
460 unsigned getLO32DSPReg() const {
461 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
462 unsigned ClassID = Mips::LO32DSPRegClassID;
463 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
466 /// Coerce the register to CCR and return the real register for the
468 unsigned getCCRReg() const {
469 assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
470 unsigned ClassID = Mips::CCRRegClassID;
471 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
474 /// Coerce the register to HWRegs and return the real register for the
476 unsigned getHWRegsReg() const {
477 assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
478 unsigned ClassID = Mips::HWRegsRegClassID;
479 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
483 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
484 // Add as immediate when possible. Null MCExpr = 0.
486 Inst.addOperand(MCOperand::CreateImm(0));
487 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
488 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
490 Inst.addOperand(MCOperand::CreateExpr(Expr));
493 void addRegOperands(MCInst &Inst, unsigned N) const {
494 llvm_unreachable("Use a custom parser instead");
497 /// Render the operand to an MCInst as a GPR32
498 /// Asserts if the wrong number of operands are requested, or the operand
499 /// is not a k_RegisterIndex compatible with RegKind_GPR
500 void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
501 assert(N == 1 && "Invalid number of operands!");
502 Inst.addOperand(MCOperand::CreateReg(getGPR32Reg()));
505 /// Render the operand to an MCInst as a GPR64
506 /// Asserts if the wrong number of operands are requested, or the operand
507 /// is not a k_RegisterIndex compatible with RegKind_GPR
508 void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
509 assert(N == 1 && "Invalid number of operands!");
510 Inst.addOperand(MCOperand::CreateReg(getGPR64Reg()));
513 void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
514 assert(N == 1 && "Invalid number of operands!");
515 Inst.addOperand(MCOperand::CreateReg(getAFGR64Reg()));
518 void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
519 assert(N == 1 && "Invalid number of operands!");
520 Inst.addOperand(MCOperand::CreateReg(getFGR64Reg()));
523 void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
524 assert(N == 1 && "Invalid number of operands!");
525 Inst.addOperand(MCOperand::CreateReg(getFGR32Reg()));
528 void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
529 assert(N == 1 && "Invalid number of operands!");
530 Inst.addOperand(MCOperand::CreateReg(getFGRH32Reg()));
533 void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
534 assert(N == 1 && "Invalid number of operands!");
535 Inst.addOperand(MCOperand::CreateReg(getFCCReg()));
538 void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
539 assert(N == 1 && "Invalid number of operands!");
540 Inst.addOperand(MCOperand::CreateReg(getMSA128Reg()));
543 void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
544 assert(N == 1 && "Invalid number of operands!");
545 Inst.addOperand(MCOperand::CreateReg(getMSACtrlReg()));
548 void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
549 assert(N == 1 && "Invalid number of operands!");
550 Inst.addOperand(MCOperand::CreateReg(getCOP2Reg()));
553 void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
554 assert(N == 1 && "Invalid number of operands!");
555 Inst.addOperand(MCOperand::CreateReg(getCOP3Reg()));
558 void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
559 assert(N == 1 && "Invalid number of operands!");
560 Inst.addOperand(MCOperand::CreateReg(getACC64DSPReg()));
563 void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
564 assert(N == 1 && "Invalid number of operands!");
565 Inst.addOperand(MCOperand::CreateReg(getHI32DSPReg()));
568 void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
569 assert(N == 1 && "Invalid number of operands!");
570 Inst.addOperand(MCOperand::CreateReg(getLO32DSPReg()));
573 void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
574 assert(N == 1 && "Invalid number of operands!");
575 Inst.addOperand(MCOperand::CreateReg(getCCRReg()));
578 void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
579 assert(N == 1 && "Invalid number of operands!");
580 Inst.addOperand(MCOperand::CreateReg(getHWRegsReg()));
583 void addImmOperands(MCInst &Inst, unsigned N) const {
584 assert(N == 1 && "Invalid number of operands!");
585 const MCExpr *Expr = getImm();
589 void addMemOperands(MCInst &Inst, unsigned N) const {
590 assert(N == 2 && "Invalid number of operands!");
592 Inst.addOperand(MCOperand::CreateReg(getMemBase()->getGPR32Reg()));
594 const MCExpr *Expr = getMemOff();
598 bool isReg() const override {
599 // As a special case until we sort out the definition of div/divu, pretend
600 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
601 if (isGPRAsmReg() && RegIdx.Index == 0)
604 return Kind == k_PhysRegister;
606 bool isRegIdx() const { return Kind == k_RegisterIndex; }
607 bool isImm() const override { return Kind == k_Immediate; }
608 bool isConstantImm() const {
609 return isImm() && dyn_cast<MCConstantExpr>(getImm());
611 bool isToken() const override {
612 // Note: It's not possible to pretend that other operand kinds are tokens.
613 // The matcher emitter checks tokens first.
614 return Kind == k_Token;
616 bool isMem() const override { return Kind == k_Memory; }
617 bool isInvNum() const { return Kind == k_Immediate; }
618 bool isLSAImm() const {
619 if (!isConstantImm())
621 int64_t Val = getConstantImm();
622 return 1 <= Val && Val <= 4;
625 StringRef getToken() const {
626 assert(Kind == k_Token && "Invalid access!");
627 return StringRef(Tok.Data, Tok.Length);
630 unsigned getReg() const override {
631 // As a special case until we sort out the definition of div/divu, pretend
632 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
633 if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
634 RegIdx.Kind & RegKind_GPR)
635 return getGPR32Reg(); // FIXME: GPR64 too
637 assert(Kind == k_PhysRegister && "Invalid access!");
641 const MCExpr *getImm() const {
642 assert((Kind == k_Immediate) && "Invalid access!");
646 int64_t getConstantImm() const {
647 const MCExpr *Val = getImm();
648 return static_cast<const MCConstantExpr *>(Val)->getValue();
651 MipsOperand *getMemBase() const {
652 assert((Kind == k_Memory) && "Invalid access!");
656 const MCExpr *getMemOff() const {
657 assert((Kind == k_Memory) && "Invalid access!");
661 static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
662 MipsAsmParser &Parser) {
663 auto Op = make_unique<MipsOperand>(k_Token, Parser);
664 Op->Tok.Data = Str.data();
665 Op->Tok.Length = Str.size();
671 /// Create a numeric register (e.g. $1). The exact register remains
672 /// unresolved until an instruction successfully matches
673 static std::unique_ptr<MipsOperand>
674 CreateNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
675 SMLoc E, MipsAsmParser &Parser) {
676 DEBUG(dbgs() << "CreateNumericReg(" << Index << ", ...)\n");
677 return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
680 /// Create a register that is definitely a GPR.
681 /// This is typically only used for named registers such as $gp.
682 static std::unique_ptr<MipsOperand>
683 CreateGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
684 MipsAsmParser &Parser) {
685 return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
688 /// Create a register that is definitely a FGR.
689 /// This is typically only used for named registers such as $f0.
690 static std::unique_ptr<MipsOperand>
691 CreateFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
692 MipsAsmParser &Parser) {
693 return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
696 /// Create a register that is definitely an FCC.
697 /// This is typically only used for named registers such as $fcc0.
698 static std::unique_ptr<MipsOperand>
699 CreateFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
700 MipsAsmParser &Parser) {
701 return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
704 /// Create a register that is definitely an ACC.
705 /// This is typically only used for named registers such as $ac0.
706 static std::unique_ptr<MipsOperand>
707 CreateACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
708 MipsAsmParser &Parser) {
709 return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
712 /// Create a register that is definitely an MSA128.
713 /// This is typically only used for named registers such as $w0.
714 static std::unique_ptr<MipsOperand>
715 CreateMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
716 SMLoc E, MipsAsmParser &Parser) {
717 return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
720 /// Create a register that is definitely an MSACtrl.
721 /// This is typically only used for named registers such as $msaaccess.
722 static std::unique_ptr<MipsOperand>
723 CreateMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
724 SMLoc E, MipsAsmParser &Parser) {
725 return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
728 static std::unique_ptr<MipsOperand>
729 CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
730 auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
737 static std::unique_ptr<MipsOperand>
738 CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
739 SMLoc E, MipsAsmParser &Parser) {
740 auto Op = make_unique<MipsOperand>(k_Memory, Parser);
741 Op->Mem.Base = Base.release();
748 bool isGPRAsmReg() const {
749 return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
751 bool isFGRAsmReg() const {
752 // AFGR64 is $0-$15 but we handle this in getAFGR64()
753 return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
755 bool isHWRegsAsmReg() const {
756 return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
758 bool isCCRAsmReg() const {
759 return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
761 bool isFCCAsmReg() const {
762 return isRegIdx() && RegIdx.Kind & RegKind_FCC && RegIdx.Index <= 7;
764 bool isACCAsmReg() const {
765 return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
767 bool isCOP2AsmReg() const {
768 return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
770 bool isCOP3AsmReg() const {
771 return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
773 bool isMSA128AsmReg() const {
774 return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
776 bool isMSACtrlAsmReg() const {
777 return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
780 /// getStartLoc - Get the location of the first token of this operand.
781 SMLoc getStartLoc() const override { return StartLoc; }
782 /// getEndLoc - Get the location of the last token of this operand.
783 SMLoc getEndLoc() const override { return EndLoc; }
785 virtual ~MipsOperand() {
793 case k_RegisterIndex:
799 void print(raw_ostream &OS) const override {
814 OS << "PhysReg<" << PhysReg.Num << ">";
816 case k_RegisterIndex:
817 OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
824 }; // class MipsOperand
828 extern const MCInstrDesc MipsInsts[];
830 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
831 return MipsInsts[Opcode];
834 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
835 SmallVectorImpl<MCInst> &Instructions) {
836 const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
840 if (MCID.isBranch() || MCID.isCall()) {
841 const unsigned Opcode = Inst.getOpcode();
851 assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
852 Offset = Inst.getOperand(2);
854 break; // We'll deal with this situation later on when applying fixups.
855 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
856 return Error(IDLoc, "branch target out of range");
857 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
858 return Error(IDLoc, "branch to misaligned address");
872 case Mips::BGEZAL_MM:
873 case Mips::BLTZAL_MM:
876 assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
877 Offset = Inst.getOperand(1);
879 break; // We'll deal with this situation later on when applying fixups.
880 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
881 return Error(IDLoc, "branch target out of range");
882 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
883 return Error(IDLoc, "branch to misaligned address");
888 if (MCID.hasDelaySlot() && Options.isReorder()) {
889 // If this instruction has a delay slot and .set reorder is active,
890 // emit a NOP after it.
891 Instructions.push_back(Inst);
893 NopInst.setOpcode(Mips::SLL);
894 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
895 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
896 NopInst.addOperand(MCOperand::CreateImm(0));
897 Instructions.push_back(NopInst);
901 if (MCID.mayLoad() || MCID.mayStore()) {
902 // Check the offset of memory operand, if it is a symbol
903 // reference or immediate we may have to expand instructions.
904 for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
905 const MCOperandInfo &OpInfo = MCID.OpInfo[i];
906 if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
907 (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
908 MCOperand &Op = Inst.getOperand(i);
910 int MemOffset = Op.getImm();
911 if (MemOffset < -32768 || MemOffset > 32767) {
912 // Offset can't exceed 16bit value.
913 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
916 } else if (Op.isExpr()) {
917 const MCExpr *Expr = Op.getExpr();
918 if (Expr->getKind() == MCExpr::SymbolRef) {
919 const MCSymbolRefExpr *SR =
920 static_cast<const MCSymbolRefExpr *>(Expr);
921 if (SR->getKind() == MCSymbolRefExpr::VK_None) {
923 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
926 } else if (!isEvaluated(Expr)) {
927 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
935 if (needsExpansion(Inst))
936 expandInstruction(Inst, IDLoc, Instructions);
938 Instructions.push_back(Inst);
943 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
945 switch (Inst.getOpcode()) {
946 case Mips::LoadImm32Reg:
947 case Mips::LoadAddr32Imm:
948 case Mips::LoadAddr32Reg:
955 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
956 SmallVectorImpl<MCInst> &Instructions) {
957 switch (Inst.getOpcode()) {
958 case Mips::LoadImm32Reg:
959 return expandLoadImm(Inst, IDLoc, Instructions);
960 case Mips::LoadAddr32Imm:
961 return expandLoadAddressImm(Inst, IDLoc, Instructions);
962 case Mips::LoadAddr32Reg:
963 return expandLoadAddressReg(Inst, IDLoc, Instructions);
967 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
968 SmallVectorImpl<MCInst> &Instructions) {
970 const MCOperand &ImmOp = Inst.getOperand(1);
971 assert(ImmOp.isImm() && "expected immediate operand kind");
972 const MCOperand &RegOp = Inst.getOperand(0);
973 assert(RegOp.isReg() && "expected register operand kind");
975 int ImmValue = ImmOp.getImm();
976 tmpInst.setLoc(IDLoc);
977 if (0 <= ImmValue && ImmValue <= 65535) {
978 // For 0 <= j <= 65535.
979 // li d,j => ori d,$zero,j
980 tmpInst.setOpcode(Mips::ORi);
981 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
982 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
983 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
984 Instructions.push_back(tmpInst);
985 } else if (ImmValue < 0 && ImmValue >= -32768) {
986 // For -32768 <= j < 0.
987 // li d,j => addiu d,$zero,j
988 tmpInst.setOpcode(Mips::ADDiu);
989 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
990 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
991 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
992 Instructions.push_back(tmpInst);
994 // For any other value of j that is representable as a 32-bit integer.
995 // li d,j => lui d,hi16(j)
997 tmpInst.setOpcode(Mips::LUi);
998 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
999 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1000 Instructions.push_back(tmpInst);
1002 tmpInst.setOpcode(Mips::ORi);
1003 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1004 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1005 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1006 tmpInst.setLoc(IDLoc);
1007 Instructions.push_back(tmpInst);
1012 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
1013 SmallVectorImpl<MCInst> &Instructions) {
1015 const MCOperand &ImmOp = Inst.getOperand(2);
1016 assert(ImmOp.isImm() && "expected immediate operand kind");
1017 const MCOperand &SrcRegOp = Inst.getOperand(1);
1018 assert(SrcRegOp.isReg() && "expected register operand kind");
1019 const MCOperand &DstRegOp = Inst.getOperand(0);
1020 assert(DstRegOp.isReg() && "expected register operand kind");
1021 int ImmValue = ImmOp.getImm();
1022 if (-32768 <= ImmValue && ImmValue <= 65535) {
1023 // For -32768 <= j <= 65535.
1024 // la d,j(s) => addiu d,s,j
1025 tmpInst.setOpcode(Mips::ADDiu);
1026 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1027 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1028 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1029 Instructions.push_back(tmpInst);
1031 // For any other value of j that is representable as a 32-bit integer.
1032 // la d,j(s) => lui d,hi16(j)
1035 tmpInst.setOpcode(Mips::LUi);
1036 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1037 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1038 Instructions.push_back(tmpInst);
1040 tmpInst.setOpcode(Mips::ORi);
1041 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1042 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1043 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1044 Instructions.push_back(tmpInst);
1046 tmpInst.setOpcode(Mips::ADDu);
1047 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1048 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1049 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1050 Instructions.push_back(tmpInst);
1055 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
1056 SmallVectorImpl<MCInst> &Instructions) {
1058 const MCOperand &ImmOp = Inst.getOperand(1);
1059 assert(ImmOp.isImm() && "expected immediate operand kind");
1060 const MCOperand &RegOp = Inst.getOperand(0);
1061 assert(RegOp.isReg() && "expected register operand kind");
1062 int ImmValue = ImmOp.getImm();
1063 if (-32768 <= ImmValue && ImmValue <= 65535) {
1064 // For -32768 <= j <= 65535.
1065 // la d,j => addiu d,$zero,j
1066 tmpInst.setOpcode(Mips::ADDiu);
1067 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1068 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1069 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1070 Instructions.push_back(tmpInst);
1072 // For any other value of j that is representable as a 32-bit integer.
1073 // la d,j => lui d,hi16(j)
1075 tmpInst.setOpcode(Mips::LUi);
1076 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1077 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1078 Instructions.push_back(tmpInst);
1080 tmpInst.setOpcode(Mips::ORi);
1081 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1082 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1083 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1084 Instructions.push_back(tmpInst);
1088 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
1089 SmallVectorImpl<MCInst> &Instructions,
1090 bool isLoad, bool isImmOpnd) {
1091 const MCSymbolRefExpr *SR;
1093 unsigned ImmOffset, HiOffset, LoOffset;
1094 const MCExpr *ExprOffset;
1096 unsigned AtRegNum = getReg(
1097 (isGP64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
1098 // 1st operand is either the source or destination register.
1099 assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1100 unsigned RegOpNum = Inst.getOperand(0).getReg();
1101 // 2nd operand is the base register.
1102 assert(Inst.getOperand(1).isReg() && "expected register operand kind");
1103 unsigned BaseRegNum = Inst.getOperand(1).getReg();
1104 // 3rd operand is either an immediate or expression.
1106 assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
1107 ImmOffset = Inst.getOperand(2).getImm();
1108 LoOffset = ImmOffset & 0x0000ffff;
1109 HiOffset = (ImmOffset & 0xffff0000) >> 16;
1110 // If msb of LoOffset is 1(negative number) we must increment HiOffset.
1111 if (LoOffset & 0x8000)
1114 ExprOffset = Inst.getOperand(2).getExpr();
1115 // All instructions will have the same location.
1116 TempInst.setLoc(IDLoc);
1117 // 1st instruction in expansion is LUi. For load instruction we can use
1118 // the dst register as a temporary if base and dst are different,
1119 // but for stores we must use $at.
1120 TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
1121 TempInst.setOpcode(Mips::LUi);
1122 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1124 TempInst.addOperand(MCOperand::CreateImm(HiOffset));
1126 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1127 SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
1128 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
1129 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
1131 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1133 const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
1134 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1137 // Add the instruction to the list.
1138 Instructions.push_back(TempInst);
1139 // Prepare TempInst for next instruction.
1141 // Add temp register to base.
1142 TempInst.setOpcode(Mips::ADDu);
1143 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1144 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1145 TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
1146 Instructions.push_back(TempInst);
1148 // And finally, create original instruction with low part
1149 // of offset and new base.
1150 TempInst.setOpcode(Inst.getOpcode());
1151 TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
1152 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1154 TempInst.addOperand(MCOperand::CreateImm(LoOffset));
1156 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1157 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
1158 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
1160 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1162 const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
1163 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1166 Instructions.push_back(TempInst);
1170 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1171 // As described by the Mips32r2 spec, the registers Rd and Rs for
1172 // jalr.hb must be different.
1173 unsigned Opcode = Inst.getOpcode();
1175 if (Opcode == Mips::JALR_HB &&
1176 (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()))
1177 return Match_RequiresDifferentSrcAndDst;
1179 return Match_Success;
1182 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1183 OperandVector &Operands,
1185 unsigned &ErrorInfo,
1186 bool MatchingInlineAsm) {
1189 SmallVector<MCInst, 8> Instructions;
1190 unsigned MatchResult =
1191 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
1193 switch (MatchResult) {
1196 case Match_Success: {
1197 if (processInstruction(Inst, IDLoc, Instructions))
1199 for (unsigned i = 0; i < Instructions.size(); i++)
1200 Out.EmitInstruction(Instructions[i], STI);
1203 case Match_MissingFeature:
1204 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1206 case Match_InvalidOperand: {
1207 SMLoc ErrorLoc = IDLoc;
1208 if (ErrorInfo != ~0U) {
1209 if (ErrorInfo >= Operands.size())
1210 return Error(IDLoc, "too few operands for instruction");
1212 ErrorLoc = ((MipsOperand &)*Operands[ErrorInfo]).getStartLoc();
1213 if (ErrorLoc == SMLoc())
1217 return Error(ErrorLoc, "invalid operand for instruction");
1219 case Match_MnemonicFail:
1220 return Error(IDLoc, "invalid instruction");
1221 case Match_RequiresDifferentSrcAndDst:
1222 return Error(IDLoc, "source and destination must be different");
1227 void MipsAsmParser::WarnIfAssemblerTemporary(int RegIndex, SMLoc Loc) {
1228 if ((RegIndex != 0) && ((int)Options.getATRegNum() == RegIndex)) {
1230 Warning(Loc, "Used $at without \".set noat\"");
1232 Warning(Loc, Twine("Used $") + Twine(RegIndex) + " with \".set at=$" +
1233 Twine(RegIndex) + "\"");
1237 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
1240 CC = StringSwitch<unsigned>(Name)
1276 if (isN32() || isN64()) {
1277 // Although SGI documentation just cuts out t0-t3 for n32/n64,
1278 // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
1279 // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
1280 if (8 <= CC && CC <= 11)
1284 CC = StringSwitch<unsigned>(Name)
1297 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
1299 if (Name[0] == 'f') {
1300 StringRef NumString = Name.substr(1);
1302 if (NumString.getAsInteger(10, IntVal))
1303 return -1; // This is not an integer.
1304 if (IntVal > 31) // Maximum index for fpu register.
1311 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1313 if (Name.startswith("fcc")) {
1314 StringRef NumString = Name.substr(3);
1316 if (NumString.getAsInteger(10, IntVal))
1317 return -1; // This is not an integer.
1318 if (IntVal > 7) // There are only 8 fcc registers.
1325 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1327 if (Name.startswith("ac")) {
1328 StringRef NumString = Name.substr(2);
1330 if (NumString.getAsInteger(10, IntVal))
1331 return -1; // This is not an integer.
1332 if (IntVal > 3) // There are only 3 acc registers.
1339 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1342 if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1351 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1354 CC = StringSwitch<unsigned>(Name)
1357 .Case("msaaccess", 2)
1359 .Case("msamodify", 4)
1360 .Case("msarequest", 5)
1362 .Case("msaunmap", 7)
1368 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1376 int MipsAsmParser::getATReg() {
1377 int AT = Options.getATRegNum();
1379 TokError("Pseudo instruction requires $at, which is not available");
1383 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1384 return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1387 unsigned MipsAsmParser::getGPR(int RegNo) {
1388 return getReg(isGP64() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1392 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1394 getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1397 return getReg(RegClass, RegNum);
1400 bool MipsAsmParser::ParseOperand(OperandVector &Operands, StringRef Mnemonic) {
1401 DEBUG(dbgs() << "ParseOperand\n");
1403 // Check if the current operand has a custom associated parser, if so, try to
1404 // custom parse the operand, or fallback to the general approach.
1405 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1406 if (ResTy == MatchOperand_Success)
1408 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1409 // there was a match, but an error occurred, in which case, just return that
1410 // the operand parsing failed.
1411 if (ResTy == MatchOperand_ParseFail)
1414 DEBUG(dbgs() << ".. Generic Parser\n");
1416 switch (getLexer().getKind()) {
1418 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1420 case AsmToken::Dollar: {
1421 // Parse the register.
1422 SMLoc S = Parser.getTok().getLoc();
1424 // Almost all registers have been parsed by custom parsers. There is only
1425 // one exception to this. $zero (and it's alias $0) will reach this point
1426 // for div, divu, and similar instructions because it is not an operand
1427 // to the instruction definition but an explicit register. Special case
1428 // this situation for now.
1429 if (ParseAnyRegister(Operands) != MatchOperand_NoMatch)
1432 // Maybe it is a symbol reference.
1433 StringRef Identifier;
1434 if (Parser.parseIdentifier(Identifier))
1437 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1438 MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1439 // Otherwise create a symbol reference.
1441 MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1443 Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
1446 // Else drop to expression parsing.
1447 case AsmToken::LParen:
1448 case AsmToken::Minus:
1449 case AsmToken::Plus:
1450 case AsmToken::Integer:
1451 case AsmToken::String: {
1452 DEBUG(dbgs() << ".. generic integer\n");
1453 OperandMatchResultTy ResTy = ParseImm(Operands);
1454 return ResTy != MatchOperand_Success;
1456 case AsmToken::Percent: {
1457 // It is a symbol reference or constant expression.
1458 const MCExpr *IdVal;
1459 SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1460 if (parseRelocOperand(IdVal))
1463 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1465 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1467 } // case AsmToken::Percent
1468 } // switch(getLexer().getKind())
1472 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1473 StringRef RelocStr) {
1475 // Check the type of the expression.
1476 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1477 // It's a constant, evaluate reloc value.
1479 switch (getVariantKind(RelocStr)) {
1480 case MCSymbolRefExpr::VK_Mips_ABS_LO:
1481 // Get the 1st 16-bits.
1482 Val = MCE->getValue() & 0xffff;
1484 case MCSymbolRefExpr::VK_Mips_ABS_HI:
1485 // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
1486 // 16 bits being negative.
1487 Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
1489 case MCSymbolRefExpr::VK_Mips_HIGHER:
1490 // Get the 3rd 16-bits.
1491 Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
1493 case MCSymbolRefExpr::VK_Mips_HIGHEST:
1494 // Get the 4th 16-bits.
1495 Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
1498 report_fatal_error("Unsupported reloc value!");
1500 return MCConstantExpr::Create(Val, getContext());
1503 if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1504 // It's a symbol, create a symbolic expression from the symbol.
1505 StringRef Symbol = MSRE->getSymbol().getName();
1506 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1507 Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1511 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1512 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1514 // Try to create target expression.
1515 if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
1516 return MipsMCExpr::Create(VK, Expr, getContext());
1518 const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1519 const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1520 Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1524 if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1525 const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1526 Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1529 // Just return the original expression.
1533 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1535 switch (Expr->getKind()) {
1536 case MCExpr::Constant:
1538 case MCExpr::SymbolRef:
1539 return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1540 case MCExpr::Binary:
1541 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1542 if (!isEvaluated(BE->getLHS()))
1544 return isEvaluated(BE->getRHS());
1547 return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1548 case MCExpr::Target:
1554 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1555 Parser.Lex(); // Eat the % token.
1556 const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1557 if (Tok.isNot(AsmToken::Identifier))
1560 std::string Str = Tok.getIdentifier().str();
1562 Parser.Lex(); // Eat the identifier.
1563 // Now make an expression from the rest of the operand.
1564 const MCExpr *IdVal;
1567 if (getLexer().getKind() == AsmToken::LParen) {
1569 Parser.Lex(); // Eat the '(' token.
1570 if (getLexer().getKind() == AsmToken::Percent) {
1571 Parser.Lex(); // Eat the % token.
1572 const AsmToken &nextTok = Parser.getTok();
1573 if (nextTok.isNot(AsmToken::Identifier))
1576 Str += nextTok.getIdentifier();
1577 Parser.Lex(); // Eat the identifier.
1578 if (getLexer().getKind() != AsmToken::LParen)
1583 if (getParser().parseParenExpression(IdVal, EndLoc))
1586 while (getLexer().getKind() == AsmToken::RParen)
1587 Parser.Lex(); // Eat the ')' token.
1590 return true; // Parenthesis must follow the relocation operand.
1592 Res = evaluateRelocExpr(IdVal, Str);
1596 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1598 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
1599 OperandMatchResultTy ResTy = ParseAnyRegister(Operands);
1600 if (ResTy == MatchOperand_Success) {
1601 assert(Operands.size() == 1);
1602 MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
1603 StartLoc = Operand.getStartLoc();
1604 EndLoc = Operand.getEndLoc();
1606 // AFAIK, we only support numeric registers and named GPR's in CFI
1608 // Don't worry about eating tokens before failing. Using an unrecognised
1609 // register is a parse error.
1610 if (Operand.isGPRAsmReg()) {
1611 // Resolve to GPR32 or GPR64 appropriately.
1612 RegNo = isGP64() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
1615 return (RegNo == (unsigned)-1);
1618 assert(Operands.size() == 0);
1619 return (RegNo == (unsigned)-1);
1622 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1626 while (getLexer().getKind() == AsmToken::LParen)
1629 switch (getLexer().getKind()) {
1632 case AsmToken::Identifier:
1633 case AsmToken::LParen:
1634 case AsmToken::Integer:
1635 case AsmToken::Minus:
1636 case AsmToken::Plus:
1638 Result = getParser().parseParenExpression(Res, S);
1640 Result = (getParser().parseExpression(Res));
1641 while (getLexer().getKind() == AsmToken::RParen)
1644 case AsmToken::Percent:
1645 Result = parseRelocOperand(Res);
1650 MipsAsmParser::OperandMatchResultTy
1651 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
1652 DEBUG(dbgs() << "parseMemOperand\n");
1653 const MCExpr *IdVal = nullptr;
1655 bool isParenExpr = false;
1656 MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1657 // First operand is the offset.
1658 S = Parser.getTok().getLoc();
1660 if (getLexer().getKind() == AsmToken::LParen) {
1665 if (getLexer().getKind() != AsmToken::Dollar) {
1666 if (parseMemOffset(IdVal, isParenExpr))
1667 return MatchOperand_ParseFail;
1669 const AsmToken &Tok = Parser.getTok(); // Get the next token.
1670 if (Tok.isNot(AsmToken::LParen)) {
1671 MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
1672 if (Mnemonic.getToken() == "la") {
1674 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1675 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1676 return MatchOperand_Success;
1678 if (Tok.is(AsmToken::EndOfStatement)) {
1680 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1682 // Zero register assumed, add a memory operand with ZERO as its base.
1683 // "Base" will be managed by k_Memory.
1684 auto Base = MipsOperand::CreateGPRReg(0, getContext().getRegisterInfo(),
1687 MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
1688 return MatchOperand_Success;
1690 Error(Parser.getTok().getLoc(), "'(' expected");
1691 return MatchOperand_ParseFail;
1694 Parser.Lex(); // Eat the '(' token.
1697 Res = ParseAnyRegister(Operands);
1698 if (Res != MatchOperand_Success)
1701 if (Parser.getTok().isNot(AsmToken::RParen)) {
1702 Error(Parser.getTok().getLoc(), "')' expected");
1703 return MatchOperand_ParseFail;
1706 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1708 Parser.Lex(); // Eat the ')' token.
1711 IdVal = MCConstantExpr::Create(0, getContext());
1713 // Replace the register operand with the memory operand.
1714 std::unique_ptr<MipsOperand> op(
1715 static_cast<MipsOperand *>(Operands.back().release()));
1716 // Remove the register from the operands.
1717 // "op" will be managed by k_Memory.
1718 Operands.pop_back();
1719 // Add the memory operand.
1720 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1722 if (IdVal->EvaluateAsAbsolute(Imm))
1723 IdVal = MCConstantExpr::Create(Imm, getContext());
1724 else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1725 IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1729 Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
1730 return MatchOperand_Success;
1733 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
1735 MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
1737 SMLoc S = Parser.getTok().getLoc();
1739 if (Sym->isVariable())
1740 Expr = Sym->getVariableValue();
1743 if (Expr->getKind() == MCExpr::SymbolRef) {
1744 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
1745 const StringRef DefSymbol = Ref->getSymbol().getName();
1746 if (DefSymbol.startswith("$")) {
1747 OperandMatchResultTy ResTy =
1748 MatchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
1749 if (ResTy == MatchOperand_Success) {
1752 } else if (ResTy == MatchOperand_ParseFail)
1753 llvm_unreachable("Should never ParseFail");
1756 } else if (Expr->getKind() == MCExpr::Constant) {
1758 const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
1760 MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
1767 MipsAsmParser::OperandMatchResultTy
1768 MipsAsmParser::MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
1769 StringRef Identifier,
1771 int Index = matchCPURegisterName(Identifier);
1773 Operands.push_back(MipsOperand::CreateGPRReg(
1774 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1775 return MatchOperand_Success;
1778 Index = matchFPURegisterName(Identifier);
1780 Operands.push_back(MipsOperand::CreateFGRReg(
1781 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1782 return MatchOperand_Success;
1785 Index = matchFCCRegisterName(Identifier);
1787 Operands.push_back(MipsOperand::CreateFCCReg(
1788 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1789 return MatchOperand_Success;
1792 Index = matchACRegisterName(Identifier);
1794 Operands.push_back(MipsOperand::CreateACCReg(
1795 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1796 return MatchOperand_Success;
1799 Index = matchMSA128RegisterName(Identifier);
1801 Operands.push_back(MipsOperand::CreateMSA128Reg(
1802 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1803 return MatchOperand_Success;
1806 Index = matchMSA128CtrlRegisterName(Identifier);
1808 Operands.push_back(MipsOperand::CreateMSACtrlReg(
1809 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1810 return MatchOperand_Success;
1813 return MatchOperand_NoMatch;
1816 MipsAsmParser::OperandMatchResultTy
1817 MipsAsmParser::MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
1818 auto Token = Parser.getLexer().peekTok(false);
1820 if (Token.is(AsmToken::Identifier)) {
1821 DEBUG(dbgs() << ".. identifier\n");
1822 StringRef Identifier = Token.getIdentifier();
1823 OperandMatchResultTy ResTy =
1824 MatchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
1826 } else if (Token.is(AsmToken::Integer)) {
1827 DEBUG(dbgs() << ".. integer\n");
1828 Operands.push_back(MipsOperand::CreateNumericReg(
1829 Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
1831 return MatchOperand_Success;
1834 DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
1836 return MatchOperand_NoMatch;
1839 MipsAsmParser::OperandMatchResultTy
1840 MipsAsmParser::ParseAnyRegister(OperandVector &Operands) {
1841 DEBUG(dbgs() << "ParseAnyRegister\n");
1843 auto Token = Parser.getTok();
1845 SMLoc S = Token.getLoc();
1847 if (Token.isNot(AsmToken::Dollar)) {
1848 DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
1849 if (Token.is(AsmToken::Identifier)) {
1850 if (searchSymbolAlias(Operands))
1851 return MatchOperand_Success;
1853 DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
1854 return MatchOperand_NoMatch;
1856 DEBUG(dbgs() << ".. $\n");
1858 OperandMatchResultTy ResTy = MatchAnyRegisterWithoutDollar(Operands, S);
1859 if (ResTy == MatchOperand_Success) {
1861 Parser.Lex(); // identifier
1866 MipsAsmParser::OperandMatchResultTy
1867 MipsAsmParser::ParseImm(OperandVector &Operands) {
1868 switch (getLexer().getKind()) {
1870 return MatchOperand_NoMatch;
1871 case AsmToken::LParen:
1872 case AsmToken::Minus:
1873 case AsmToken::Plus:
1874 case AsmToken::Integer:
1875 case AsmToken::String:
1879 const MCExpr *IdVal;
1880 SMLoc S = Parser.getTok().getLoc();
1881 if (getParser().parseExpression(IdVal))
1882 return MatchOperand_ParseFail;
1884 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1885 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1886 return MatchOperand_Success;
1889 MipsAsmParser::OperandMatchResultTy
1890 MipsAsmParser::ParseJumpTarget(OperandVector &Operands) {
1891 DEBUG(dbgs() << "ParseJumpTarget\n");
1893 SMLoc S = getLexer().getLoc();
1895 // Integers and expressions are acceptable
1896 OperandMatchResultTy ResTy = ParseImm(Operands);
1897 if (ResTy != MatchOperand_NoMatch)
1900 // Registers are a valid target and have priority over symbols.
1901 ResTy = ParseAnyRegister(Operands);
1902 if (ResTy != MatchOperand_NoMatch)
1905 const MCExpr *Expr = nullptr;
1906 if (Parser.parseExpression(Expr)) {
1907 // We have no way of knowing if a symbol was consumed so we must ParseFail
1908 return MatchOperand_ParseFail;
1911 MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
1912 return MatchOperand_Success;
1915 MipsAsmParser::OperandMatchResultTy
1916 MipsAsmParser::parseInvNum(OperandVector &Operands) {
1917 const MCExpr *IdVal;
1918 // If the first token is '$' we may have register operand.
1919 if (Parser.getTok().is(AsmToken::Dollar))
1920 return MatchOperand_NoMatch;
1921 SMLoc S = Parser.getTok().getLoc();
1922 if (getParser().parseExpression(IdVal))
1923 return MatchOperand_ParseFail;
1924 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
1925 assert(MCE && "Unexpected MCExpr type.");
1926 int64_t Val = MCE->getValue();
1927 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1928 Operands.push_back(MipsOperand::CreateImm(
1929 MCConstantExpr::Create(0 - Val, getContext()), S, E, *this));
1930 return MatchOperand_Success;
1933 MipsAsmParser::OperandMatchResultTy
1934 MipsAsmParser::ParseLSAImm(OperandVector &Operands) {
1935 switch (getLexer().getKind()) {
1937 return MatchOperand_NoMatch;
1938 case AsmToken::LParen:
1939 case AsmToken::Plus:
1940 case AsmToken::Minus:
1941 case AsmToken::Integer:
1946 SMLoc S = Parser.getTok().getLoc();
1948 if (getParser().parseExpression(Expr))
1949 return MatchOperand_ParseFail;
1952 if (!Expr->EvaluateAsAbsolute(Val)) {
1953 Error(S, "expected immediate value");
1954 return MatchOperand_ParseFail;
1957 // The LSA instruction allows a 2-bit unsigned immediate. For this reason
1958 // and because the CPU always adds one to the immediate field, the allowed
1959 // range becomes 1..4. We'll only check the range here and will deal
1960 // with the addition/subtraction when actually decoding/encoding
1962 if (Val < 1 || Val > 4) {
1963 Error(S, "immediate not in range (1..4)");
1964 return MatchOperand_ParseFail;
1968 MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
1969 return MatchOperand_Success;
1972 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
1974 MCSymbolRefExpr::VariantKind VK =
1975 StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
1976 .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
1977 .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
1978 .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
1979 .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
1980 .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
1981 .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
1982 .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
1983 .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
1984 .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
1985 .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
1986 .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
1987 .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
1988 .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
1989 .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
1990 .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
1991 .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
1992 .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
1993 .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
1994 .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
1995 .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
1996 .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
1997 .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
1998 .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
1999 .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
2000 .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
2001 .Default(MCSymbolRefExpr::VK_None);
2003 assert(VK != MCSymbolRefExpr::VK_None);
2008 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
2010 /// ::= '(', register, ')'
2011 /// handle it before we iterate so we don't get tripped up by the lack of
2013 bool MipsAsmParser::ParseParenSuffix(StringRef Name, OperandVector &Operands) {
2014 if (getLexer().is(AsmToken::LParen)) {
2016 MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
2018 if (ParseOperand(Operands, Name)) {
2019 SMLoc Loc = getLexer().getLoc();
2020 Parser.eatToEndOfStatement();
2021 return Error(Loc, "unexpected token in argument list");
2023 if (Parser.getTok().isNot(AsmToken::RParen)) {
2024 SMLoc Loc = getLexer().getLoc();
2025 Parser.eatToEndOfStatement();
2026 return Error(Loc, "unexpected token, expected ')'");
2029 MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
2035 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
2036 /// either one of these.
2037 /// ::= '[', register, ']'
2038 /// ::= '[', integer, ']'
2039 /// handle it before we iterate so we don't get tripped up by the lack of
2041 bool MipsAsmParser::ParseBracketSuffix(StringRef Name,
2042 OperandVector &Operands) {
2043 if (getLexer().is(AsmToken::LBrac)) {
2045 MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
2047 if (ParseOperand(Operands, Name)) {
2048 SMLoc Loc = getLexer().getLoc();
2049 Parser.eatToEndOfStatement();
2050 return Error(Loc, "unexpected token in argument list");
2052 if (Parser.getTok().isNot(AsmToken::RBrac)) {
2053 SMLoc Loc = getLexer().getLoc();
2054 Parser.eatToEndOfStatement();
2055 return Error(Loc, "unexpected token, expected ']'");
2058 MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
2064 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2065 SMLoc NameLoc, OperandVector &Operands) {
2066 DEBUG(dbgs() << "ParseInstruction\n");
2067 // Check if we have valid mnemonic
2068 if (!mnemonicIsValid(Name, 0)) {
2069 Parser.eatToEndOfStatement();
2070 return Error(NameLoc, "Unknown instruction");
2072 // First operand in MCInst is instruction mnemonic.
2073 Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
2075 // Read the remaining operands.
2076 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2077 // Read the first operand.
2078 if (ParseOperand(Operands, Name)) {
2079 SMLoc Loc = getLexer().getLoc();
2080 Parser.eatToEndOfStatement();
2081 return Error(Loc, "unexpected token in argument list");
2083 if (getLexer().is(AsmToken::LBrac) && ParseBracketSuffix(Name, Operands))
2085 // AFAIK, parenthesis suffixes are never on the first operand
2087 while (getLexer().is(AsmToken::Comma)) {
2088 Parser.Lex(); // Eat the comma.
2089 // Parse and remember the operand.
2090 if (ParseOperand(Operands, Name)) {
2091 SMLoc Loc = getLexer().getLoc();
2092 Parser.eatToEndOfStatement();
2093 return Error(Loc, "unexpected token in argument list");
2095 // Parse bracket and parenthesis suffixes before we iterate
2096 if (getLexer().is(AsmToken::LBrac)) {
2097 if (ParseBracketSuffix(Name, Operands))
2099 } else if (getLexer().is(AsmToken::LParen) &&
2100 ParseParenSuffix(Name, Operands))
2104 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2105 SMLoc Loc = getLexer().getLoc();
2106 Parser.eatToEndOfStatement();
2107 return Error(Loc, "unexpected token in argument list");
2109 Parser.Lex(); // Consume the EndOfStatement.
2113 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2114 SMLoc Loc = getLexer().getLoc();
2115 Parser.eatToEndOfStatement();
2116 return Error(Loc, ErrorMsg);
2119 bool MipsAsmParser::reportParseError(SMLoc Loc, StringRef ErrorMsg) {
2120 return Error(Loc, ErrorMsg);
2123 bool MipsAsmParser::parseSetNoAtDirective() {
2124 // Line should look like: ".set noat".
2126 Options.setATReg(0);
2129 // If this is not the end of the statement, report an error.
2130 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2131 reportParseError("unexpected token in statement");
2134 Parser.Lex(); // Consume the EndOfStatement.
2138 bool MipsAsmParser::parseSetAtDirective() {
2139 // Line can be .set at - defaults to $1
2143 if (getLexer().is(AsmToken::EndOfStatement)) {
2144 Options.setATReg(1);
2145 Parser.Lex(); // Consume the EndOfStatement.
2147 } else if (getLexer().is(AsmToken::Equal)) {
2148 getParser().Lex(); // Eat the '='.
2149 if (getLexer().isNot(AsmToken::Dollar)) {
2150 reportParseError("unexpected token in statement");
2153 Parser.Lex(); // Eat the '$'.
2154 const AsmToken &Reg = Parser.getTok();
2155 if (Reg.is(AsmToken::Identifier)) {
2156 AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2157 } else if (Reg.is(AsmToken::Integer)) {
2158 AtRegNo = Reg.getIntVal();
2160 reportParseError("unexpected token in statement");
2164 if (AtRegNo < 0 || AtRegNo > 31) {
2165 reportParseError("unexpected token in statement");
2169 if (!Options.setATReg(AtRegNo)) {
2170 reportParseError("unexpected token in statement");
2173 getParser().Lex(); // Eat the register.
2175 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2176 reportParseError("unexpected token in statement");
2179 Parser.Lex(); // Consume the EndOfStatement.
2182 reportParseError("unexpected token in statement");
2187 bool MipsAsmParser::parseSetReorderDirective() {
2189 // If this is not the end of the statement, report an error.
2190 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2191 reportParseError("unexpected token in statement");
2194 Options.setReorder();
2195 getTargetStreamer().emitDirectiveSetReorder();
2196 Parser.Lex(); // Consume the EndOfStatement.
2200 bool MipsAsmParser::parseSetNoReorderDirective() {
2202 // If this is not the end of the statement, report an error.
2203 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2204 reportParseError("unexpected token in statement");
2207 Options.setNoreorder();
2208 getTargetStreamer().emitDirectiveSetNoReorder();
2209 Parser.Lex(); // Consume the EndOfStatement.
2213 bool MipsAsmParser::parseSetMacroDirective() {
2215 // If this is not the end of the statement, report an error.
2216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2217 reportParseError("unexpected token in statement");
2221 Parser.Lex(); // Consume the EndOfStatement.
2225 bool MipsAsmParser::parseSetNoMacroDirective() {
2227 // If this is not the end of the statement, report an error.
2228 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2229 reportParseError("`noreorder' must be set before `nomacro'");
2232 if (Options.isReorder()) {
2233 reportParseError("`noreorder' must be set before `nomacro'");
2236 Options.setNomacro();
2237 Parser.Lex(); // Consume the EndOfStatement.
2241 bool MipsAsmParser::parseSetNoMips16Directive() {
2243 // If this is not the end of the statement, report an error.
2244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2245 reportParseError("unexpected token in statement");
2248 // For now do nothing.
2249 Parser.Lex(); // Consume the EndOfStatement.
2253 bool MipsAsmParser::parseSetAssignment() {
2255 const MCExpr *Value;
2257 if (Parser.parseIdentifier(Name))
2258 reportParseError("expected identifier after .set");
2260 if (getLexer().isNot(AsmToken::Comma))
2261 return reportParseError("unexpected token in .set directive");
2264 if (Parser.parseExpression(Value))
2265 return reportParseError("expected valid expression after comma");
2267 // Check if the Name already exists as a symbol.
2268 MCSymbol *Sym = getContext().LookupSymbol(Name);
2270 return reportParseError("symbol already defined");
2271 Sym = getContext().GetOrCreateSymbol(Name);
2272 Sym->setVariableValue(Value);
2277 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2279 if (getLexer().isNot(AsmToken::EndOfStatement))
2280 return reportParseError("unexpected token in .set directive");
2284 llvm_unreachable("Unimplemented feature");
2285 case Mips::FeatureDSP:
2286 setFeatureBits(Mips::FeatureDSP, "dsp");
2287 getTargetStreamer().emitDirectiveSetDsp();
2289 case Mips::FeatureMicroMips:
2290 getTargetStreamer().emitDirectiveSetMicroMips();
2292 case Mips::FeatureMips16:
2293 getTargetStreamer().emitDirectiveSetMips16();
2295 case Mips::FeatureMips32r2:
2296 setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2297 getTargetStreamer().emitDirectiveSetMips32R2();
2299 case Mips::FeatureMips64:
2300 setFeatureBits(Mips::FeatureMips64, "mips64");
2301 getTargetStreamer().emitDirectiveSetMips64();
2303 case Mips::FeatureMips64r2:
2304 setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2305 getTargetStreamer().emitDirectiveSetMips64R2();
2311 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2312 if (!getLexer().is(AsmToken::Dollar))
2317 const AsmToken &Reg = Parser.getTok();
2318 if (Reg.is(AsmToken::Identifier)) {
2319 RegNum = matchCPURegisterName(Reg.getIdentifier());
2320 } else if (Reg.is(AsmToken::Integer)) {
2321 RegNum = Reg.getIntVal();
2330 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2331 if (getLexer().isNot(AsmToken::Comma)) {
2332 SMLoc Loc = getLexer().getLoc();
2333 Parser.eatToEndOfStatement();
2334 return Error(Loc, ErrorStr);
2337 Parser.Lex(); // Eat the comma.
2341 bool MipsAsmParser::parseDirectiveCPLoad(SMLoc Loc) {
2342 if (Options.isReorder())
2343 Warning(Loc, ".cpload in reorder section");
2345 // FIXME: Warn if cpload is used in Mips16 mode.
2347 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
2348 OperandMatchResultTy ResTy = ParseAnyRegister(Reg);
2349 if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
2350 reportParseError("expected register containing function address");
2354 MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
2355 if (!RegOpnd.isGPRAsmReg()) {
2356 reportParseError(RegOpnd.getStartLoc(), "invalid register");
2360 getTargetStreamer().emitDirectiveCpload(RegOpnd.getGPR32Reg());
2364 bool MipsAsmParser::parseDirectiveCPSetup() {
2367 bool SaveIsReg = true;
2369 if (!parseRegister(FuncReg))
2370 return reportParseError("expected register containing function address");
2371 FuncReg = getGPR(FuncReg);
2373 if (!eatComma("expected comma parsing directive"))
2376 if (!parseRegister(Save)) {
2377 const AsmToken &Tok = Parser.getTok();
2378 if (Tok.is(AsmToken::Integer)) {
2379 Save = Tok.getIntVal();
2383 return reportParseError("expected save register or stack offset");
2385 Save = getGPR(Save);
2387 if (!eatComma("expected comma parsing directive"))
2391 if (Parser.parseIdentifier(Name))
2392 reportParseError("expected identifier");
2393 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2395 getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, *Sym, SaveIsReg);
2399 bool MipsAsmParser::parseDirectiveNaN() {
2400 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2401 const AsmToken &Tok = Parser.getTok();
2403 if (Tok.getString() == "2008") {
2405 getTargetStreamer().emitDirectiveNaN2008();
2407 } else if (Tok.getString() == "legacy") {
2409 getTargetStreamer().emitDirectiveNaNLegacy();
2413 // If we don't recognize the option passed to the .nan
2414 // directive (e.g. no option or unknown option), emit an error.
2415 reportParseError("invalid option in .nan directive");
2419 bool MipsAsmParser::parseDirectiveSet() {
2421 // Get the next token.
2422 const AsmToken &Tok = Parser.getTok();
2424 if (Tok.getString() == "noat") {
2425 return parseSetNoAtDirective();
2426 } else if (Tok.getString() == "at") {
2427 return parseSetAtDirective();
2428 } else if (Tok.getString() == "reorder") {
2429 return parseSetReorderDirective();
2430 } else if (Tok.getString() == "noreorder") {
2431 return parseSetNoReorderDirective();
2432 } else if (Tok.getString() == "macro") {
2433 return parseSetMacroDirective();
2434 } else if (Tok.getString() == "nomacro") {
2435 return parseSetNoMacroDirective();
2436 } else if (Tok.getString() == "mips16") {
2437 return parseSetFeature(Mips::FeatureMips16);
2438 } else if (Tok.getString() == "nomips16") {
2439 return parseSetNoMips16Directive();
2440 } else if (Tok.getString() == "nomicromips") {
2441 getTargetStreamer().emitDirectiveSetNoMicroMips();
2442 Parser.eatToEndOfStatement();
2444 } else if (Tok.getString() == "micromips") {
2445 return parseSetFeature(Mips::FeatureMicroMips);
2446 } else if (Tok.getString() == "mips32r2") {
2447 return parseSetFeature(Mips::FeatureMips32r2);
2448 } else if (Tok.getString() == "mips64") {
2449 return parseSetFeature(Mips::FeatureMips64);
2450 } else if (Tok.getString() == "mips64r2") {
2451 return parseSetFeature(Mips::FeatureMips64r2);
2452 } else if (Tok.getString() == "dsp") {
2453 return parseSetFeature(Mips::FeatureDSP);
2455 // It is just an identifier, look for an assignment.
2456 parseSetAssignment();
2463 /// parseDataDirective
2464 /// ::= .word [ expression (, expression)* ]
2465 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2466 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2468 const MCExpr *Value;
2469 if (getParser().parseExpression(Value))
2472 getParser().getStreamer().EmitValue(Value, Size);
2474 if (getLexer().is(AsmToken::EndOfStatement))
2477 // FIXME: Improve diagnostic.
2478 if (getLexer().isNot(AsmToken::Comma))
2479 return Error(L, "unexpected token in directive");
2488 /// parseDirectiveGpWord
2489 /// ::= .gpword local_sym
2490 bool MipsAsmParser::parseDirectiveGpWord() {
2491 const MCExpr *Value;
2492 // EmitGPRel32Value requires an expression, so we are using base class
2493 // method to evaluate the expression.
2494 if (getParser().parseExpression(Value))
2496 getParser().getStreamer().EmitGPRel32Value(Value);
2498 if (getLexer().isNot(AsmToken::EndOfStatement))
2499 return Error(getLexer().getLoc(), "unexpected token in directive");
2500 Parser.Lex(); // Eat EndOfStatement token.
2504 /// parseDirectiveGpDWord
2505 /// ::= .gpdword local_sym
2506 bool MipsAsmParser::parseDirectiveGpDWord() {
2507 const MCExpr *Value;
2508 // EmitGPRel64Value requires an expression, so we are using base class
2509 // method to evaluate the expression.
2510 if (getParser().parseExpression(Value))
2512 getParser().getStreamer().EmitGPRel64Value(Value);
2514 if (getLexer().isNot(AsmToken::EndOfStatement))
2515 return Error(getLexer().getLoc(), "unexpected token in directive");
2516 Parser.Lex(); // Eat EndOfStatement token.
2520 bool MipsAsmParser::parseDirectiveOption() {
2521 // Get the option token.
2522 AsmToken Tok = Parser.getTok();
2523 // At the moment only identifiers are supported.
2524 if (Tok.isNot(AsmToken::Identifier)) {
2525 Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2526 Parser.eatToEndOfStatement();
2530 StringRef Option = Tok.getIdentifier();
2532 if (Option == "pic0") {
2533 getTargetStreamer().emitDirectiveOptionPic0();
2535 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2536 Error(Parser.getTok().getLoc(),
2537 "unexpected token in .option pic0 directive");
2538 Parser.eatToEndOfStatement();
2543 if (Option == "pic2") {
2544 getTargetStreamer().emitDirectiveOptionPic2();
2546 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2547 Error(Parser.getTok().getLoc(),
2548 "unexpected token in .option pic2 directive");
2549 Parser.eatToEndOfStatement();
2555 Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2556 Parser.eatToEndOfStatement();
2560 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2561 StringRef IDVal = DirectiveID.getString();
2563 if (IDVal == ".cpload")
2564 return parseDirectiveCPLoad(DirectiveID.getLoc());
2565 if (IDVal == ".dword") {
2566 parseDataDirective(8, DirectiveID.getLoc());
2570 if (IDVal == ".ent") {
2571 // Ignore this directive for now.
2576 if (IDVal == ".end") {
2577 // Ignore this directive for now.
2582 if (IDVal == ".frame") {
2583 // Ignore this directive for now.
2584 Parser.eatToEndOfStatement();
2588 if (IDVal == ".set") {
2589 return parseDirectiveSet();
2592 if (IDVal == ".fmask") {
2593 // Ignore this directive for now.
2594 Parser.eatToEndOfStatement();
2598 if (IDVal == ".mask") {
2599 // Ignore this directive for now.
2600 Parser.eatToEndOfStatement();
2604 if (IDVal == ".nan")
2605 return parseDirectiveNaN();
2607 if (IDVal == ".gpword") {
2608 parseDirectiveGpWord();
2612 if (IDVal == ".gpdword") {
2613 parseDirectiveGpDWord();
2617 if (IDVal == ".word") {
2618 parseDataDirective(4, DirectiveID.getLoc());
2622 if (IDVal == ".option")
2623 return parseDirectiveOption();
2625 if (IDVal == ".abicalls") {
2626 getTargetStreamer().emitDirectiveAbiCalls();
2627 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2628 Error(Parser.getTok().getLoc(), "unexpected token in directive");
2630 Parser.eatToEndOfStatement();
2635 if (IDVal == ".cpsetup")
2636 return parseDirectiveCPSetup();
2641 extern "C" void LLVMInitializeMipsAsmParser() {
2642 RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2643 RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2644 RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2645 RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2648 #define GET_REGISTER_MATCHER
2649 #define GET_MATCHER_IMPLEMENTATION
2650 #include "MipsGenAsmMatcher.inc"