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 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
76 OperandVector &Operands, MCStreamer &Out,
78 bool MatchingInlineAsm) override;
80 /// Parse a register as used in CFI directives
81 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
83 bool ParseParenSuffix(StringRef Name, OperandVector &Operands);
85 bool ParseBracketSuffix(StringRef Name, OperandVector &Operands);
87 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
88 SMLoc NameLoc, OperandVector &Operands) override;
90 bool ParseDirective(AsmToken DirectiveID) override;
92 MipsAsmParser::OperandMatchResultTy parseMemOperand(OperandVector &Operands);
94 MipsAsmParser::OperandMatchResultTy
95 MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
96 StringRef Identifier, SMLoc S);
98 MipsAsmParser::OperandMatchResultTy
99 MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S);
101 MipsAsmParser::OperandMatchResultTy ParseAnyRegister(OperandVector &Operands);
103 MipsAsmParser::OperandMatchResultTy ParseImm(OperandVector &Operands);
105 MipsAsmParser::OperandMatchResultTy ParseJumpTarget(OperandVector &Operands);
107 MipsAsmParser::OperandMatchResultTy parseInvNum(OperandVector &Operands);
109 MipsAsmParser::OperandMatchResultTy ParseLSAImm(OperandVector &Operands);
111 bool searchSymbolAlias(OperandVector &Operands);
113 bool ParseOperand(OperandVector &, StringRef Mnemonic);
115 bool needsExpansion(MCInst &Inst);
117 void expandInstruction(MCInst &Inst, SMLoc IDLoc,
118 SmallVectorImpl<MCInst> &Instructions);
119 void expandLoadImm(MCInst &Inst, SMLoc IDLoc,
120 SmallVectorImpl<MCInst> &Instructions);
121 void expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
122 SmallVectorImpl<MCInst> &Instructions);
123 void expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
124 SmallVectorImpl<MCInst> &Instructions);
125 void expandMemInst(MCInst &Inst, SMLoc IDLoc,
126 SmallVectorImpl<MCInst> &Instructions, bool isLoad,
128 bool reportParseError(StringRef ErrorMsg);
129 bool reportParseError(SMLoc Loc, StringRef ErrorMsg);
131 bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
132 bool parseRelocOperand(const MCExpr *&Res);
134 const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
136 bool isEvaluated(const MCExpr *Expr);
137 bool parseSetFeature(uint64_t Feature);
138 bool parseDirectiveCPLoad(SMLoc Loc);
139 bool parseDirectiveCPSetup();
140 bool parseDirectiveNaN();
141 bool parseDirectiveSet();
142 bool parseDirectiveOption();
144 bool parseSetAtDirective();
145 bool parseSetNoAtDirective();
146 bool parseSetMacroDirective();
147 bool parseSetNoMacroDirective();
148 bool parseSetReorderDirective();
149 bool parseSetNoReorderDirective();
150 bool parseSetNoMips16Directive();
152 bool parseSetAssignment();
154 bool parseDataDirective(unsigned Size, SMLoc L);
155 bool parseDirectiveGpWord();
156 bool parseDirectiveGpDWord();
158 MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
160 bool isGP64() const {
161 return (STI.getFeatureBits() & Mips::FeatureGP64Bit) != 0;
164 bool isFP64() const {
165 return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
168 bool isN32() const { return STI.getFeatureBits() & Mips::FeatureN32; }
169 bool isN64() const { return STI.getFeatureBits() & Mips::FeatureN64; }
171 bool isMicroMips() const {
172 return STI.getFeatureBits() & Mips::FeatureMicroMips;
175 bool parseRegister(unsigned &RegNum);
177 bool eatComma(StringRef ErrorStr);
179 int matchCPURegisterName(StringRef Symbol);
181 int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
183 int matchFPURegisterName(StringRef Name);
185 int matchFCCRegisterName(StringRef Name);
187 int matchACRegisterName(StringRef Name);
189 int matchMSA128RegisterName(StringRef Name);
191 int matchMSA128CtrlRegisterName(StringRef Name);
193 unsigned getReg(int RC, int RegNo);
195 unsigned getGPR(int RegNo);
199 bool processInstruction(MCInst &Inst, SMLoc IDLoc,
200 SmallVectorImpl<MCInst> &Instructions);
202 // Helper function that checks if the value of a vector index is within the
203 // boundaries of accepted values for each RegisterKind
204 // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
205 bool validateMSAIndex(int Val, int RegKind);
207 void setFeatureBits(unsigned Feature, StringRef FeatureString) {
208 if (!(STI.getFeatureBits() & Feature)) {
209 setAvailableFeatures(
210 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
214 void clearFeatureBits(unsigned Feature, StringRef FeatureString) {
215 if (STI.getFeatureBits() & Feature) {
216 setAvailableFeatures(
217 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
222 MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
223 const MCInstrInfo &MII,
224 const MCTargetOptions &Options)
225 : MCTargetAsmParser(), STI(sti), Parser(parser) {
226 // Initialize the set of available features.
227 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
229 // Assert exactly one ABI was chosen.
230 assert((((STI.getFeatureBits() & Mips::FeatureO32) != 0) +
231 ((STI.getFeatureBits() & Mips::FeatureEABI) != 0) +
232 ((STI.getFeatureBits() & Mips::FeatureN32) != 0) +
233 ((STI.getFeatureBits() & Mips::FeatureN64) != 0)) == 1);
236 MCAsmParser &getParser() const { return Parser; }
237 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
239 /// Warn if RegNo is the current assembler temporary.
240 void WarnIfAssemblerTemporary(int RegNo, SMLoc Loc);
246 /// MipsOperand - Instances of this class represent a parsed Mips machine
248 class MipsOperand : public MCParsedAsmOperand {
250 /// Broad categories of register classes
251 /// The exact class is finalized by the render method.
253 RegKind_GPR = 1, /// GPR32 and GPR64 (depending on isGP64())
254 RegKind_FGR = 2, /// FGR32, FGR64, AFGR64 (depending on context and
256 RegKind_FCC = 4, /// FCC
257 RegKind_MSA128 = 8, /// MSA128[BHWD] (makes no difference which)
258 RegKind_MSACtrl = 16, /// MSA control registers
259 RegKind_COP2 = 32, /// COP2
260 RegKind_ACC = 64, /// HI32DSP, LO32DSP, and ACC64DSP (depending on
262 RegKind_CCR = 128, /// CCR
263 RegKind_HWRegs = 256, /// HWRegs
264 RegKind_COP3 = 512, /// COP3
266 /// Potentially any (e.g. $1)
267 RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
268 RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
269 RegKind_CCR | RegKind_HWRegs | RegKind_COP3
274 k_Immediate, /// An immediate (possibly involving symbol references)
275 k_Memory, /// Base + Offset Memory Address
276 k_PhysRegister, /// A physical register from the Mips namespace
277 k_RegisterIndex, /// A register index in one or more RegKind.
278 k_Token /// A simple token
282 MipsOperand(KindTy K, MipsAsmParser &Parser)
283 : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
286 /// For diagnostics, and checking the assembler temporary
287 MipsAsmParser &AsmParser;
295 unsigned Num; /// Register Number
299 unsigned Index; /// Index into the register class
300 RegKind Kind; /// Bitfield of the kinds it could possibly be
301 const MCRegisterInfo *RegInfo;
315 struct PhysRegOp PhysReg;
316 struct RegIdxOp RegIdx;
321 SMLoc StartLoc, EndLoc;
323 /// Internal constructor for register kinds
324 static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
325 const MCRegisterInfo *RegInfo,
327 MipsAsmParser &Parser) {
328 auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
329 Op->RegIdx.Index = Index;
330 Op->RegIdx.RegInfo = RegInfo;
331 Op->RegIdx.Kind = RegKind;
338 /// Coerce the register to GPR32 and return the real register for the current
340 unsigned getGPR32Reg() const {
341 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
342 AsmParser.WarnIfAssemblerTemporary(RegIdx.Index, StartLoc);
343 unsigned ClassID = Mips::GPR32RegClassID;
344 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
347 /// Coerce the register to GPR64 and return the real register for the current
349 unsigned getGPR64Reg() const {
350 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
351 unsigned ClassID = Mips::GPR64RegClassID;
352 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
356 /// Coerce the register to AFGR64 and return the real register for the current
358 unsigned getAFGR64Reg() const {
359 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
360 if (RegIdx.Index % 2 != 0)
361 AsmParser.Warning(StartLoc, "Float register should be even.");
362 return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
363 .getRegister(RegIdx.Index / 2);
366 /// Coerce the register to FGR64 and return the real register for the current
368 unsigned getFGR64Reg() const {
369 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
370 return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
371 .getRegister(RegIdx.Index);
374 /// Coerce the register to FGR32 and return the real register for the current
376 unsigned getFGR32Reg() const {
377 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
378 return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
379 .getRegister(RegIdx.Index);
382 /// Coerce the register to FGRH32 and return the real register for the current
384 unsigned getFGRH32Reg() const {
385 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
386 return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
387 .getRegister(RegIdx.Index);
390 /// Coerce the register to FCC and return the real register for the current
392 unsigned getFCCReg() const {
393 assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
394 return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
395 .getRegister(RegIdx.Index);
398 /// Coerce the register to MSA128 and return the real register for the current
400 unsigned getMSA128Reg() const {
401 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
402 // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
404 unsigned ClassID = Mips::MSA128BRegClassID;
405 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
408 /// Coerce the register to MSACtrl and return the real register for the
410 unsigned getMSACtrlReg() const {
411 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
412 unsigned ClassID = Mips::MSACtrlRegClassID;
413 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
416 /// Coerce the register to COP2 and return the real register for the
418 unsigned getCOP2Reg() const {
419 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
420 unsigned ClassID = Mips::COP2RegClassID;
421 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
424 /// Coerce the register to COP3 and return the real register for the
426 unsigned getCOP3Reg() const {
427 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
428 unsigned ClassID = Mips::COP3RegClassID;
429 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
432 /// Coerce the register to ACC64DSP and return the real register for the
434 unsigned getACC64DSPReg() const {
435 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
436 unsigned ClassID = Mips::ACC64DSPRegClassID;
437 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
440 /// Coerce the register to HI32DSP and return the real register for the
442 unsigned getHI32DSPReg() const {
443 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
444 unsigned ClassID = Mips::HI32DSPRegClassID;
445 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
448 /// Coerce the register to LO32DSP and return the real register for the
450 unsigned getLO32DSPReg() const {
451 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
452 unsigned ClassID = Mips::LO32DSPRegClassID;
453 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
456 /// Coerce the register to CCR and return the real register for the
458 unsigned getCCRReg() const {
459 assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
460 unsigned ClassID = Mips::CCRRegClassID;
461 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
464 /// Coerce the register to HWRegs and return the real register for the
466 unsigned getHWRegsReg() const {
467 assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
468 unsigned ClassID = Mips::HWRegsRegClassID;
469 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
473 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
474 // Add as immediate when possible. Null MCExpr = 0.
476 Inst.addOperand(MCOperand::CreateImm(0));
477 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
478 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
480 Inst.addOperand(MCOperand::CreateExpr(Expr));
483 void addRegOperands(MCInst &Inst, unsigned N) const {
484 llvm_unreachable("Use a custom parser instead");
487 /// Render the operand to an MCInst as a GPR32
488 /// Asserts if the wrong number of operands are requested, or the operand
489 /// is not a k_RegisterIndex compatible with RegKind_GPR
490 void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
491 assert(N == 1 && "Invalid number of operands!");
492 Inst.addOperand(MCOperand::CreateReg(getGPR32Reg()));
495 /// Render the operand to an MCInst as a GPR64
496 /// Asserts if the wrong number of operands are requested, or the operand
497 /// is not a k_RegisterIndex compatible with RegKind_GPR
498 void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
499 assert(N == 1 && "Invalid number of operands!");
500 Inst.addOperand(MCOperand::CreateReg(getGPR64Reg()));
503 void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
504 assert(N == 1 && "Invalid number of operands!");
505 Inst.addOperand(MCOperand::CreateReg(getAFGR64Reg()));
508 void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
509 assert(N == 1 && "Invalid number of operands!");
510 Inst.addOperand(MCOperand::CreateReg(getFGR64Reg()));
513 void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
514 assert(N == 1 && "Invalid number of operands!");
515 Inst.addOperand(MCOperand::CreateReg(getFGR32Reg()));
518 void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
519 assert(N == 1 && "Invalid number of operands!");
520 Inst.addOperand(MCOperand::CreateReg(getFGRH32Reg()));
523 void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
524 assert(N == 1 && "Invalid number of operands!");
525 Inst.addOperand(MCOperand::CreateReg(getFCCReg()));
528 void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
529 assert(N == 1 && "Invalid number of operands!");
530 Inst.addOperand(MCOperand::CreateReg(getMSA128Reg()));
533 void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
534 assert(N == 1 && "Invalid number of operands!");
535 Inst.addOperand(MCOperand::CreateReg(getMSACtrlReg()));
538 void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
539 assert(N == 1 && "Invalid number of operands!");
540 Inst.addOperand(MCOperand::CreateReg(getCOP2Reg()));
543 void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
544 assert(N == 1 && "Invalid number of operands!");
545 Inst.addOperand(MCOperand::CreateReg(getCOP3Reg()));
548 void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
549 assert(N == 1 && "Invalid number of operands!");
550 Inst.addOperand(MCOperand::CreateReg(getACC64DSPReg()));
553 void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
554 assert(N == 1 && "Invalid number of operands!");
555 Inst.addOperand(MCOperand::CreateReg(getHI32DSPReg()));
558 void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
559 assert(N == 1 && "Invalid number of operands!");
560 Inst.addOperand(MCOperand::CreateReg(getLO32DSPReg()));
563 void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
564 assert(N == 1 && "Invalid number of operands!");
565 Inst.addOperand(MCOperand::CreateReg(getCCRReg()));
568 void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
569 assert(N == 1 && "Invalid number of operands!");
570 Inst.addOperand(MCOperand::CreateReg(getHWRegsReg()));
573 void addImmOperands(MCInst &Inst, unsigned N) const {
574 assert(N == 1 && "Invalid number of operands!");
575 const MCExpr *Expr = getImm();
579 void addMemOperands(MCInst &Inst, unsigned N) const {
580 assert(N == 2 && "Invalid number of operands!");
582 Inst.addOperand(MCOperand::CreateReg(getMemBase()->getGPR32Reg()));
584 const MCExpr *Expr = getMemOff();
588 bool isReg() const override {
589 // As a special case until we sort out the definition of div/divu, pretend
590 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
591 if (isGPRAsmReg() && RegIdx.Index == 0)
594 return Kind == k_PhysRegister;
596 bool isRegIdx() const { return Kind == k_RegisterIndex; }
597 bool isImm() const override { return Kind == k_Immediate; }
598 bool isConstantImm() const {
599 return isImm() && dyn_cast<MCConstantExpr>(getImm());
601 bool isToken() const override {
602 // Note: It's not possible to pretend that other operand kinds are tokens.
603 // The matcher emitter checks tokens first.
604 return Kind == k_Token;
606 bool isMem() const override { return Kind == k_Memory; }
607 bool isInvNum() const { return Kind == k_Immediate; }
608 bool isLSAImm() const {
609 if (!isConstantImm())
611 int64_t Val = getConstantImm();
612 return 1 <= Val && Val <= 4;
615 StringRef getToken() const {
616 assert(Kind == k_Token && "Invalid access!");
617 return StringRef(Tok.Data, Tok.Length);
620 unsigned getReg() const override {
621 // As a special case until we sort out the definition of div/divu, pretend
622 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
623 if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
624 RegIdx.Kind & RegKind_GPR)
625 return getGPR32Reg(); // FIXME: GPR64 too
627 assert(Kind == k_PhysRegister && "Invalid access!");
631 const MCExpr *getImm() const {
632 assert((Kind == k_Immediate) && "Invalid access!");
636 int64_t getConstantImm() const {
637 const MCExpr *Val = getImm();
638 return static_cast<const MCConstantExpr *>(Val)->getValue();
641 MipsOperand *getMemBase() const {
642 assert((Kind == k_Memory) && "Invalid access!");
646 const MCExpr *getMemOff() const {
647 assert((Kind == k_Memory) && "Invalid access!");
651 static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
652 MipsAsmParser &Parser) {
653 auto Op = make_unique<MipsOperand>(k_Token, Parser);
654 Op->Tok.Data = Str.data();
655 Op->Tok.Length = Str.size();
661 /// Create a numeric register (e.g. $1). The exact register remains
662 /// unresolved until an instruction successfully matches
663 static std::unique_ptr<MipsOperand>
664 CreateNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
665 SMLoc E, MipsAsmParser &Parser) {
666 DEBUG(dbgs() << "CreateNumericReg(" << Index << ", ...)\n");
667 return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
670 /// Create a register that is definitely a GPR.
671 /// This is typically only used for named registers such as $gp.
672 static std::unique_ptr<MipsOperand>
673 CreateGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
674 MipsAsmParser &Parser) {
675 return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
678 /// Create a register that is definitely a FGR.
679 /// This is typically only used for named registers such as $f0.
680 static std::unique_ptr<MipsOperand>
681 CreateFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
682 MipsAsmParser &Parser) {
683 return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
686 /// Create a register that is definitely an FCC.
687 /// This is typically only used for named registers such as $fcc0.
688 static std::unique_ptr<MipsOperand>
689 CreateFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
690 MipsAsmParser &Parser) {
691 return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
694 /// Create a register that is definitely an ACC.
695 /// This is typically only used for named registers such as $ac0.
696 static std::unique_ptr<MipsOperand>
697 CreateACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
698 MipsAsmParser &Parser) {
699 return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
702 /// Create a register that is definitely an MSA128.
703 /// This is typically only used for named registers such as $w0.
704 static std::unique_ptr<MipsOperand>
705 CreateMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
706 SMLoc E, MipsAsmParser &Parser) {
707 return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
710 /// Create a register that is definitely an MSACtrl.
711 /// This is typically only used for named registers such as $msaaccess.
712 static std::unique_ptr<MipsOperand>
713 CreateMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
714 SMLoc E, MipsAsmParser &Parser) {
715 return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
718 static std::unique_ptr<MipsOperand>
719 CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
720 auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
727 static std::unique_ptr<MipsOperand>
728 CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
729 SMLoc E, MipsAsmParser &Parser) {
730 auto Op = make_unique<MipsOperand>(k_Memory, Parser);
731 Op->Mem.Base = Base.release();
738 bool isGPRAsmReg() const {
739 return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
741 bool isFGRAsmReg() const {
742 // AFGR64 is $0-$15 but we handle this in getAFGR64()
743 return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
745 bool isHWRegsAsmReg() const {
746 return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
748 bool isCCRAsmReg() const {
749 return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
751 bool isFCCAsmReg() const {
752 return isRegIdx() && RegIdx.Kind & RegKind_FCC && RegIdx.Index <= 7;
754 bool isACCAsmReg() const {
755 return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
757 bool isCOP2AsmReg() const {
758 return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
760 bool isCOP3AsmReg() const {
761 return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
763 bool isMSA128AsmReg() const {
764 return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
766 bool isMSACtrlAsmReg() const {
767 return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
770 /// getStartLoc - Get the location of the first token of this operand.
771 SMLoc getStartLoc() const override { return StartLoc; }
772 /// getEndLoc - Get the location of the last token of this operand.
773 SMLoc getEndLoc() const override { return EndLoc; }
775 virtual ~MipsOperand() {
783 case k_RegisterIndex:
789 void print(raw_ostream &OS) const override {
804 OS << "PhysReg<" << PhysReg.Num << ">";
806 case k_RegisterIndex:
807 OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
814 }; // class MipsOperand
818 extern const MCInstrDesc MipsInsts[];
820 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
821 return MipsInsts[Opcode];
824 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
825 SmallVectorImpl<MCInst> &Instructions) {
826 const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
830 if (MCID.isBranch() || MCID.isCall()) {
831 const unsigned Opcode = Inst.getOpcode();
841 assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
842 Offset = Inst.getOperand(2);
844 break; // We'll deal with this situation later on when applying fixups.
845 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
846 return Error(IDLoc, "branch target out of range");
847 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
848 return Error(IDLoc, "branch to misaligned address");
862 case Mips::BGEZAL_MM:
863 case Mips::BLTZAL_MM:
866 assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
867 Offset = Inst.getOperand(1);
869 break; // We'll deal with this situation later on when applying fixups.
870 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
871 return Error(IDLoc, "branch target out of range");
872 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
873 return Error(IDLoc, "branch to misaligned address");
878 if (MCID.hasDelaySlot() && Options.isReorder()) {
879 // If this instruction has a delay slot and .set reorder is active,
880 // emit a NOP after it.
881 Instructions.push_back(Inst);
883 NopInst.setOpcode(Mips::SLL);
884 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
885 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
886 NopInst.addOperand(MCOperand::CreateImm(0));
887 Instructions.push_back(NopInst);
891 if (MCID.mayLoad() || MCID.mayStore()) {
892 // Check the offset of memory operand, if it is a symbol
893 // reference or immediate we may have to expand instructions.
894 for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
895 const MCOperandInfo &OpInfo = MCID.OpInfo[i];
896 if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
897 (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
898 MCOperand &Op = Inst.getOperand(i);
900 int MemOffset = Op.getImm();
901 if (MemOffset < -32768 || MemOffset > 32767) {
902 // Offset can't exceed 16bit value.
903 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
906 } else if (Op.isExpr()) {
907 const MCExpr *Expr = Op.getExpr();
908 if (Expr->getKind() == MCExpr::SymbolRef) {
909 const MCSymbolRefExpr *SR =
910 static_cast<const MCSymbolRefExpr *>(Expr);
911 if (SR->getKind() == MCSymbolRefExpr::VK_None) {
913 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
916 } else if (!isEvaluated(Expr)) {
917 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
925 if (needsExpansion(Inst))
926 expandInstruction(Inst, IDLoc, Instructions);
928 Instructions.push_back(Inst);
933 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
935 switch (Inst.getOpcode()) {
936 case Mips::LoadImm32Reg:
937 case Mips::LoadAddr32Imm:
938 case Mips::LoadAddr32Reg:
945 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
946 SmallVectorImpl<MCInst> &Instructions) {
947 switch (Inst.getOpcode()) {
948 case Mips::LoadImm32Reg:
949 return expandLoadImm(Inst, IDLoc, Instructions);
950 case Mips::LoadAddr32Imm:
951 return expandLoadAddressImm(Inst, IDLoc, Instructions);
952 case Mips::LoadAddr32Reg:
953 return expandLoadAddressReg(Inst, IDLoc, Instructions);
957 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
958 SmallVectorImpl<MCInst> &Instructions) {
960 const MCOperand &ImmOp = Inst.getOperand(1);
961 assert(ImmOp.isImm() && "expected immediate operand kind");
962 const MCOperand &RegOp = Inst.getOperand(0);
963 assert(RegOp.isReg() && "expected register operand kind");
965 int ImmValue = ImmOp.getImm();
966 tmpInst.setLoc(IDLoc);
967 if (0 <= ImmValue && ImmValue <= 65535) {
968 // For 0 <= j <= 65535.
969 // li d,j => ori d,$zero,j
970 tmpInst.setOpcode(Mips::ORi);
971 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
972 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
973 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
974 Instructions.push_back(tmpInst);
975 } else if (ImmValue < 0 && ImmValue >= -32768) {
976 // For -32768 <= j < 0.
977 // li d,j => addiu d,$zero,j
978 tmpInst.setOpcode(Mips::ADDiu);
979 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
980 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
981 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
982 Instructions.push_back(tmpInst);
984 // For any other value of j that is representable as a 32-bit integer.
985 // li d,j => lui d,hi16(j)
987 tmpInst.setOpcode(Mips::LUi);
988 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
989 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
990 Instructions.push_back(tmpInst);
992 tmpInst.setOpcode(Mips::ORi);
993 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
994 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
995 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
996 tmpInst.setLoc(IDLoc);
997 Instructions.push_back(tmpInst);
1002 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
1003 SmallVectorImpl<MCInst> &Instructions) {
1005 const MCOperand &ImmOp = Inst.getOperand(2);
1006 assert(ImmOp.isImm() && "expected immediate operand kind");
1007 const MCOperand &SrcRegOp = Inst.getOperand(1);
1008 assert(SrcRegOp.isReg() && "expected register operand kind");
1009 const MCOperand &DstRegOp = Inst.getOperand(0);
1010 assert(DstRegOp.isReg() && "expected register operand kind");
1011 int ImmValue = ImmOp.getImm();
1012 if (-32768 <= ImmValue && ImmValue <= 65535) {
1013 // For -32768 <= j <= 65535.
1014 // la d,j(s) => addiu d,s,j
1015 tmpInst.setOpcode(Mips::ADDiu);
1016 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1017 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1018 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1019 Instructions.push_back(tmpInst);
1021 // For any other value of j that is representable as a 32-bit integer.
1022 // la d,j(s) => lui d,hi16(j)
1025 tmpInst.setOpcode(Mips::LUi);
1026 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1027 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1028 Instructions.push_back(tmpInst);
1030 tmpInst.setOpcode(Mips::ORi);
1031 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1032 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1033 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1034 Instructions.push_back(tmpInst);
1036 tmpInst.setOpcode(Mips::ADDu);
1037 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1038 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1039 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1040 Instructions.push_back(tmpInst);
1045 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
1046 SmallVectorImpl<MCInst> &Instructions) {
1048 const MCOperand &ImmOp = Inst.getOperand(1);
1049 assert(ImmOp.isImm() && "expected immediate operand kind");
1050 const MCOperand &RegOp = Inst.getOperand(0);
1051 assert(RegOp.isReg() && "expected register operand kind");
1052 int ImmValue = ImmOp.getImm();
1053 if (-32768 <= ImmValue && ImmValue <= 65535) {
1054 // For -32768 <= j <= 65535.
1055 // la d,j => addiu d,$zero,j
1056 tmpInst.setOpcode(Mips::ADDiu);
1057 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1058 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1059 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1060 Instructions.push_back(tmpInst);
1062 // For any other value of j that is representable as a 32-bit integer.
1063 // la d,j => lui d,hi16(j)
1065 tmpInst.setOpcode(Mips::LUi);
1066 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1067 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1068 Instructions.push_back(tmpInst);
1070 tmpInst.setOpcode(Mips::ORi);
1071 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1072 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1073 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1074 Instructions.push_back(tmpInst);
1078 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
1079 SmallVectorImpl<MCInst> &Instructions,
1080 bool isLoad, bool isImmOpnd) {
1081 const MCSymbolRefExpr *SR;
1083 unsigned ImmOffset, HiOffset, LoOffset;
1084 const MCExpr *ExprOffset;
1086 unsigned AtRegNum = getReg(
1087 (isGP64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
1088 // 1st operand is either the source or destination register.
1089 assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1090 unsigned RegOpNum = Inst.getOperand(0).getReg();
1091 // 2nd operand is the base register.
1092 assert(Inst.getOperand(1).isReg() && "expected register operand kind");
1093 unsigned BaseRegNum = Inst.getOperand(1).getReg();
1094 // 3rd operand is either an immediate or expression.
1096 assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
1097 ImmOffset = Inst.getOperand(2).getImm();
1098 LoOffset = ImmOffset & 0x0000ffff;
1099 HiOffset = (ImmOffset & 0xffff0000) >> 16;
1100 // If msb of LoOffset is 1(negative number) we must increment HiOffset.
1101 if (LoOffset & 0x8000)
1104 ExprOffset = Inst.getOperand(2).getExpr();
1105 // All instructions will have the same location.
1106 TempInst.setLoc(IDLoc);
1107 // 1st instruction in expansion is LUi. For load instruction we can use
1108 // the dst register as a temporary if base and dst are different,
1109 // but for stores we must use $at.
1110 TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
1111 TempInst.setOpcode(Mips::LUi);
1112 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1114 TempInst.addOperand(MCOperand::CreateImm(HiOffset));
1116 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1117 SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
1118 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
1119 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
1121 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1123 const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
1124 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1127 // Add the instruction to the list.
1128 Instructions.push_back(TempInst);
1129 // Prepare TempInst for next instruction.
1131 // Add temp register to base.
1132 TempInst.setOpcode(Mips::ADDu);
1133 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1134 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1135 TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
1136 Instructions.push_back(TempInst);
1138 // And finally, create original instruction with low part
1139 // of offset and new base.
1140 TempInst.setOpcode(Inst.getOpcode());
1141 TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
1142 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1144 TempInst.addOperand(MCOperand::CreateImm(LoOffset));
1146 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1147 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
1148 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
1150 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1152 const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
1153 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1156 Instructions.push_back(TempInst);
1160 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1161 OperandVector &Operands,
1163 unsigned &ErrorInfo,
1164 bool MatchingInlineAsm) {
1166 SmallVector<MCInst, 8> Instructions;
1167 unsigned MatchResult =
1168 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
1170 switch (MatchResult) {
1173 case Match_Success: {
1174 if (processInstruction(Inst, IDLoc, Instructions))
1176 for (unsigned i = 0; i < Instructions.size(); i++)
1177 Out.EmitInstruction(Instructions[i], STI);
1180 case Match_MissingFeature:
1181 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1183 case Match_InvalidOperand: {
1184 SMLoc ErrorLoc = IDLoc;
1185 if (ErrorInfo != ~0U) {
1186 if (ErrorInfo >= Operands.size())
1187 return Error(IDLoc, "too few operands for instruction");
1189 ErrorLoc = ((MipsOperand &)*Operands[ErrorInfo]).getStartLoc();
1190 if (ErrorLoc == SMLoc())
1194 return Error(ErrorLoc, "invalid operand for instruction");
1196 case Match_MnemonicFail:
1197 return Error(IDLoc, "invalid instruction");
1202 void MipsAsmParser::WarnIfAssemblerTemporary(int RegIndex, SMLoc Loc) {
1203 if ((RegIndex != 0) && ((int)Options.getATRegNum() == RegIndex)) {
1205 Warning(Loc, "Used $at without \".set noat\"");
1207 Warning(Loc, Twine("Used $") + Twine(RegIndex) + " with \".set at=$" +
1208 Twine(RegIndex) + "\"");
1212 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
1215 CC = StringSwitch<unsigned>(Name)
1251 if (isN32() || isN64()) {
1252 // Although SGI documentation just cuts out t0-t3 for n32/n64,
1253 // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
1254 // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
1255 if (8 <= CC && CC <= 11)
1259 CC = StringSwitch<unsigned>(Name)
1272 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
1274 if (Name[0] == 'f') {
1275 StringRef NumString = Name.substr(1);
1277 if (NumString.getAsInteger(10, IntVal))
1278 return -1; // This is not an integer.
1279 if (IntVal > 31) // Maximum index for fpu register.
1286 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1288 if (Name.startswith("fcc")) {
1289 StringRef NumString = Name.substr(3);
1291 if (NumString.getAsInteger(10, IntVal))
1292 return -1; // This is not an integer.
1293 if (IntVal > 7) // There are only 8 fcc registers.
1300 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1302 if (Name.startswith("ac")) {
1303 StringRef NumString = Name.substr(2);
1305 if (NumString.getAsInteger(10, IntVal))
1306 return -1; // This is not an integer.
1307 if (IntVal > 3) // There are only 3 acc registers.
1314 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1317 if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1326 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1329 CC = StringSwitch<unsigned>(Name)
1332 .Case("msaaccess", 2)
1334 .Case("msamodify", 4)
1335 .Case("msarequest", 5)
1337 .Case("msaunmap", 7)
1343 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1351 int MipsAsmParser::getATReg() {
1352 int AT = Options.getATRegNum();
1354 TokError("Pseudo instruction requires $at, which is not available");
1358 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1359 return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1362 unsigned MipsAsmParser::getGPR(int RegNo) {
1363 return getReg(isGP64() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1367 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1369 getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1372 return getReg(RegClass, RegNum);
1375 bool MipsAsmParser::ParseOperand(OperandVector &Operands, StringRef Mnemonic) {
1376 DEBUG(dbgs() << "ParseOperand\n");
1378 // Check if the current operand has a custom associated parser, if so, try to
1379 // custom parse the operand, or fallback to the general approach.
1380 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1381 if (ResTy == MatchOperand_Success)
1383 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1384 // there was a match, but an error occurred, in which case, just return that
1385 // the operand parsing failed.
1386 if (ResTy == MatchOperand_ParseFail)
1389 DEBUG(dbgs() << ".. Generic Parser\n");
1391 switch (getLexer().getKind()) {
1393 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1395 case AsmToken::Dollar: {
1396 // Parse the register.
1397 SMLoc S = Parser.getTok().getLoc();
1399 // Almost all registers have been parsed by custom parsers. There is only
1400 // one exception to this. $zero (and it's alias $0) will reach this point
1401 // for div, divu, and similar instructions because it is not an operand
1402 // to the instruction definition but an explicit register. Special case
1403 // this situation for now.
1404 if (ParseAnyRegister(Operands) != MatchOperand_NoMatch)
1407 // Maybe it is a symbol reference.
1408 StringRef Identifier;
1409 if (Parser.parseIdentifier(Identifier))
1412 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1413 MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1414 // Otherwise create a symbol reference.
1416 MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1418 Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
1421 // Else drop to expression parsing.
1422 case AsmToken::LParen:
1423 case AsmToken::Minus:
1424 case AsmToken::Plus:
1425 case AsmToken::Integer:
1426 case AsmToken::String: {
1427 DEBUG(dbgs() << ".. generic integer\n");
1428 OperandMatchResultTy ResTy = ParseImm(Operands);
1429 return ResTy != MatchOperand_Success;
1431 case AsmToken::Percent: {
1432 // It is a symbol reference or constant expression.
1433 const MCExpr *IdVal;
1434 SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1435 if (parseRelocOperand(IdVal))
1438 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1440 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1442 } // case AsmToken::Percent
1443 } // switch(getLexer().getKind())
1447 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1448 StringRef RelocStr) {
1450 // Check the type of the expression.
1451 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1452 // It's a constant, evaluate reloc value.
1454 switch (getVariantKind(RelocStr)) {
1455 case MCSymbolRefExpr::VK_Mips_ABS_LO:
1456 // Get the 1st 16-bits.
1457 Val = MCE->getValue() & 0xffff;
1459 case MCSymbolRefExpr::VK_Mips_ABS_HI:
1460 // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
1461 // 16 bits being negative.
1462 Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
1464 case MCSymbolRefExpr::VK_Mips_HIGHER:
1465 // Get the 3rd 16-bits.
1466 Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
1468 case MCSymbolRefExpr::VK_Mips_HIGHEST:
1469 // Get the 4th 16-bits.
1470 Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
1473 report_fatal_error("Unsupported reloc value!");
1475 return MCConstantExpr::Create(Val, getContext());
1478 if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1479 // It's a symbol, create a symbolic expression from the symbol.
1480 StringRef Symbol = MSRE->getSymbol().getName();
1481 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1482 Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1486 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1487 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1489 // Try to create target expression.
1490 if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
1491 return MipsMCExpr::Create(VK, Expr, getContext());
1493 const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1494 const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1495 Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1499 if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1500 const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1501 Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1504 // Just return the original expression.
1508 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1510 switch (Expr->getKind()) {
1511 case MCExpr::Constant:
1513 case MCExpr::SymbolRef:
1514 return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1515 case MCExpr::Binary:
1516 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1517 if (!isEvaluated(BE->getLHS()))
1519 return isEvaluated(BE->getRHS());
1522 return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1523 case MCExpr::Target:
1529 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1530 Parser.Lex(); // Eat the % token.
1531 const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1532 if (Tok.isNot(AsmToken::Identifier))
1535 std::string Str = Tok.getIdentifier().str();
1537 Parser.Lex(); // Eat the identifier.
1538 // Now make an expression from the rest of the operand.
1539 const MCExpr *IdVal;
1542 if (getLexer().getKind() == AsmToken::LParen) {
1544 Parser.Lex(); // Eat the '(' token.
1545 if (getLexer().getKind() == AsmToken::Percent) {
1546 Parser.Lex(); // Eat the % token.
1547 const AsmToken &nextTok = Parser.getTok();
1548 if (nextTok.isNot(AsmToken::Identifier))
1551 Str += nextTok.getIdentifier();
1552 Parser.Lex(); // Eat the identifier.
1553 if (getLexer().getKind() != AsmToken::LParen)
1558 if (getParser().parseParenExpression(IdVal, EndLoc))
1561 while (getLexer().getKind() == AsmToken::RParen)
1562 Parser.Lex(); // Eat the ')' token.
1565 return true; // Parenthesis must follow the relocation operand.
1567 Res = evaluateRelocExpr(IdVal, Str);
1571 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1573 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
1574 OperandMatchResultTy ResTy = ParseAnyRegister(Operands);
1575 if (ResTy == MatchOperand_Success) {
1576 assert(Operands.size() == 1);
1577 MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
1578 StartLoc = Operand.getStartLoc();
1579 EndLoc = Operand.getEndLoc();
1581 // AFAIK, we only support numeric registers and named GPR's in CFI
1583 // Don't worry about eating tokens before failing. Using an unrecognised
1584 // register is a parse error.
1585 if (Operand.isGPRAsmReg()) {
1586 // Resolve to GPR32 or GPR64 appropriately.
1587 RegNo = isGP64() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
1590 return (RegNo == (unsigned)-1);
1593 assert(Operands.size() == 0);
1594 return (RegNo == (unsigned)-1);
1597 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1601 while (getLexer().getKind() == AsmToken::LParen)
1604 switch (getLexer().getKind()) {
1607 case AsmToken::Identifier:
1608 case AsmToken::LParen:
1609 case AsmToken::Integer:
1610 case AsmToken::Minus:
1611 case AsmToken::Plus:
1613 Result = getParser().parseParenExpression(Res, S);
1615 Result = (getParser().parseExpression(Res));
1616 while (getLexer().getKind() == AsmToken::RParen)
1619 case AsmToken::Percent:
1620 Result = parseRelocOperand(Res);
1625 MipsAsmParser::OperandMatchResultTy
1626 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
1627 DEBUG(dbgs() << "parseMemOperand\n");
1628 const MCExpr *IdVal = nullptr;
1630 bool isParenExpr = false;
1631 MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1632 // First operand is the offset.
1633 S = Parser.getTok().getLoc();
1635 if (getLexer().getKind() == AsmToken::LParen) {
1640 if (getLexer().getKind() != AsmToken::Dollar) {
1641 if (parseMemOffset(IdVal, isParenExpr))
1642 return MatchOperand_ParseFail;
1644 const AsmToken &Tok = Parser.getTok(); // Get the next token.
1645 if (Tok.isNot(AsmToken::LParen)) {
1646 MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
1647 if (Mnemonic.getToken() == "la") {
1649 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1650 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1651 return MatchOperand_Success;
1653 if (Tok.is(AsmToken::EndOfStatement)) {
1655 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1657 // Zero register assumed, add a memory operand with ZERO as its base.
1658 // "Base" will be managed by k_Memory.
1659 auto Base = MipsOperand::CreateGPRReg(0, getContext().getRegisterInfo(),
1662 MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
1663 return MatchOperand_Success;
1665 Error(Parser.getTok().getLoc(), "'(' expected");
1666 return MatchOperand_ParseFail;
1669 Parser.Lex(); // Eat the '(' token.
1672 Res = ParseAnyRegister(Operands);
1673 if (Res != MatchOperand_Success)
1676 if (Parser.getTok().isNot(AsmToken::RParen)) {
1677 Error(Parser.getTok().getLoc(), "')' expected");
1678 return MatchOperand_ParseFail;
1681 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1683 Parser.Lex(); // Eat the ')' token.
1686 IdVal = MCConstantExpr::Create(0, getContext());
1688 // Replace the register operand with the memory operand.
1689 std::unique_ptr<MipsOperand> op(
1690 static_cast<MipsOperand *>(Operands.back().release()));
1691 // Remove the register from the operands.
1692 // "op" will be managed by k_Memory.
1693 Operands.pop_back();
1694 // Add the memory operand.
1695 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1697 if (IdVal->EvaluateAsAbsolute(Imm))
1698 IdVal = MCConstantExpr::Create(Imm, getContext());
1699 else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1700 IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1704 Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
1705 return MatchOperand_Success;
1708 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
1710 MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
1712 SMLoc S = Parser.getTok().getLoc();
1714 if (Sym->isVariable())
1715 Expr = Sym->getVariableValue();
1718 if (Expr->getKind() == MCExpr::SymbolRef) {
1719 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
1720 const StringRef DefSymbol = Ref->getSymbol().getName();
1721 if (DefSymbol.startswith("$")) {
1722 OperandMatchResultTy ResTy =
1723 MatchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
1724 if (ResTy == MatchOperand_Success) {
1727 } else if (ResTy == MatchOperand_ParseFail)
1728 llvm_unreachable("Should never ParseFail");
1731 } else if (Expr->getKind() == MCExpr::Constant) {
1733 const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
1735 MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
1742 MipsAsmParser::OperandMatchResultTy
1743 MipsAsmParser::MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
1744 StringRef Identifier,
1746 int Index = matchCPURegisterName(Identifier);
1748 Operands.push_back(MipsOperand::CreateGPRReg(
1749 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1750 return MatchOperand_Success;
1753 Index = matchFPURegisterName(Identifier);
1755 Operands.push_back(MipsOperand::CreateFGRReg(
1756 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1757 return MatchOperand_Success;
1760 Index = matchFCCRegisterName(Identifier);
1762 Operands.push_back(MipsOperand::CreateFCCReg(
1763 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1764 return MatchOperand_Success;
1767 Index = matchACRegisterName(Identifier);
1769 Operands.push_back(MipsOperand::CreateACCReg(
1770 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1771 return MatchOperand_Success;
1774 Index = matchMSA128RegisterName(Identifier);
1776 Operands.push_back(MipsOperand::CreateMSA128Reg(
1777 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1778 return MatchOperand_Success;
1781 Index = matchMSA128CtrlRegisterName(Identifier);
1783 Operands.push_back(MipsOperand::CreateMSACtrlReg(
1784 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1785 return MatchOperand_Success;
1788 return MatchOperand_NoMatch;
1791 MipsAsmParser::OperandMatchResultTy
1792 MipsAsmParser::MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
1793 auto Token = Parser.getLexer().peekTok(false);
1795 if (Token.is(AsmToken::Identifier)) {
1796 DEBUG(dbgs() << ".. identifier\n");
1797 StringRef Identifier = Token.getIdentifier();
1798 OperandMatchResultTy ResTy =
1799 MatchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
1801 } else if (Token.is(AsmToken::Integer)) {
1802 DEBUG(dbgs() << ".. integer\n");
1803 Operands.push_back(MipsOperand::CreateNumericReg(
1804 Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
1806 return MatchOperand_Success;
1809 DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
1811 return MatchOperand_NoMatch;
1814 MipsAsmParser::OperandMatchResultTy
1815 MipsAsmParser::ParseAnyRegister(OperandVector &Operands) {
1816 DEBUG(dbgs() << "ParseAnyRegister\n");
1818 auto Token = Parser.getTok();
1820 SMLoc S = Token.getLoc();
1822 if (Token.isNot(AsmToken::Dollar)) {
1823 DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
1824 if (Token.is(AsmToken::Identifier)) {
1825 if (searchSymbolAlias(Operands))
1826 return MatchOperand_Success;
1828 DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
1829 return MatchOperand_NoMatch;
1831 DEBUG(dbgs() << ".. $\n");
1833 OperandMatchResultTy ResTy = MatchAnyRegisterWithoutDollar(Operands, S);
1834 if (ResTy == MatchOperand_Success) {
1836 Parser.Lex(); // identifier
1841 MipsAsmParser::OperandMatchResultTy
1842 MipsAsmParser::ParseImm(OperandVector &Operands) {
1843 switch (getLexer().getKind()) {
1845 return MatchOperand_NoMatch;
1846 case AsmToken::LParen:
1847 case AsmToken::Minus:
1848 case AsmToken::Plus:
1849 case AsmToken::Integer:
1850 case AsmToken::String:
1854 const MCExpr *IdVal;
1855 SMLoc S = Parser.getTok().getLoc();
1856 if (getParser().parseExpression(IdVal))
1857 return MatchOperand_ParseFail;
1859 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1860 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1861 return MatchOperand_Success;
1864 MipsAsmParser::OperandMatchResultTy
1865 MipsAsmParser::ParseJumpTarget(OperandVector &Operands) {
1866 DEBUG(dbgs() << "ParseJumpTarget\n");
1868 SMLoc S = getLexer().getLoc();
1870 // Integers and expressions are acceptable
1871 OperandMatchResultTy ResTy = ParseImm(Operands);
1872 if (ResTy != MatchOperand_NoMatch)
1875 // Registers are a valid target and have priority over symbols.
1876 ResTy = ParseAnyRegister(Operands);
1877 if (ResTy != MatchOperand_NoMatch)
1880 const MCExpr *Expr = nullptr;
1881 if (Parser.parseExpression(Expr)) {
1882 // We have no way of knowing if a symbol was consumed so we must ParseFail
1883 return MatchOperand_ParseFail;
1886 MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
1887 return MatchOperand_Success;
1890 MipsAsmParser::OperandMatchResultTy
1891 MipsAsmParser::parseInvNum(OperandVector &Operands) {
1892 const MCExpr *IdVal;
1893 // If the first token is '$' we may have register operand.
1894 if (Parser.getTok().is(AsmToken::Dollar))
1895 return MatchOperand_NoMatch;
1896 SMLoc S = Parser.getTok().getLoc();
1897 if (getParser().parseExpression(IdVal))
1898 return MatchOperand_ParseFail;
1899 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
1900 assert(MCE && "Unexpected MCExpr type.");
1901 int64_t Val = MCE->getValue();
1902 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1903 Operands.push_back(MipsOperand::CreateImm(
1904 MCConstantExpr::Create(0 - Val, getContext()), S, E, *this));
1905 return MatchOperand_Success;
1908 MipsAsmParser::OperandMatchResultTy
1909 MipsAsmParser::ParseLSAImm(OperandVector &Operands) {
1910 switch (getLexer().getKind()) {
1912 return MatchOperand_NoMatch;
1913 case AsmToken::LParen:
1914 case AsmToken::Plus:
1915 case AsmToken::Minus:
1916 case AsmToken::Integer:
1921 SMLoc S = Parser.getTok().getLoc();
1923 if (getParser().parseExpression(Expr))
1924 return MatchOperand_ParseFail;
1927 if (!Expr->EvaluateAsAbsolute(Val)) {
1928 Error(S, "expected immediate value");
1929 return MatchOperand_ParseFail;
1932 // The LSA instruction allows a 2-bit unsigned immediate. For this reason
1933 // and because the CPU always adds one to the immediate field, the allowed
1934 // range becomes 1..4. We'll only check the range here and will deal
1935 // with the addition/subtraction when actually decoding/encoding
1937 if (Val < 1 || Val > 4) {
1938 Error(S, "immediate not in range (1..4)");
1939 return MatchOperand_ParseFail;
1943 MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
1944 return MatchOperand_Success;
1947 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
1949 MCSymbolRefExpr::VariantKind VK =
1950 StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
1951 .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
1952 .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
1953 .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
1954 .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
1955 .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
1956 .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
1957 .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
1958 .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
1959 .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
1960 .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
1961 .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
1962 .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
1963 .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
1964 .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
1965 .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
1966 .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
1967 .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
1968 .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
1969 .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
1970 .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
1971 .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
1972 .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
1973 .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
1974 .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
1975 .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
1976 .Default(MCSymbolRefExpr::VK_None);
1978 assert(VK != MCSymbolRefExpr::VK_None);
1983 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
1985 /// ::= '(', register, ')'
1986 /// handle it before we iterate so we don't get tripped up by the lack of
1988 bool MipsAsmParser::ParseParenSuffix(StringRef Name, OperandVector &Operands) {
1989 if (getLexer().is(AsmToken::LParen)) {
1991 MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
1993 if (ParseOperand(Operands, Name)) {
1994 SMLoc Loc = getLexer().getLoc();
1995 Parser.eatToEndOfStatement();
1996 return Error(Loc, "unexpected token in argument list");
1998 if (Parser.getTok().isNot(AsmToken::RParen)) {
1999 SMLoc Loc = getLexer().getLoc();
2000 Parser.eatToEndOfStatement();
2001 return Error(Loc, "unexpected token, expected ')'");
2004 MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
2010 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
2011 /// either one of these.
2012 /// ::= '[', register, ']'
2013 /// ::= '[', integer, ']'
2014 /// handle it before we iterate so we don't get tripped up by the lack of
2016 bool MipsAsmParser::ParseBracketSuffix(StringRef Name,
2017 OperandVector &Operands) {
2018 if (getLexer().is(AsmToken::LBrac)) {
2020 MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
2022 if (ParseOperand(Operands, Name)) {
2023 SMLoc Loc = getLexer().getLoc();
2024 Parser.eatToEndOfStatement();
2025 return Error(Loc, "unexpected token in argument list");
2027 if (Parser.getTok().isNot(AsmToken::RBrac)) {
2028 SMLoc Loc = getLexer().getLoc();
2029 Parser.eatToEndOfStatement();
2030 return Error(Loc, "unexpected token, expected ']'");
2033 MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
2039 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2040 SMLoc NameLoc, OperandVector &Operands) {
2041 DEBUG(dbgs() << "ParseInstruction\n");
2042 // Check if we have valid mnemonic
2043 if (!mnemonicIsValid(Name, 0)) {
2044 Parser.eatToEndOfStatement();
2045 return Error(NameLoc, "Unknown instruction");
2047 // First operand in MCInst is instruction mnemonic.
2048 Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
2050 // Read the remaining operands.
2051 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2052 // Read the first operand.
2053 if (ParseOperand(Operands, Name)) {
2054 SMLoc Loc = getLexer().getLoc();
2055 Parser.eatToEndOfStatement();
2056 return Error(Loc, "unexpected token in argument list");
2058 if (getLexer().is(AsmToken::LBrac) && ParseBracketSuffix(Name, Operands))
2060 // AFAIK, parenthesis suffixes are never on the first operand
2062 while (getLexer().is(AsmToken::Comma)) {
2063 Parser.Lex(); // Eat the comma.
2064 // Parse and remember the operand.
2065 if (ParseOperand(Operands, Name)) {
2066 SMLoc Loc = getLexer().getLoc();
2067 Parser.eatToEndOfStatement();
2068 return Error(Loc, "unexpected token in argument list");
2070 // Parse bracket and parenthesis suffixes before we iterate
2071 if (getLexer().is(AsmToken::LBrac)) {
2072 if (ParseBracketSuffix(Name, Operands))
2074 } else if (getLexer().is(AsmToken::LParen) &&
2075 ParseParenSuffix(Name, Operands))
2079 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2080 SMLoc Loc = getLexer().getLoc();
2081 Parser.eatToEndOfStatement();
2082 return Error(Loc, "unexpected token in argument list");
2084 Parser.Lex(); // Consume the EndOfStatement.
2088 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2089 SMLoc Loc = getLexer().getLoc();
2090 Parser.eatToEndOfStatement();
2091 return Error(Loc, ErrorMsg);
2094 bool MipsAsmParser::reportParseError(SMLoc Loc, StringRef ErrorMsg) {
2095 return Error(Loc, ErrorMsg);
2098 bool MipsAsmParser::parseSetNoAtDirective() {
2099 // Line should look like: ".set noat".
2101 Options.setATReg(0);
2104 // If this is not the end of the statement, report an error.
2105 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2106 reportParseError("unexpected token in statement");
2109 Parser.Lex(); // Consume the EndOfStatement.
2113 bool MipsAsmParser::parseSetAtDirective() {
2114 // Line can be .set at - defaults to $1
2118 if (getLexer().is(AsmToken::EndOfStatement)) {
2119 Options.setATReg(1);
2120 Parser.Lex(); // Consume the EndOfStatement.
2122 } else if (getLexer().is(AsmToken::Equal)) {
2123 getParser().Lex(); // Eat the '='.
2124 if (getLexer().isNot(AsmToken::Dollar)) {
2125 reportParseError("unexpected token in statement");
2128 Parser.Lex(); // Eat the '$'.
2129 const AsmToken &Reg = Parser.getTok();
2130 if (Reg.is(AsmToken::Identifier)) {
2131 AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2132 } else if (Reg.is(AsmToken::Integer)) {
2133 AtRegNo = Reg.getIntVal();
2135 reportParseError("unexpected token in statement");
2139 if (AtRegNo < 0 || AtRegNo > 31) {
2140 reportParseError("unexpected token in statement");
2144 if (!Options.setATReg(AtRegNo)) {
2145 reportParseError("unexpected token in statement");
2148 getParser().Lex(); // Eat the register.
2150 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2151 reportParseError("unexpected token in statement");
2154 Parser.Lex(); // Consume the EndOfStatement.
2157 reportParseError("unexpected token in statement");
2162 bool MipsAsmParser::parseSetReorderDirective() {
2164 // If this is not the end of the statement, report an error.
2165 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2166 reportParseError("unexpected token in statement");
2169 Options.setReorder();
2170 getTargetStreamer().emitDirectiveSetReorder();
2171 Parser.Lex(); // Consume the EndOfStatement.
2175 bool MipsAsmParser::parseSetNoReorderDirective() {
2177 // If this is not the end of the statement, report an error.
2178 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2179 reportParseError("unexpected token in statement");
2182 Options.setNoreorder();
2183 getTargetStreamer().emitDirectiveSetNoReorder();
2184 Parser.Lex(); // Consume the EndOfStatement.
2188 bool MipsAsmParser::parseSetMacroDirective() {
2190 // If this is not the end of the statement, report an error.
2191 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2192 reportParseError("unexpected token in statement");
2196 Parser.Lex(); // Consume the EndOfStatement.
2200 bool MipsAsmParser::parseSetNoMacroDirective() {
2202 // If this is not the end of the statement, report an error.
2203 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2204 reportParseError("`noreorder' must be set before `nomacro'");
2207 if (Options.isReorder()) {
2208 reportParseError("`noreorder' must be set before `nomacro'");
2211 Options.setNomacro();
2212 Parser.Lex(); // Consume the EndOfStatement.
2216 bool MipsAsmParser::parseSetNoMips16Directive() {
2218 // If this is not the end of the statement, report an error.
2219 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2220 reportParseError("unexpected token in statement");
2223 // For now do nothing.
2224 Parser.Lex(); // Consume the EndOfStatement.
2228 bool MipsAsmParser::parseSetAssignment() {
2230 const MCExpr *Value;
2232 if (Parser.parseIdentifier(Name))
2233 reportParseError("expected identifier after .set");
2235 if (getLexer().isNot(AsmToken::Comma))
2236 return reportParseError("unexpected token in .set directive");
2239 if (Parser.parseExpression(Value))
2240 return reportParseError("expected valid expression after comma");
2242 // Check if the Name already exists as a symbol.
2243 MCSymbol *Sym = getContext().LookupSymbol(Name);
2245 return reportParseError("symbol already defined");
2246 Sym = getContext().GetOrCreateSymbol(Name);
2247 Sym->setVariableValue(Value);
2252 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2254 if (getLexer().isNot(AsmToken::EndOfStatement))
2255 return reportParseError("unexpected token in .set directive");
2259 llvm_unreachable("Unimplemented feature");
2260 case Mips::FeatureDSP:
2261 setFeatureBits(Mips::FeatureDSP, "dsp");
2262 getTargetStreamer().emitDirectiveSetDsp();
2264 case Mips::FeatureMicroMips:
2265 getTargetStreamer().emitDirectiveSetMicroMips();
2267 case Mips::FeatureMips16:
2268 getTargetStreamer().emitDirectiveSetMips16();
2270 case Mips::FeatureMips32r2:
2271 setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2272 getTargetStreamer().emitDirectiveSetMips32R2();
2274 case Mips::FeatureMips64:
2275 setFeatureBits(Mips::FeatureMips64, "mips64");
2276 getTargetStreamer().emitDirectiveSetMips64();
2278 case Mips::FeatureMips64r2:
2279 setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2280 getTargetStreamer().emitDirectiveSetMips64R2();
2286 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2287 if (!getLexer().is(AsmToken::Dollar))
2292 const AsmToken &Reg = Parser.getTok();
2293 if (Reg.is(AsmToken::Identifier)) {
2294 RegNum = matchCPURegisterName(Reg.getIdentifier());
2295 } else if (Reg.is(AsmToken::Integer)) {
2296 RegNum = Reg.getIntVal();
2305 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2306 if (getLexer().isNot(AsmToken::Comma)) {
2307 SMLoc Loc = getLexer().getLoc();
2308 Parser.eatToEndOfStatement();
2309 return Error(Loc, ErrorStr);
2312 Parser.Lex(); // Eat the comma.
2316 bool MipsAsmParser::parseDirectiveCPLoad(SMLoc Loc) {
2317 if (Options.isReorder())
2318 Warning(Loc, ".cpload in reorder section");
2320 // FIXME: Warn if cpload is used in Mips16 mode.
2322 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
2323 OperandMatchResultTy ResTy = ParseAnyRegister(Reg);
2324 if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
2325 reportParseError("expected register containing function address");
2329 MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
2330 if (!RegOpnd.isGPRAsmReg()) {
2331 reportParseError(RegOpnd.getStartLoc(), "invalid register");
2335 getTargetStreamer().emitDirectiveCpload(RegOpnd.getGPR32Reg());
2339 bool MipsAsmParser::parseDirectiveCPSetup() {
2342 bool SaveIsReg = true;
2344 if (!parseRegister(FuncReg))
2345 return reportParseError("expected register containing function address");
2346 FuncReg = getGPR(FuncReg);
2348 if (!eatComma("expected comma parsing directive"))
2351 if (!parseRegister(Save)) {
2352 const AsmToken &Tok = Parser.getTok();
2353 if (Tok.is(AsmToken::Integer)) {
2354 Save = Tok.getIntVal();
2358 return reportParseError("expected save register or stack offset");
2360 Save = getGPR(Save);
2362 if (!eatComma("expected comma parsing directive"))
2366 if (Parser.parseIdentifier(Name))
2367 reportParseError("expected identifier");
2368 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2370 getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, *Sym, SaveIsReg);
2374 bool MipsAsmParser::parseDirectiveNaN() {
2375 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2376 const AsmToken &Tok = Parser.getTok();
2378 if (Tok.getString() == "2008") {
2380 getTargetStreamer().emitDirectiveNaN2008();
2382 } else if (Tok.getString() == "legacy") {
2384 getTargetStreamer().emitDirectiveNaNLegacy();
2388 // If we don't recognize the option passed to the .nan
2389 // directive (e.g. no option or unknown option), emit an error.
2390 reportParseError("invalid option in .nan directive");
2394 bool MipsAsmParser::parseDirectiveSet() {
2396 // Get the next token.
2397 const AsmToken &Tok = Parser.getTok();
2399 if (Tok.getString() == "noat") {
2400 return parseSetNoAtDirective();
2401 } else if (Tok.getString() == "at") {
2402 return parseSetAtDirective();
2403 } else if (Tok.getString() == "reorder") {
2404 return parseSetReorderDirective();
2405 } else if (Tok.getString() == "noreorder") {
2406 return parseSetNoReorderDirective();
2407 } else if (Tok.getString() == "macro") {
2408 return parseSetMacroDirective();
2409 } else if (Tok.getString() == "nomacro") {
2410 return parseSetNoMacroDirective();
2411 } else if (Tok.getString() == "mips16") {
2412 return parseSetFeature(Mips::FeatureMips16);
2413 } else if (Tok.getString() == "nomips16") {
2414 return parseSetNoMips16Directive();
2415 } else if (Tok.getString() == "nomicromips") {
2416 getTargetStreamer().emitDirectiveSetNoMicroMips();
2417 Parser.eatToEndOfStatement();
2419 } else if (Tok.getString() == "micromips") {
2420 return parseSetFeature(Mips::FeatureMicroMips);
2421 } else if (Tok.getString() == "mips32r2") {
2422 return parseSetFeature(Mips::FeatureMips32r2);
2423 } else if (Tok.getString() == "mips64") {
2424 return parseSetFeature(Mips::FeatureMips64);
2425 } else if (Tok.getString() == "mips64r2") {
2426 return parseSetFeature(Mips::FeatureMips64r2);
2427 } else if (Tok.getString() == "dsp") {
2428 return parseSetFeature(Mips::FeatureDSP);
2430 // It is just an identifier, look for an assignment.
2431 parseSetAssignment();
2438 /// parseDataDirective
2439 /// ::= .word [ expression (, expression)* ]
2440 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2441 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2443 const MCExpr *Value;
2444 if (getParser().parseExpression(Value))
2447 getParser().getStreamer().EmitValue(Value, Size);
2449 if (getLexer().is(AsmToken::EndOfStatement))
2452 // FIXME: Improve diagnostic.
2453 if (getLexer().isNot(AsmToken::Comma))
2454 return Error(L, "unexpected token in directive");
2463 /// parseDirectiveGpWord
2464 /// ::= .gpword local_sym
2465 bool MipsAsmParser::parseDirectiveGpWord() {
2466 const MCExpr *Value;
2467 // EmitGPRel32Value requires an expression, so we are using base class
2468 // method to evaluate the expression.
2469 if (getParser().parseExpression(Value))
2471 getParser().getStreamer().EmitGPRel32Value(Value);
2473 if (getLexer().isNot(AsmToken::EndOfStatement))
2474 return Error(getLexer().getLoc(), "unexpected token in directive");
2475 Parser.Lex(); // Eat EndOfStatement token.
2479 /// parseDirectiveGpDWord
2480 /// ::= .gpdword local_sym
2481 bool MipsAsmParser::parseDirectiveGpDWord() {
2482 const MCExpr *Value;
2483 // EmitGPRel64Value requires an expression, so we are using base class
2484 // method to evaluate the expression.
2485 if (getParser().parseExpression(Value))
2487 getParser().getStreamer().EmitGPRel64Value(Value);
2489 if (getLexer().isNot(AsmToken::EndOfStatement))
2490 return Error(getLexer().getLoc(), "unexpected token in directive");
2491 Parser.Lex(); // Eat EndOfStatement token.
2495 bool MipsAsmParser::parseDirectiveOption() {
2496 // Get the option token.
2497 AsmToken Tok = Parser.getTok();
2498 // At the moment only identifiers are supported.
2499 if (Tok.isNot(AsmToken::Identifier)) {
2500 Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2501 Parser.eatToEndOfStatement();
2505 StringRef Option = Tok.getIdentifier();
2507 if (Option == "pic0") {
2508 getTargetStreamer().emitDirectiveOptionPic0();
2510 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2511 Error(Parser.getTok().getLoc(),
2512 "unexpected token in .option pic0 directive");
2513 Parser.eatToEndOfStatement();
2518 if (Option == "pic2") {
2519 getTargetStreamer().emitDirectiveOptionPic2();
2521 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2522 Error(Parser.getTok().getLoc(),
2523 "unexpected token in .option pic2 directive");
2524 Parser.eatToEndOfStatement();
2530 Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2531 Parser.eatToEndOfStatement();
2535 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2536 StringRef IDVal = DirectiveID.getString();
2538 if (IDVal == ".cpload")
2539 return parseDirectiveCPLoad(DirectiveID.getLoc());
2540 if (IDVal == ".dword") {
2541 parseDataDirective(8, DirectiveID.getLoc());
2545 if (IDVal == ".ent") {
2546 // Ignore this directive for now.
2551 if (IDVal == ".end") {
2552 // Ignore this directive for now.
2557 if (IDVal == ".frame") {
2558 // Ignore this directive for now.
2559 Parser.eatToEndOfStatement();
2563 if (IDVal == ".set") {
2564 return parseDirectiveSet();
2567 if (IDVal == ".fmask") {
2568 // Ignore this directive for now.
2569 Parser.eatToEndOfStatement();
2573 if (IDVal == ".mask") {
2574 // Ignore this directive for now.
2575 Parser.eatToEndOfStatement();
2579 if (IDVal == ".nan")
2580 return parseDirectiveNaN();
2582 if (IDVal == ".gpword") {
2583 parseDirectiveGpWord();
2587 if (IDVal == ".gpdword") {
2588 parseDirectiveGpDWord();
2592 if (IDVal == ".word") {
2593 parseDataDirective(4, DirectiveID.getLoc());
2597 if (IDVal == ".option")
2598 return parseDirectiveOption();
2600 if (IDVal == ".abicalls") {
2601 getTargetStreamer().emitDirectiveAbiCalls();
2602 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2603 Error(Parser.getTok().getLoc(), "unexpected token in directive");
2605 Parser.eatToEndOfStatement();
2610 if (IDVal == ".cpsetup")
2611 return parseDirectiveCPSetup();
2616 extern "C" void LLVMInitializeMipsAsmParser() {
2617 RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2618 RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2619 RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2620 RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2623 #define GET_REGISTER_MATCHER
2624 #define GET_MATCHER_IMPLEMENTATION
2625 #include "MipsGenAsmMatcher.inc"