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"
37 class MipsAssemblerOptions {
39 MipsAssemblerOptions() : aTReg(1), reorder(true), macro(true) {}
41 unsigned getATRegNum() { return aTReg; }
42 bool setATReg(unsigned Reg);
44 bool isReorder() { return reorder; }
45 void setReorder() { reorder = true; }
46 void setNoreorder() { reorder = false; }
48 bool isMacro() { return macro; }
49 void setMacro() { macro = true; }
50 void setNomacro() { macro = false; }
60 class MipsAsmParser : public MCTargetAsmParser {
61 MipsTargetStreamer &getTargetStreamer() {
62 MCTargetStreamer &TS = *Parser.getStreamer().getTargetStreamer();
63 return static_cast<MipsTargetStreamer &>(TS);
68 MipsAssemblerOptions Options;
70 #define GET_ASSEMBLER_HEADER
71 #include "MipsGenAsmMatcher.inc"
73 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
74 SmallVectorImpl<MCParsedAsmOperand *> &Operands,
75 MCStreamer &Out, unsigned &ErrorInfo,
76 bool MatchingInlineAsm);
78 /// Parse a register as used in CFI directives
79 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
81 bool ParseParenSuffix(StringRef Name,
82 SmallVectorImpl<MCParsedAsmOperand *> &Operands);
84 bool ParseBracketSuffix(StringRef Name,
85 SmallVectorImpl<MCParsedAsmOperand *> &Operands);
87 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
89 SmallVectorImpl<MCParsedAsmOperand *> &Operands);
91 bool ParseDirective(AsmToken DirectiveID);
93 MipsAsmParser::OperandMatchResultTy
94 parseMemOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
96 MipsAsmParser::OperandMatchResultTy MatchAnyRegisterNameWithoutDollar(
97 SmallVectorImpl<MCParsedAsmOperand *> &Operands, StringRef Identifier,
100 MipsAsmParser::OperandMatchResultTy
101 MatchAnyRegisterWithoutDollar(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
104 MipsAsmParser::OperandMatchResultTy
105 ParseAnyRegister(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
107 MipsAsmParser::OperandMatchResultTy
108 ParseImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
110 MipsAsmParser::OperandMatchResultTy
111 ParseJumpTarget(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
113 MipsAsmParser::OperandMatchResultTy
114 parseInvNum(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
116 MipsAsmParser::OperandMatchResultTy
117 ParseLSAImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
119 bool searchSymbolAlias(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
121 bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand *> &,
124 bool needsExpansion(MCInst &Inst);
126 void expandInstruction(MCInst &Inst, SMLoc IDLoc,
127 SmallVectorImpl<MCInst> &Instructions);
128 void expandLoadImm(MCInst &Inst, SMLoc IDLoc,
129 SmallVectorImpl<MCInst> &Instructions);
130 void expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
131 SmallVectorImpl<MCInst> &Instructions);
132 void expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
133 SmallVectorImpl<MCInst> &Instructions);
134 void expandMemInst(MCInst &Inst, SMLoc IDLoc,
135 SmallVectorImpl<MCInst> &Instructions, bool isLoad,
137 bool reportParseError(StringRef ErrorMsg);
139 bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
140 bool parseRelocOperand(const MCExpr *&Res);
142 const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
144 bool isEvaluated(const MCExpr *Expr);
145 bool parseSetFeature(uint64_t Feature);
146 bool parseDirectiveCPSetup();
147 bool parseDirectiveSet();
148 bool parseDirectiveOption();
150 bool parseSetAtDirective();
151 bool parseSetNoAtDirective();
152 bool parseSetMacroDirective();
153 bool parseSetNoMacroDirective();
154 bool parseSetReorderDirective();
155 bool parseSetNoReorderDirective();
156 bool parseSetNoMips16Directive();
158 bool parseSetAssignment();
160 bool parseDataDirective(unsigned Size, SMLoc L);
161 bool parseDirectiveGpWord();
162 bool parseDirectiveGpDWord();
164 MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
166 bool isGP64() const {
167 return (STI.getFeatureBits() & Mips::FeatureGP64Bit) != 0;
170 bool isFP64() const {
171 return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
174 bool isN32() const { return STI.getFeatureBits() & Mips::FeatureN32; }
175 bool isN64() const { return STI.getFeatureBits() & Mips::FeatureN64; }
177 bool isMicroMips() const {
178 return STI.getFeatureBits() & Mips::FeatureMicroMips;
181 bool parseRegister(unsigned &RegNum);
183 bool eatComma(StringRef ErrorStr);
185 int matchCPURegisterName(StringRef Symbol);
187 int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
189 int matchFPURegisterName(StringRef Name);
191 int matchFCCRegisterName(StringRef Name);
193 int matchACRegisterName(StringRef Name);
195 int matchMSA128RegisterName(StringRef Name);
197 int matchMSA128CtrlRegisterName(StringRef Name);
199 unsigned getReg(int RC, int RegNo);
201 unsigned getGPR(int RegNo);
205 bool processInstruction(MCInst &Inst, SMLoc IDLoc,
206 SmallVectorImpl<MCInst> &Instructions);
208 // Helper function that checks if the value of a vector index is within the
209 // boundaries of accepted values for each RegisterKind
210 // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
211 bool validateMSAIndex(int Val, int RegKind);
213 void setFeatureBits(unsigned Feature, StringRef FeatureString) {
214 if (!(STI.getFeatureBits() & Feature)) {
215 setAvailableFeatures(ComputeAvailableFeatures(
216 STI.ToggleFeature(FeatureString)));
220 void clearFeatureBits(unsigned Feature, StringRef FeatureString) {
221 if (STI.getFeatureBits() & Feature) {
222 setAvailableFeatures(ComputeAvailableFeatures(
223 STI.ToggleFeature(FeatureString)));
228 MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
229 const MCInstrInfo &MII)
230 : MCTargetAsmParser(), STI(sti), Parser(parser) {
231 // Initialize the set of available features.
232 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
234 // Assert exactly one ABI was chosen.
235 assert((((STI.getFeatureBits() & Mips::FeatureO32) != 0) +
236 ((STI.getFeatureBits() & Mips::FeatureEABI) != 0) +
237 ((STI.getFeatureBits() & Mips::FeatureN32) != 0) +
238 ((STI.getFeatureBits() & Mips::FeatureN64) != 0)) == 1);
241 MCAsmParser &getParser() const { return Parser; }
242 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
244 /// Warn if RegNo is the current assembler temporary.
245 void WarnIfAssemblerTemporary(int RegNo, SMLoc Loc);
251 /// MipsOperand - Instances of this class represent a parsed Mips machine
253 class MipsOperand : public MCParsedAsmOperand {
255 /// Broad categories of register classes
256 /// The exact class is finalized by the render method.
258 RegKind_GPR = 1, /// GPR32 and GPR64 (depending on isGP64())
259 RegKind_FGR = 2, /// FGR32, FGR64, AFGR64 (depending on context and
261 RegKind_FCC = 4, /// FCC
262 RegKind_MSA128 = 8, /// MSA128[BHWD] (makes no difference which)
263 RegKind_MSACtrl = 16, /// MSA control registers
264 RegKind_COP2 = 32, /// COP2
265 RegKind_ACC = 64, /// HI32DSP, LO32DSP, and ACC64DSP (depending on
267 RegKind_CCR = 128, /// CCR
268 RegKind_HWRegs = 256, /// HWRegs
270 /// Potentially any (e.g. $1)
271 RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
272 RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
273 RegKind_CCR | RegKind_HWRegs
278 k_Immediate, /// An immediate (possibly involving symbol references)
279 k_Memory, /// Base + Offset Memory Address
280 k_PhysRegister, /// A physical register from the Mips namespace
281 k_RegisterIndex, /// A register index in one or more RegKind.
282 k_Token /// A simple token
285 MipsOperand(KindTy K, MipsAsmParser &Parser)
286 : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
288 /// For diagnostics, and checking the assembler temporary
289 MipsAsmParser &AsmParser;
297 unsigned Num; /// Register Number
301 unsigned Index; /// Index into the register class
302 RegKind Kind; /// Bitfield of the kinds it could possibly be
303 const MCRegisterInfo *RegInfo;
317 struct PhysRegOp PhysReg;
318 struct RegIdxOp RegIdx;
323 SMLoc StartLoc, EndLoc;
325 /// Internal constructor for register kinds
326 static MipsOperand *CreateReg(unsigned Index, RegKind RegKind,
327 const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
328 MipsAsmParser &Parser) {
329 MipsOperand *Op = new MipsOperand(k_RegisterIndex, Parser);
330 Op->RegIdx.Index = Index;
331 Op->RegIdx.RegInfo = RegInfo;
332 Op->RegIdx.Kind = RegKind;
339 /// Coerce the register to GPR32 and return the real register for the current
341 unsigned getGPR32Reg() const {
342 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
343 AsmParser.WarnIfAssemblerTemporary(RegIdx.Index, StartLoc);
344 unsigned ClassID = Mips::GPR32RegClassID;
345 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
348 /// Coerce the register to GPR64 and return the real register for the current
350 unsigned getGPR64Reg() const {
351 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
352 unsigned ClassID = Mips::GPR64RegClassID;
353 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
357 /// Coerce the register to AFGR64 and return the real register for the current
359 unsigned getAFGR64Reg() const {
360 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
361 if (RegIdx.Index % 2 != 0)
362 AsmParser.Warning(StartLoc, "Float register should be even.");
363 return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
364 .getRegister(RegIdx.Index / 2);
367 /// Coerce the register to FGR64 and return the real register for the current
369 unsigned getFGR64Reg() const {
370 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
371 return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
372 .getRegister(RegIdx.Index);
375 /// Coerce the register to FGR32 and return the real register for the current
377 unsigned getFGR32Reg() const {
378 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
379 return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
380 .getRegister(RegIdx.Index);
383 /// Coerce the register to FGRH32 and return the real register for the current
385 unsigned getFGRH32Reg() const {
386 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
387 return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
388 .getRegister(RegIdx.Index);
391 /// Coerce the register to FCC and return the real register for the current
393 unsigned getFCCReg() const {
394 assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
395 return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
396 .getRegister(RegIdx.Index);
399 /// Coerce the register to MSA128 and return the real register for the current
401 unsigned getMSA128Reg() const {
402 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
403 // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
405 unsigned ClassID = Mips::MSA128BRegClassID;
406 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
409 /// Coerce the register to MSACtrl and return the real register for the
411 unsigned getMSACtrlReg() const {
412 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
413 unsigned ClassID = Mips::MSACtrlRegClassID;
414 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
417 /// Coerce the register to COP2 and return the real register for the
419 unsigned getCOP2Reg() const {
420 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
421 unsigned ClassID = Mips::COP2RegClassID;
422 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
425 /// Coerce the register to ACC64DSP and return the real register for the
427 unsigned getACC64DSPReg() const {
428 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
429 unsigned ClassID = Mips::ACC64DSPRegClassID;
430 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
433 /// Coerce the register to HI32DSP and return the real register for the
435 unsigned getHI32DSPReg() const {
436 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
437 unsigned ClassID = Mips::HI32DSPRegClassID;
438 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
441 /// Coerce the register to LO32DSP and return the real register for the
443 unsigned getLO32DSPReg() const {
444 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
445 unsigned ClassID = Mips::LO32DSPRegClassID;
446 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
449 /// Coerce the register to CCR and return the real register for the
451 unsigned getCCRReg() const {
452 assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
453 unsigned ClassID = Mips::CCRRegClassID;
454 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
457 /// Coerce the register to HWRegs and return the real register for the
459 unsigned getHWRegsReg() const {
460 assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
461 unsigned ClassID = Mips::HWRegsRegClassID;
462 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
466 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
467 // Add as immediate when possible. Null MCExpr = 0.
469 Inst.addOperand(MCOperand::CreateImm(0));
470 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
471 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
473 Inst.addOperand(MCOperand::CreateExpr(Expr));
476 void addRegOperands(MCInst &Inst, unsigned N) const {
477 llvm_unreachable("Use a custom parser instead");
480 /// Render the operand to an MCInst as a GPR32
481 /// Asserts if the wrong number of operands are requested, or the operand
482 /// is not a k_RegisterIndex compatible with RegKind_GPR
483 void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
484 assert(N == 1 && "Invalid number of operands!");
485 Inst.addOperand(MCOperand::CreateReg(getGPR32Reg()));
488 /// Render the operand to an MCInst as a GPR64
489 /// Asserts if the wrong number of operands are requested, or the operand
490 /// is not a k_RegisterIndex compatible with RegKind_GPR
491 void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
492 assert(N == 1 && "Invalid number of operands!");
493 Inst.addOperand(MCOperand::CreateReg(getGPR64Reg()));
496 void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
497 assert(N == 1 && "Invalid number of operands!");
498 Inst.addOperand(MCOperand::CreateReg(getAFGR64Reg()));
501 void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
502 assert(N == 1 && "Invalid number of operands!");
503 Inst.addOperand(MCOperand::CreateReg(getFGR64Reg()));
506 void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
507 assert(N == 1 && "Invalid number of operands!");
508 Inst.addOperand(MCOperand::CreateReg(getFGR32Reg()));
511 void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
512 assert(N == 1 && "Invalid number of operands!");
513 Inst.addOperand(MCOperand::CreateReg(getFGRH32Reg()));
516 void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
517 assert(N == 1 && "Invalid number of operands!");
518 Inst.addOperand(MCOperand::CreateReg(getFCCReg()));
521 void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
522 assert(N == 1 && "Invalid number of operands!");
523 Inst.addOperand(MCOperand::CreateReg(getMSA128Reg()));
526 void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
527 assert(N == 1 && "Invalid number of operands!");
528 Inst.addOperand(MCOperand::CreateReg(getMSACtrlReg()));
531 void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
532 assert(N == 1 && "Invalid number of operands!");
533 Inst.addOperand(MCOperand::CreateReg(getCOP2Reg()));
536 void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
537 assert(N == 1 && "Invalid number of operands!");
538 Inst.addOperand(MCOperand::CreateReg(getACC64DSPReg()));
541 void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
542 assert(N == 1 && "Invalid number of operands!");
543 Inst.addOperand(MCOperand::CreateReg(getHI32DSPReg()));
546 void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
547 assert(N == 1 && "Invalid number of operands!");
548 Inst.addOperand(MCOperand::CreateReg(getLO32DSPReg()));
551 void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
552 assert(N == 1 && "Invalid number of operands!");
553 Inst.addOperand(MCOperand::CreateReg(getCCRReg()));
556 void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
557 assert(N == 1 && "Invalid number of operands!");
558 Inst.addOperand(MCOperand::CreateReg(getHWRegsReg()));
561 void addImmOperands(MCInst &Inst, unsigned N) const {
562 assert(N == 1 && "Invalid number of operands!");
563 const MCExpr *Expr = getImm();
567 void addMemOperands(MCInst &Inst, unsigned N) const {
568 assert(N == 2 && "Invalid number of operands!");
570 Inst.addOperand(MCOperand::CreateReg(getMemBase()->getGPR32Reg()));
572 const MCExpr *Expr = getMemOff();
577 // As a special case until we sort out the definition of div/divu, pretend
578 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
579 if (isGPRAsmReg() && RegIdx.Index == 0)
582 return Kind == k_PhysRegister;
584 bool isRegIdx() const { return Kind == k_RegisterIndex; }
585 bool isImm() const { return Kind == k_Immediate; }
586 bool isConstantImm() const {
587 return isImm() && dyn_cast<MCConstantExpr>(getImm());
589 bool isToken() const {
590 // Note: It's not possible to pretend that other operand kinds are tokens.
591 // The matcher emitter checks tokens first.
592 return Kind == k_Token;
594 bool isMem() const { return Kind == k_Memory; }
595 bool isInvNum() const { return Kind == k_Immediate; }
596 bool isLSAImm() const {
597 if (!isConstantImm())
599 int64_t Val = getConstantImm();
600 return 1 <= Val && Val <= 4;
603 StringRef getToken() const {
604 assert(Kind == k_Token && "Invalid access!");
605 return StringRef(Tok.Data, Tok.Length);
608 unsigned getReg() const {
609 // As a special case until we sort out the definition of div/divu, pretend
610 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
611 if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
612 RegIdx.Kind & RegKind_GPR)
613 return getGPR32Reg(); // FIXME: GPR64 too
615 assert(Kind == k_PhysRegister && "Invalid access!");
619 const MCExpr *getImm() const {
620 assert((Kind == k_Immediate) && "Invalid access!");
624 int64_t getConstantImm() const {
625 const MCExpr *Val = getImm();
626 return static_cast<const MCConstantExpr *>(Val)->getValue();
629 MipsOperand *getMemBase() const {
630 assert((Kind == k_Memory) && "Invalid access!");
634 const MCExpr *getMemOff() const {
635 assert((Kind == k_Memory) && "Invalid access!");
639 static MipsOperand *CreateToken(StringRef Str, SMLoc S,
640 MipsAsmParser &Parser) {
641 MipsOperand *Op = new MipsOperand(k_Token, Parser);
642 Op->Tok.Data = Str.data();
643 Op->Tok.Length = Str.size();
649 /// Create a numeric register (e.g. $1). The exact register remains
650 /// unresolved until an instruction successfully matches
651 static MipsOperand *CreateNumericReg(unsigned Index,
652 const MCRegisterInfo *RegInfo, SMLoc S,
653 SMLoc E, MipsAsmParser &Parser) {
654 DEBUG(dbgs() << "CreateNumericReg(" << Index << ", ...)\n");
655 return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
658 /// Create a register that is definitely a GPR.
659 /// This is typically only used for named registers such as $gp.
660 static MipsOperand *CreateGPRReg(unsigned Index,
661 const MCRegisterInfo *RegInfo, SMLoc S,
662 SMLoc E, MipsAsmParser &Parser) {
663 return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
666 /// Create a register that is definitely a FGR.
667 /// This is typically only used for named registers such as $f0.
668 static MipsOperand *CreateFGRReg(unsigned Index,
669 const MCRegisterInfo *RegInfo, SMLoc S,
670 SMLoc E, MipsAsmParser &Parser) {
671 return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
674 /// Create a register that is definitely an FCC.
675 /// This is typically only used for named registers such as $fcc0.
676 static MipsOperand *CreateFCCReg(unsigned Index,
677 const MCRegisterInfo *RegInfo, SMLoc S,
678 SMLoc E, MipsAsmParser &Parser) {
679 return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
682 /// Create a register that is definitely an ACC.
683 /// This is typically only used for named registers such as $ac0.
684 static MipsOperand *CreateACCReg(unsigned Index,
685 const MCRegisterInfo *RegInfo, SMLoc S,
686 SMLoc E, MipsAsmParser &Parser) {
687 return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
690 /// Create a register that is definitely an MSA128.
691 /// This is typically only used for named registers such as $w0.
692 static MipsOperand *CreateMSA128Reg(unsigned Index,
693 const MCRegisterInfo *RegInfo, SMLoc S,
694 SMLoc E, MipsAsmParser &Parser) {
695 return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
698 /// Create a register that is definitely an MSACtrl.
699 /// This is typically only used for named registers such as $msaaccess.
700 static MipsOperand *CreateMSACtrlReg(unsigned Index,
701 const MCRegisterInfo *RegInfo, SMLoc S,
702 SMLoc E, MipsAsmParser &Parser) {
703 return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
706 static MipsOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E,
707 MipsAsmParser &Parser) {
708 MipsOperand *Op = new MipsOperand(k_Immediate, Parser);
715 static MipsOperand *CreateMem(MipsOperand *Base, const MCExpr *Off, SMLoc S,
716 SMLoc E, MipsAsmParser &Parser) {
717 MipsOperand *Op = new MipsOperand(k_Memory, Parser);
725 bool isGPRAsmReg() const {
726 return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
728 bool isFGRAsmReg() const {
729 // AFGR64 is $0-$15 but we handle this in getAFGR64()
730 return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
732 bool isHWRegsAsmReg() const {
733 return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
735 bool isCCRAsmReg() const {
736 return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
738 bool isFCCAsmReg() const {
739 return isRegIdx() && RegIdx.Kind & RegKind_FCC && RegIdx.Index <= 7;
741 bool isACCAsmReg() const {
742 return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
744 bool isCOP2AsmReg() const {
745 return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
747 bool isMSA128AsmReg() const {
748 return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
750 bool isMSACtrlAsmReg() const {
751 return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
754 /// getStartLoc - Get the location of the first token of this operand.
755 SMLoc getStartLoc() const { return StartLoc; }
756 /// getEndLoc - Get the location of the last token of this operand.
757 SMLoc getEndLoc() const { return EndLoc; }
759 virtual void print(raw_ostream &OS) const {
774 OS << "PhysReg<" << PhysReg.Num << ">";
776 case k_RegisterIndex:
777 OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
784 }; // class MipsOperand
788 extern const MCInstrDesc MipsInsts[];
790 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
791 return MipsInsts[Opcode];
794 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
795 SmallVectorImpl<MCInst> &Instructions) {
796 const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
800 if (MCID.isBranch() || MCID.isCall()) {
801 const unsigned Opcode = Inst.getOpcode();
811 assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
812 Offset = Inst.getOperand(2);
814 break; // We'll deal with this situation later on when applying fixups.
815 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
816 return Error(IDLoc, "branch target out of range");
817 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
818 return Error(IDLoc, "branch to misaligned address");
832 case Mips::BGEZAL_MM:
833 case Mips::BLTZAL_MM:
836 assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
837 Offset = Inst.getOperand(1);
839 break; // We'll deal with this situation later on when applying fixups.
840 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
841 return Error(IDLoc, "branch target out of range");
842 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
843 return Error(IDLoc, "branch to misaligned address");
848 if (MCID.hasDelaySlot() && Options.isReorder()) {
849 // If this instruction has a delay slot and .set reorder is active,
850 // emit a NOP after it.
851 Instructions.push_back(Inst);
853 NopInst.setOpcode(Mips::SLL);
854 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
855 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
856 NopInst.addOperand(MCOperand::CreateImm(0));
857 Instructions.push_back(NopInst);
861 if (MCID.mayLoad() || MCID.mayStore()) {
862 // Check the offset of memory operand, if it is a symbol
863 // reference or immediate we may have to expand instructions.
864 for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
865 const MCOperandInfo &OpInfo = MCID.OpInfo[i];
866 if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
867 (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
868 MCOperand &Op = Inst.getOperand(i);
870 int MemOffset = Op.getImm();
871 if (MemOffset < -32768 || MemOffset > 32767) {
872 // Offset can't exceed 16bit value.
873 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
876 } else if (Op.isExpr()) {
877 const MCExpr *Expr = Op.getExpr();
878 if (Expr->getKind() == MCExpr::SymbolRef) {
879 const MCSymbolRefExpr *SR =
880 static_cast<const MCSymbolRefExpr *>(Expr);
881 if (SR->getKind() == MCSymbolRefExpr::VK_None) {
883 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
886 } else if (!isEvaluated(Expr)) {
887 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
895 if (needsExpansion(Inst))
896 expandInstruction(Inst, IDLoc, Instructions);
898 Instructions.push_back(Inst);
903 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
905 switch (Inst.getOpcode()) {
906 case Mips::LoadImm32Reg:
907 case Mips::LoadAddr32Imm:
908 case Mips::LoadAddr32Reg:
915 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
916 SmallVectorImpl<MCInst> &Instructions) {
917 switch (Inst.getOpcode()) {
918 case Mips::LoadImm32Reg:
919 return expandLoadImm(Inst, IDLoc, Instructions);
920 case Mips::LoadAddr32Imm:
921 return expandLoadAddressImm(Inst, IDLoc, Instructions);
922 case Mips::LoadAddr32Reg:
923 return expandLoadAddressReg(Inst, IDLoc, Instructions);
927 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
928 SmallVectorImpl<MCInst> &Instructions) {
930 const MCOperand &ImmOp = Inst.getOperand(1);
931 assert(ImmOp.isImm() && "expected immediate operand kind");
932 const MCOperand &RegOp = Inst.getOperand(0);
933 assert(RegOp.isReg() && "expected register operand kind");
935 int ImmValue = ImmOp.getImm();
936 tmpInst.setLoc(IDLoc);
937 if (0 <= ImmValue && ImmValue <= 65535) {
938 // For 0 <= j <= 65535.
939 // li d,j => ori d,$zero,j
940 tmpInst.setOpcode(Mips::ORi);
941 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
942 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
943 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
944 Instructions.push_back(tmpInst);
945 } else if (ImmValue < 0 && ImmValue >= -32768) {
946 // For -32768 <= j < 0.
947 // li d,j => addiu d,$zero,j
948 tmpInst.setOpcode(Mips::ADDiu);
949 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
950 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
951 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
952 Instructions.push_back(tmpInst);
954 // For any other value of j that is representable as a 32-bit integer.
955 // li d,j => lui d,hi16(j)
957 tmpInst.setOpcode(Mips::LUi);
958 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
959 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
960 Instructions.push_back(tmpInst);
962 tmpInst.setOpcode(Mips::ORi);
963 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
964 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
965 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
966 tmpInst.setLoc(IDLoc);
967 Instructions.push_back(tmpInst);
972 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
973 SmallVectorImpl<MCInst> &Instructions) {
975 const MCOperand &ImmOp = Inst.getOperand(2);
976 assert(ImmOp.isImm() && "expected immediate operand kind");
977 const MCOperand &SrcRegOp = Inst.getOperand(1);
978 assert(SrcRegOp.isReg() && "expected register operand kind");
979 const MCOperand &DstRegOp = Inst.getOperand(0);
980 assert(DstRegOp.isReg() && "expected register operand kind");
981 int ImmValue = ImmOp.getImm();
982 if (-32768 <= ImmValue && ImmValue <= 65535) {
983 // For -32768 <= j <= 65535.
984 // la d,j(s) => addiu d,s,j
985 tmpInst.setOpcode(Mips::ADDiu);
986 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
987 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
988 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
989 Instructions.push_back(tmpInst);
991 // For any other value of j that is representable as a 32-bit integer.
992 // la d,j(s) => lui d,hi16(j)
995 tmpInst.setOpcode(Mips::LUi);
996 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
997 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
998 Instructions.push_back(tmpInst);
1000 tmpInst.setOpcode(Mips::ORi);
1001 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1002 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1003 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1004 Instructions.push_back(tmpInst);
1006 tmpInst.setOpcode(Mips::ADDu);
1007 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1008 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1009 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1010 Instructions.push_back(tmpInst);
1015 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
1016 SmallVectorImpl<MCInst> &Instructions) {
1018 const MCOperand &ImmOp = Inst.getOperand(1);
1019 assert(ImmOp.isImm() && "expected immediate operand kind");
1020 const MCOperand &RegOp = Inst.getOperand(0);
1021 assert(RegOp.isReg() && "expected register operand kind");
1022 int ImmValue = ImmOp.getImm();
1023 if (-32768 <= ImmValue && ImmValue <= 65535) {
1024 // For -32768 <= j <= 65535.
1025 // la d,j => addiu d,$zero,j
1026 tmpInst.setOpcode(Mips::ADDiu);
1027 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1028 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1029 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1030 Instructions.push_back(tmpInst);
1032 // For any other value of j that is representable as a 32-bit integer.
1033 // la d,j => lui d,hi16(j)
1035 tmpInst.setOpcode(Mips::LUi);
1036 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1037 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1038 Instructions.push_back(tmpInst);
1040 tmpInst.setOpcode(Mips::ORi);
1041 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1042 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1043 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1044 Instructions.push_back(tmpInst);
1048 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
1049 SmallVectorImpl<MCInst> &Instructions,
1050 bool isLoad, bool isImmOpnd) {
1051 const MCSymbolRefExpr *SR;
1053 unsigned ImmOffset, HiOffset, LoOffset;
1054 const MCExpr *ExprOffset;
1056 unsigned AtRegNum = getReg(
1057 (isGP64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
1058 // 1st operand is either the source or destination register.
1059 assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1060 unsigned RegOpNum = Inst.getOperand(0).getReg();
1061 // 2nd operand is the base register.
1062 assert(Inst.getOperand(1).isReg() && "expected register operand kind");
1063 unsigned BaseRegNum = Inst.getOperand(1).getReg();
1064 // 3rd operand is either an immediate or expression.
1066 assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
1067 ImmOffset = Inst.getOperand(2).getImm();
1068 LoOffset = ImmOffset & 0x0000ffff;
1069 HiOffset = (ImmOffset & 0xffff0000) >> 16;
1070 // If msb of LoOffset is 1(negative number) we must increment HiOffset.
1071 if (LoOffset & 0x8000)
1074 ExprOffset = Inst.getOperand(2).getExpr();
1075 // All instructions will have the same location.
1076 TempInst.setLoc(IDLoc);
1077 // 1st instruction in expansion is LUi. For load instruction we can use
1078 // the dst register as a temporary if base and dst are different,
1079 // but for stores we must use $at.
1080 TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
1081 TempInst.setOpcode(Mips::LUi);
1082 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1084 TempInst.addOperand(MCOperand::CreateImm(HiOffset));
1086 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1087 SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
1088 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
1089 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
1091 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1093 const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
1094 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1097 // Add the instruction to the list.
1098 Instructions.push_back(TempInst);
1099 // Prepare TempInst for next instruction.
1101 // Add temp register to base.
1102 TempInst.setOpcode(Mips::ADDu);
1103 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1104 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1105 TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
1106 Instructions.push_back(TempInst);
1108 // And finally, create original instruction with low part
1109 // of offset and new base.
1110 TempInst.setOpcode(Inst.getOpcode());
1111 TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
1112 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1114 TempInst.addOperand(MCOperand::CreateImm(LoOffset));
1116 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1117 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
1118 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
1120 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1122 const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
1123 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1126 Instructions.push_back(TempInst);
1130 bool MipsAsmParser::MatchAndEmitInstruction(
1131 SMLoc IDLoc, unsigned &Opcode,
1132 SmallVectorImpl<MCParsedAsmOperand *> &Operands, MCStreamer &Out,
1133 unsigned &ErrorInfo, bool MatchingInlineAsm) {
1135 SmallVector<MCInst, 8> Instructions;
1136 unsigned MatchResult =
1137 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
1139 switch (MatchResult) {
1142 case Match_Success: {
1143 if (processInstruction(Inst, IDLoc, Instructions))
1145 for (unsigned i = 0; i < Instructions.size(); i++)
1146 Out.EmitInstruction(Instructions[i], STI);
1149 case Match_MissingFeature:
1150 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1152 case Match_InvalidOperand: {
1153 SMLoc ErrorLoc = IDLoc;
1154 if (ErrorInfo != ~0U) {
1155 if (ErrorInfo >= Operands.size())
1156 return Error(IDLoc, "too few operands for instruction");
1158 ErrorLoc = ((MipsOperand *)Operands[ErrorInfo])->getStartLoc();
1159 if (ErrorLoc == SMLoc())
1163 return Error(ErrorLoc, "invalid operand for instruction");
1165 case Match_MnemonicFail:
1166 return Error(IDLoc, "invalid instruction");
1171 void MipsAsmParser::WarnIfAssemblerTemporary(int RegIndex, SMLoc Loc) {
1172 if ((RegIndex != 0) && ((int)Options.getATRegNum() == RegIndex)) {
1174 Warning(Loc, "Used $at without \".set noat\"");
1176 Warning(Loc, Twine("Used $") + Twine(RegIndex) + " with \".set at=$" +
1177 Twine(RegIndex) + "\"");
1181 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
1184 CC = StringSwitch<unsigned>(Name)
1220 if (isN32() || isN64()) {
1221 // Although SGI documentation just cuts out t0-t3 for n32/n64,
1222 // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
1223 // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
1224 if (8 <= CC && CC <= 11)
1228 CC = StringSwitch<unsigned>(Name)
1241 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
1243 if (Name[0] == 'f') {
1244 StringRef NumString = Name.substr(1);
1246 if (NumString.getAsInteger(10, IntVal))
1247 return -1; // This is not an integer.
1248 if (IntVal > 31) // Maximum index for fpu register.
1255 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1257 if (Name.startswith("fcc")) {
1258 StringRef NumString = Name.substr(3);
1260 if (NumString.getAsInteger(10, IntVal))
1261 return -1; // This is not an integer.
1262 if (IntVal > 7) // There are only 8 fcc registers.
1269 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1271 if (Name.startswith("ac")) {
1272 StringRef NumString = Name.substr(2);
1274 if (NumString.getAsInteger(10, IntVal))
1275 return -1; // This is not an integer.
1276 if (IntVal > 3) // There are only 3 acc registers.
1283 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1286 if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1295 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1298 CC = StringSwitch<unsigned>(Name)
1301 .Case("msaaccess", 2)
1303 .Case("msamodify", 4)
1304 .Case("msarequest", 5)
1306 .Case("msaunmap", 7)
1312 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1320 int MipsAsmParser::getATReg() {
1321 int AT = Options.getATRegNum();
1323 TokError("Pseudo instruction requires $at, which is not available");
1327 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1328 return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1331 unsigned MipsAsmParser::getGPR(int RegNo) {
1332 return getReg(isGP64() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1336 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1338 getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1341 return getReg(RegClass, RegNum);
1345 MipsAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1346 StringRef Mnemonic) {
1347 DEBUG(dbgs() << "ParseOperand\n");
1349 // Check if the current operand has a custom associated parser, if so, try to
1350 // custom parse the operand, or fallback to the general approach.
1351 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1352 if (ResTy == MatchOperand_Success)
1354 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1355 // there was a match, but an error occurred, in which case, just return that
1356 // the operand parsing failed.
1357 if (ResTy == MatchOperand_ParseFail)
1360 DEBUG(dbgs() << ".. Generic Parser\n");
1362 switch (getLexer().getKind()) {
1364 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1366 case AsmToken::Dollar: {
1367 // Parse the register.
1368 SMLoc S = Parser.getTok().getLoc();
1370 // Almost all registers have been parsed by custom parsers. There is only
1371 // one exception to this. $zero (and it's alias $0) will reach this point
1372 // for div, divu, and similar instructions because it is not an operand
1373 // to the instruction definition but an explicit register. Special case
1374 // this situation for now.
1375 if (ParseAnyRegister(Operands) != MatchOperand_NoMatch)
1378 // Maybe it is a symbol reference.
1379 StringRef Identifier;
1380 if (Parser.parseIdentifier(Identifier))
1383 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1384 MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1385 // Otherwise create a symbol reference.
1387 MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1389 Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
1392 // Else drop to expression parsing.
1393 case AsmToken::LParen:
1394 case AsmToken::Minus:
1395 case AsmToken::Plus:
1396 case AsmToken::Integer:
1397 case AsmToken::String: {
1398 DEBUG(dbgs() << ".. generic integer\n");
1399 OperandMatchResultTy ResTy = ParseImm(Operands);
1400 return ResTy != MatchOperand_Success;
1402 case AsmToken::Percent: {
1403 // It is a symbol reference or constant expression.
1404 const MCExpr *IdVal;
1405 SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1406 if (parseRelocOperand(IdVal))
1409 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1411 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1413 } // case AsmToken::Percent
1414 } // switch(getLexer().getKind())
1418 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1419 StringRef RelocStr) {
1421 // Check the type of the expression.
1422 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1423 // It's a constant, evaluate reloc value.
1425 switch (getVariantKind(RelocStr)) {
1426 case MCSymbolRefExpr::VK_Mips_ABS_LO:
1427 // Get the 1st 16-bits.
1428 Val = MCE->getValue() & 0xffff;
1430 case MCSymbolRefExpr::VK_Mips_ABS_HI:
1431 // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
1432 // 16 bits being negative.
1433 Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
1435 case MCSymbolRefExpr::VK_Mips_HIGHER:
1436 // Get the 3rd 16-bits.
1437 Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
1439 case MCSymbolRefExpr::VK_Mips_HIGHEST:
1440 // Get the 4th 16-bits.
1441 Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
1444 report_fatal_error("Unsupported reloc value!");
1446 return MCConstantExpr::Create(Val, getContext());
1449 if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1450 // It's a symbol, create a symbolic expression from the symbol.
1451 StringRef Symbol = MSRE->getSymbol().getName();
1452 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1453 Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1457 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1458 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1460 // Try to create target expression.
1461 if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
1462 return MipsMCExpr::Create(VK, Expr, getContext());
1464 const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1465 const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1466 Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1470 if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1471 const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1472 Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1475 // Just return the original expression.
1479 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1481 switch (Expr->getKind()) {
1482 case MCExpr::Constant:
1484 case MCExpr::SymbolRef:
1485 return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1486 case MCExpr::Binary:
1487 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1488 if (!isEvaluated(BE->getLHS()))
1490 return isEvaluated(BE->getRHS());
1493 return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1494 case MCExpr::Target:
1500 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1501 Parser.Lex(); // Eat the % token.
1502 const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1503 if (Tok.isNot(AsmToken::Identifier))
1506 std::string Str = Tok.getIdentifier().str();
1508 Parser.Lex(); // Eat the identifier.
1509 // Now make an expression from the rest of the operand.
1510 const MCExpr *IdVal;
1513 if (getLexer().getKind() == AsmToken::LParen) {
1515 Parser.Lex(); // Eat the '(' token.
1516 if (getLexer().getKind() == AsmToken::Percent) {
1517 Parser.Lex(); // Eat the % token.
1518 const AsmToken &nextTok = Parser.getTok();
1519 if (nextTok.isNot(AsmToken::Identifier))
1522 Str += nextTok.getIdentifier();
1523 Parser.Lex(); // Eat the identifier.
1524 if (getLexer().getKind() != AsmToken::LParen)
1529 if (getParser().parseParenExpression(IdVal, EndLoc))
1532 while (getLexer().getKind() == AsmToken::RParen)
1533 Parser.Lex(); // Eat the ')' token.
1536 return true; // Parenthesis must follow the relocation operand.
1538 Res = evaluateRelocExpr(IdVal, Str);
1542 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1544 SmallVector<MCParsedAsmOperand *, 1> Operands;
1545 OperandMatchResultTy ResTy = ParseAnyRegister(Operands);
1546 if (ResTy == MatchOperand_Success) {
1547 assert(Operands.size() == 1);
1548 MipsOperand &Operand = *static_cast<MipsOperand *>(Operands.front());
1549 StartLoc = Operand.getStartLoc();
1550 EndLoc = Operand.getEndLoc();
1552 // AFAIK, we only support numeric registers and named GPR's in CFI
1554 // Don't worry about eating tokens before failing. Using an unrecognised
1555 // register is a parse error.
1556 if (Operand.isGPRAsmReg()) {
1557 // Resolve to GPR32 or GPR64 appropriately.
1558 RegNo = isGP64() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
1563 return (RegNo == (unsigned)-1);
1566 assert(Operands.size() == 0);
1567 return (RegNo == (unsigned)-1);
1570 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1574 while (getLexer().getKind() == AsmToken::LParen)
1577 switch (getLexer().getKind()) {
1580 case AsmToken::Identifier:
1581 case AsmToken::LParen:
1582 case AsmToken::Integer:
1583 case AsmToken::Minus:
1584 case AsmToken::Plus:
1586 Result = getParser().parseParenExpression(Res, S);
1588 Result = (getParser().parseExpression(Res));
1589 while (getLexer().getKind() == AsmToken::RParen)
1592 case AsmToken::Percent:
1593 Result = parseRelocOperand(Res);
1598 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMemOperand(
1599 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1600 DEBUG(dbgs() << "parseMemOperand\n");
1601 const MCExpr *IdVal = 0;
1603 bool isParenExpr = false;
1604 MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1605 // First operand is the offset.
1606 S = Parser.getTok().getLoc();
1608 if (getLexer().getKind() == AsmToken::LParen) {
1613 if (getLexer().getKind() != AsmToken::Dollar) {
1614 if (parseMemOffset(IdVal, isParenExpr))
1615 return MatchOperand_ParseFail;
1617 const AsmToken &Tok = Parser.getTok(); // Get the next token.
1618 if (Tok.isNot(AsmToken::LParen)) {
1619 MipsOperand *Mnemonic = static_cast<MipsOperand *>(Operands[0]);
1620 if (Mnemonic->getToken() == "la") {
1622 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1623 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1624 return MatchOperand_Success;
1626 if (Tok.is(AsmToken::EndOfStatement)) {
1628 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1630 // Zero register assumed, add a memory operand with ZERO as its base.
1631 MipsOperand *Base = MipsOperand::CreateGPRReg(
1632 0, getContext().getRegisterInfo(), S, E, *this);
1633 Operands.push_back(MipsOperand::CreateMem(Base, IdVal, S, E, *this));
1634 return MatchOperand_Success;
1636 Error(Parser.getTok().getLoc(), "'(' expected");
1637 return MatchOperand_ParseFail;
1640 Parser.Lex(); // Eat the '(' token.
1643 Res = ParseAnyRegister(Operands);
1644 if (Res != MatchOperand_Success)
1647 if (Parser.getTok().isNot(AsmToken::RParen)) {
1648 Error(Parser.getTok().getLoc(), "')' expected");
1649 return MatchOperand_ParseFail;
1652 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1654 Parser.Lex(); // Eat the ')' token.
1657 IdVal = MCConstantExpr::Create(0, getContext());
1659 // Replace the register operand with the memory operand.
1660 MipsOperand *op = static_cast<MipsOperand *>(Operands.back());
1661 // Remove the register from the operands.
1662 Operands.pop_back();
1663 // Add the memory operand.
1664 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1666 if (IdVal->EvaluateAsAbsolute(Imm))
1667 IdVal = MCConstantExpr::Create(Imm, getContext());
1668 else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1669 IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1673 Operands.push_back(MipsOperand::CreateMem(op, IdVal, S, E, *this));
1674 return MatchOperand_Success;
1677 bool MipsAsmParser::searchSymbolAlias(
1678 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1680 MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
1682 SMLoc S = Parser.getTok().getLoc();
1684 if (Sym->isVariable())
1685 Expr = Sym->getVariableValue();
1688 if (Expr->getKind() == MCExpr::SymbolRef) {
1689 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
1690 const StringRef DefSymbol = Ref->getSymbol().getName();
1691 if (DefSymbol.startswith("$")) {
1692 OperandMatchResultTy ResTy =
1693 MatchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
1694 if (ResTy == MatchOperand_Success) {
1697 } else if (ResTy == MatchOperand_ParseFail)
1698 llvm_unreachable("Should never ParseFail");
1701 } else if (Expr->getKind() == MCExpr::Constant) {
1703 const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
1705 MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this);
1706 Operands.push_back(op);
1713 MipsAsmParser::OperandMatchResultTy
1714 MipsAsmParser::MatchAnyRegisterNameWithoutDollar(
1715 SmallVectorImpl<MCParsedAsmOperand *> &Operands, StringRef Identifier,
1717 int Index = matchCPURegisterName(Identifier);
1719 Operands.push_back(MipsOperand::CreateGPRReg(
1720 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1721 return MatchOperand_Success;
1724 Index = matchFPURegisterName(Identifier);
1726 Operands.push_back(MipsOperand::CreateFGRReg(
1727 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1728 return MatchOperand_Success;
1731 Index = matchFCCRegisterName(Identifier);
1733 Operands.push_back(MipsOperand::CreateFCCReg(
1734 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1735 return MatchOperand_Success;
1738 Index = matchACRegisterName(Identifier);
1740 Operands.push_back(MipsOperand::CreateACCReg(
1741 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1742 return MatchOperand_Success;
1745 Index = matchMSA128RegisterName(Identifier);
1747 Operands.push_back(MipsOperand::CreateMSA128Reg(
1748 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1749 return MatchOperand_Success;
1752 Index = matchMSA128CtrlRegisterName(Identifier);
1754 Operands.push_back(MipsOperand::CreateMSACtrlReg(
1755 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1756 return MatchOperand_Success;
1759 return MatchOperand_NoMatch;
1762 MipsAsmParser::OperandMatchResultTy
1763 MipsAsmParser::MatchAnyRegisterWithoutDollar(
1764 SmallVectorImpl<MCParsedAsmOperand *> &Operands, SMLoc S) {
1765 auto Token = Parser.getLexer().peekTok(false);
1767 if (Token.is(AsmToken::Identifier)) {
1768 DEBUG(dbgs() << ".. identifier\n");
1769 StringRef Identifier = Token.getIdentifier();
1770 OperandMatchResultTy ResTy =
1771 MatchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
1773 } else if (Token.is(AsmToken::Integer)) {
1774 DEBUG(dbgs() << ".. integer\n");
1775 Operands.push_back(MipsOperand::CreateNumericReg(
1776 Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
1778 return MatchOperand_Success;
1781 DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
1783 return MatchOperand_NoMatch;
1786 MipsAsmParser::OperandMatchResultTy MipsAsmParser::ParseAnyRegister(
1787 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1788 DEBUG(dbgs() << "ParseAnyRegister\n");
1790 auto Token = Parser.getTok();
1792 SMLoc S = Token.getLoc();
1794 if (Token.isNot(AsmToken::Dollar)) {
1795 DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
1796 if (Token.is(AsmToken::Identifier)) {
1797 if (searchSymbolAlias(Operands))
1798 return MatchOperand_Success;
1800 DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
1801 return MatchOperand_NoMatch;
1803 DEBUG(dbgs() << ".. $\n");
1805 OperandMatchResultTy ResTy = MatchAnyRegisterWithoutDollar(Operands, S);
1806 if (ResTy == MatchOperand_Success) {
1808 Parser.Lex(); // identifier
1813 MipsAsmParser::OperandMatchResultTy
1814 MipsAsmParser::ParseImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1815 switch (getLexer().getKind()) {
1817 return MatchOperand_NoMatch;
1818 case AsmToken::LParen:
1819 case AsmToken::Minus:
1820 case AsmToken::Plus:
1821 case AsmToken::Integer:
1822 case AsmToken::String:
1826 const MCExpr *IdVal;
1827 SMLoc S = Parser.getTok().getLoc();
1828 if (getParser().parseExpression(IdVal))
1829 return MatchOperand_ParseFail;
1831 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1832 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1833 return MatchOperand_Success;
1836 MipsAsmParser::OperandMatchResultTy MipsAsmParser::ParseJumpTarget(
1837 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1838 DEBUG(dbgs() << "ParseJumpTarget\n");
1840 SMLoc S = getLexer().getLoc();
1842 // Integers and expressions are acceptable
1843 OperandMatchResultTy ResTy = ParseImm(Operands);
1844 if (ResTy != MatchOperand_NoMatch)
1847 // Registers are a valid target and have priority over symbols.
1848 ResTy = ParseAnyRegister(Operands);
1849 if (ResTy != MatchOperand_NoMatch)
1852 const MCExpr *Expr = nullptr;
1853 if (Parser.parseExpression(Expr)) {
1854 // We have no way of knowing if a symbol was consumed so we must ParseFail
1855 return MatchOperand_ParseFail;
1858 MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
1859 return MatchOperand_Success;
1862 MipsAsmParser::OperandMatchResultTy
1863 MipsAsmParser::parseInvNum(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1864 const MCExpr *IdVal;
1865 // If the first token is '$' we may have register operand.
1866 if (Parser.getTok().is(AsmToken::Dollar))
1867 return MatchOperand_NoMatch;
1868 SMLoc S = Parser.getTok().getLoc();
1869 if (getParser().parseExpression(IdVal))
1870 return MatchOperand_ParseFail;
1871 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
1872 assert(MCE && "Unexpected MCExpr type.");
1873 int64_t Val = MCE->getValue();
1874 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1875 Operands.push_back(MipsOperand::CreateImm(
1876 MCConstantExpr::Create(0 - Val, getContext()), S, E, *this));
1877 return MatchOperand_Success;
1880 MipsAsmParser::OperandMatchResultTy
1881 MipsAsmParser::ParseLSAImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1882 switch (getLexer().getKind()) {
1884 return MatchOperand_NoMatch;
1885 case AsmToken::LParen:
1886 case AsmToken::Plus:
1887 case AsmToken::Minus:
1888 case AsmToken::Integer:
1893 SMLoc S = Parser.getTok().getLoc();
1895 if (getParser().parseExpression(Expr))
1896 return MatchOperand_ParseFail;
1899 if (!Expr->EvaluateAsAbsolute(Val)) {
1900 Error(S, "expected immediate value");
1901 return MatchOperand_ParseFail;
1904 // The LSA instruction allows a 2-bit unsigned immediate. For this reason
1905 // and because the CPU always adds one to the immediate field, the allowed
1906 // range becomes 1..4. We'll only check the range here and will deal
1907 // with the addition/subtraction when actually decoding/encoding
1909 if (Val < 1 || Val > 4) {
1910 Error(S, "immediate not in range (1..4)");
1911 return MatchOperand_ParseFail;
1915 MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
1916 return MatchOperand_Success;
1919 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
1921 MCSymbolRefExpr::VariantKind VK =
1922 StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
1923 .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
1924 .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
1925 .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
1926 .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
1927 .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
1928 .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
1929 .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
1930 .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
1931 .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
1932 .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
1933 .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
1934 .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
1935 .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
1936 .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
1937 .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
1938 .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
1939 .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
1940 .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
1941 .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
1942 .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
1943 .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
1944 .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
1945 .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
1946 .Default(MCSymbolRefExpr::VK_None);
1948 assert (VK != MCSymbolRefExpr::VK_None);
1953 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
1955 /// ::= '(', register, ')'
1956 /// handle it before we iterate so we don't get tripped up by the lack of
1958 bool MipsAsmParser::ParseParenSuffix(
1959 StringRef Name, SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1960 if (getLexer().is(AsmToken::LParen)) {
1962 MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
1964 if (ParseOperand(Operands, Name)) {
1965 SMLoc Loc = getLexer().getLoc();
1966 Parser.eatToEndOfStatement();
1967 return Error(Loc, "unexpected token in argument list");
1969 if (Parser.getTok().isNot(AsmToken::RParen)) {
1970 SMLoc Loc = getLexer().getLoc();
1971 Parser.eatToEndOfStatement();
1972 return Error(Loc, "unexpected token, expected ')'");
1975 MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
1981 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
1982 /// either one of these.
1983 /// ::= '[', register, ']'
1984 /// ::= '[', integer, ']'
1985 /// handle it before we iterate so we don't get tripped up by the lack of
1987 bool MipsAsmParser::ParseBracketSuffix(
1988 StringRef Name, SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1989 if (getLexer().is(AsmToken::LBrac)) {
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::RBrac)) {
1999 SMLoc Loc = getLexer().getLoc();
2000 Parser.eatToEndOfStatement();
2001 return Error(Loc, "unexpected token, expected ']'");
2004 MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
2010 bool MipsAsmParser::ParseInstruction(
2011 ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
2012 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2013 DEBUG(dbgs() << "ParseInstruction\n");
2014 // Check if we have valid mnemonic
2015 if (!mnemonicIsValid(Name, 0)) {
2016 Parser.eatToEndOfStatement();
2017 return Error(NameLoc, "Unknown instruction");
2019 // First operand in MCInst is instruction mnemonic.
2020 Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
2022 // Read the remaining operands.
2023 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2024 // Read the first operand.
2025 if (ParseOperand(Operands, Name)) {
2026 SMLoc Loc = getLexer().getLoc();
2027 Parser.eatToEndOfStatement();
2028 return Error(Loc, "unexpected token in argument list");
2030 if (getLexer().is(AsmToken::LBrac) && ParseBracketSuffix(Name, Operands))
2032 // AFAIK, parenthesis suffixes are never on the first operand
2034 while (getLexer().is(AsmToken::Comma)) {
2035 Parser.Lex(); // Eat the comma.
2036 // Parse and remember the operand.
2037 if (ParseOperand(Operands, Name)) {
2038 SMLoc Loc = getLexer().getLoc();
2039 Parser.eatToEndOfStatement();
2040 return Error(Loc, "unexpected token in argument list");
2042 // Parse bracket and parenthesis suffixes before we iterate
2043 if (getLexer().is(AsmToken::LBrac)) {
2044 if (ParseBracketSuffix(Name, Operands))
2046 } else if (getLexer().is(AsmToken::LParen) &&
2047 ParseParenSuffix(Name, Operands))
2051 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2052 SMLoc Loc = getLexer().getLoc();
2053 Parser.eatToEndOfStatement();
2054 return Error(Loc, "unexpected token in argument list");
2056 Parser.Lex(); // Consume the EndOfStatement.
2060 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2061 SMLoc Loc = getLexer().getLoc();
2062 Parser.eatToEndOfStatement();
2063 return Error(Loc, ErrorMsg);
2066 bool MipsAsmParser::parseSetNoAtDirective() {
2067 // Line should look like: ".set noat".
2069 Options.setATReg(0);
2072 // If this is not the end of the statement, report an error.
2073 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2074 reportParseError("unexpected token in statement");
2077 Parser.Lex(); // Consume the EndOfStatement.
2081 bool MipsAsmParser::parseSetAtDirective() {
2082 // Line can be .set at - defaults to $1
2086 if (getLexer().is(AsmToken::EndOfStatement)) {
2087 Options.setATReg(1);
2088 Parser.Lex(); // Consume the EndOfStatement.
2090 } else if (getLexer().is(AsmToken::Equal)) {
2091 getParser().Lex(); // Eat the '='.
2092 if (getLexer().isNot(AsmToken::Dollar)) {
2093 reportParseError("unexpected token in statement");
2096 Parser.Lex(); // Eat the '$'.
2097 const AsmToken &Reg = Parser.getTok();
2098 if (Reg.is(AsmToken::Identifier)) {
2099 AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2100 } else if (Reg.is(AsmToken::Integer)) {
2101 AtRegNo = Reg.getIntVal();
2103 reportParseError("unexpected token in statement");
2107 if (AtRegNo < 0 || AtRegNo > 31) {
2108 reportParseError("unexpected token in statement");
2112 if (!Options.setATReg(AtRegNo)) {
2113 reportParseError("unexpected token in statement");
2116 getParser().Lex(); // Eat the register.
2118 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2119 reportParseError("unexpected token in statement");
2122 Parser.Lex(); // Consume the EndOfStatement.
2125 reportParseError("unexpected token in statement");
2130 bool MipsAsmParser::parseSetReorderDirective() {
2132 // If this is not the end of the statement, report an error.
2133 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2134 reportParseError("unexpected token in statement");
2137 Options.setReorder();
2138 getTargetStreamer().emitDirectiveSetReorder();
2139 Parser.Lex(); // Consume the EndOfStatement.
2143 bool MipsAsmParser::parseSetNoReorderDirective() {
2145 // If this is not the end of the statement, report an error.
2146 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2147 reportParseError("unexpected token in statement");
2150 Options.setNoreorder();
2151 getTargetStreamer().emitDirectiveSetNoReorder();
2152 Parser.Lex(); // Consume the EndOfStatement.
2156 bool MipsAsmParser::parseSetMacroDirective() {
2158 // If this is not the end of the statement, report an error.
2159 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2160 reportParseError("unexpected token in statement");
2164 Parser.Lex(); // Consume the EndOfStatement.
2168 bool MipsAsmParser::parseSetNoMacroDirective() {
2170 // If this is not the end of the statement, report an error.
2171 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2172 reportParseError("`noreorder' must be set before `nomacro'");
2175 if (Options.isReorder()) {
2176 reportParseError("`noreorder' must be set before `nomacro'");
2179 Options.setNomacro();
2180 Parser.Lex(); // Consume the EndOfStatement.
2184 bool MipsAsmParser::parseSetNoMips16Directive() {
2186 // If this is not the end of the statement, report an error.
2187 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2188 reportParseError("unexpected token in statement");
2191 // For now do nothing.
2192 Parser.Lex(); // Consume the EndOfStatement.
2196 bool MipsAsmParser::parseSetAssignment() {
2198 const MCExpr *Value;
2200 if (Parser.parseIdentifier(Name))
2201 reportParseError("expected identifier after .set");
2203 if (getLexer().isNot(AsmToken::Comma))
2204 return reportParseError("unexpected token in .set directive");
2207 if (Parser.parseExpression(Value))
2208 return reportParseError("expected valid expression after comma");
2210 // Check if the Name already exists as a symbol.
2211 MCSymbol *Sym = getContext().LookupSymbol(Name);
2213 return reportParseError("symbol already defined");
2214 Sym = getContext().GetOrCreateSymbol(Name);
2215 Sym->setVariableValue(Value);
2220 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2222 if (getLexer().isNot(AsmToken::EndOfStatement))
2223 return reportParseError("unexpected token in .set directive");
2226 default: llvm_unreachable("Unimplemented feature");
2227 case Mips::FeatureDSP:
2228 setFeatureBits(Mips::FeatureDSP, "dsp");
2229 getTargetStreamer().emitDirectiveSetDsp();
2231 case Mips::FeatureMicroMips:
2232 getTargetStreamer().emitDirectiveSetMicroMips();
2234 case Mips::FeatureMips16:
2235 getTargetStreamer().emitDirectiveSetMips16();
2237 case Mips::FeatureMips32r2:
2238 setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2239 getTargetStreamer().emitDirectiveSetMips32R2();
2241 case Mips::FeatureMips64:
2242 setFeatureBits(Mips::FeatureMips64, "mips64");
2243 getTargetStreamer().emitDirectiveSetMips64();
2245 case Mips::FeatureMips64r2:
2246 setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2247 getTargetStreamer().emitDirectiveSetMips64R2();
2253 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2254 if (!getLexer().is(AsmToken::Dollar))
2259 const AsmToken &Reg = Parser.getTok();
2260 if (Reg.is(AsmToken::Identifier)) {
2261 RegNum = matchCPURegisterName(Reg.getIdentifier());
2262 } else if (Reg.is(AsmToken::Integer)) {
2263 RegNum = Reg.getIntVal();
2272 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2273 if (getLexer().isNot(AsmToken::Comma)) {
2274 SMLoc Loc = getLexer().getLoc();
2275 Parser.eatToEndOfStatement();
2276 return Error(Loc, ErrorStr);
2279 Parser.Lex(); // Eat the comma.
2283 bool MipsAsmParser::parseDirectiveCPSetup() {
2286 bool SaveIsReg = true;
2288 if (!parseRegister(FuncReg))
2289 return reportParseError("expected register containing function address");
2290 FuncReg = getGPR(FuncReg);
2292 if (!eatComma("expected comma parsing directive"))
2295 if (!parseRegister(Save)) {
2296 const AsmToken &Tok = Parser.getTok();
2297 if (Tok.is(AsmToken::Integer)) {
2298 Save = Tok.getIntVal();
2302 return reportParseError("expected save register or stack offset");
2304 Save = getGPR(Save);
2306 if (!eatComma("expected comma parsing directive"))
2310 if (Parser.parseIdentifier(Name))
2311 reportParseError("expected identifier");
2312 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2313 unsigned GPReg = getGPR(matchCPURegisterName("gp"));
2315 // FIXME: The code below this point should be in the TargetStreamers.
2316 // Only N32 and N64 emit anything for .cpsetup
2317 // FIXME: We should only emit something for PIC mode too.
2318 if (!isN32() && !isN64())
2321 MCStreamer &TS = getStreamer();
2323 // Either store the old $gp in a register or on the stack
2325 // move $save, $gpreg
2326 Inst.setOpcode(Mips::DADDu);
2327 Inst.addOperand(MCOperand::CreateReg(Save));
2328 Inst.addOperand(MCOperand::CreateReg(GPReg));
2329 Inst.addOperand(MCOperand::CreateReg(getGPR(0)));
2331 // sd $gpreg, offset($sp)
2332 Inst.setOpcode(Mips::SD);
2333 Inst.addOperand(MCOperand::CreateReg(GPReg));
2334 Inst.addOperand(MCOperand::CreateReg(getGPR(matchCPURegisterName("sp"))));
2335 Inst.addOperand(MCOperand::CreateImm(Save));
2337 TS.EmitInstruction(Inst, STI);
2340 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
2341 Sym->getName(), MCSymbolRefExpr::VK_Mips_GPOFF_HI,
2343 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
2344 Sym->getName(), MCSymbolRefExpr::VK_Mips_GPOFF_LO,
2346 // lui $gp, %hi(%neg(%gp_rel(funcSym)))
2347 Inst.setOpcode(Mips::LUi);
2348 Inst.addOperand(MCOperand::CreateReg(GPReg));
2349 Inst.addOperand(MCOperand::CreateExpr(HiExpr));
2350 TS.EmitInstruction(Inst, STI);
2353 // addiu $gp, $gp, %lo(%neg(%gp_rel(funcSym)))
2354 Inst.setOpcode(Mips::ADDiu);
2355 Inst.addOperand(MCOperand::CreateReg(GPReg));
2356 Inst.addOperand(MCOperand::CreateReg(GPReg));
2357 Inst.addOperand(MCOperand::CreateExpr(LoExpr));
2358 TS.EmitInstruction(Inst, STI);
2361 // daddu $gp, $gp, $funcreg
2362 Inst.setOpcode(Mips::DADDu);
2363 Inst.addOperand(MCOperand::CreateReg(GPReg));
2364 Inst.addOperand(MCOperand::CreateReg(GPReg));
2365 Inst.addOperand(MCOperand::CreateReg(FuncReg));
2366 TS.EmitInstruction(Inst, STI);
2370 bool MipsAsmParser::parseDirectiveSet() {
2372 // Get the next token.
2373 const AsmToken &Tok = Parser.getTok();
2375 if (Tok.getString() == "noat") {
2376 return parseSetNoAtDirective();
2377 } else if (Tok.getString() == "at") {
2378 return parseSetAtDirective();
2379 } else if (Tok.getString() == "reorder") {
2380 return parseSetReorderDirective();
2381 } else if (Tok.getString() == "noreorder") {
2382 return parseSetNoReorderDirective();
2383 } else if (Tok.getString() == "macro") {
2384 return parseSetMacroDirective();
2385 } else if (Tok.getString() == "nomacro") {
2386 return parseSetNoMacroDirective();
2387 } else if (Tok.getString() == "mips16") {
2388 return parseSetFeature(Mips::FeatureMips16);
2389 } else if (Tok.getString() == "nomips16") {
2390 return parseSetNoMips16Directive();
2391 } else if (Tok.getString() == "nomicromips") {
2392 getTargetStreamer().emitDirectiveSetNoMicroMips();
2393 Parser.eatToEndOfStatement();
2395 } else if (Tok.getString() == "micromips") {
2396 return parseSetFeature(Mips::FeatureMicroMips);
2397 } else if (Tok.getString() == "mips32r2") {
2398 return parseSetFeature(Mips::FeatureMips32r2);
2399 } else if (Tok.getString() == "mips64") {
2400 return parseSetFeature(Mips::FeatureMips64);
2401 } else if (Tok.getString() == "mips64r2") {
2402 return parseSetFeature(Mips::FeatureMips64r2);
2403 } else if (Tok.getString() == "dsp") {
2404 return parseSetFeature(Mips::FeatureDSP);
2406 // It is just an identifier, look for an assignment.
2407 parseSetAssignment();
2414 /// parseDataDirective
2415 /// ::= .word [ expression (, expression)* ]
2416 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2419 const MCExpr *Value;
2420 if (getParser().parseExpression(Value))
2423 getParser().getStreamer().EmitValue(Value, Size);
2425 if (getLexer().is(AsmToken::EndOfStatement))
2428 // FIXME: Improve diagnostic.
2429 if (getLexer().isNot(AsmToken::Comma))
2430 return Error(L, "unexpected token in directive");
2439 /// parseDirectiveGpWord
2440 /// ::= .gpword local_sym
2441 bool MipsAsmParser::parseDirectiveGpWord() {
2442 const MCExpr *Value;
2443 // EmitGPRel32Value requires an expression, so we are using base class
2444 // method to evaluate the expression.
2445 if (getParser().parseExpression(Value))
2447 getParser().getStreamer().EmitGPRel32Value(Value);
2449 if (getLexer().isNot(AsmToken::EndOfStatement))
2450 return Error(getLexer().getLoc(), "unexpected token in directive");
2451 Parser.Lex(); // Eat EndOfStatement token.
2455 /// parseDirectiveGpDWord
2456 /// ::= .gpdword local_sym
2457 bool MipsAsmParser::parseDirectiveGpDWord() {
2458 const MCExpr *Value;
2459 // EmitGPRel64Value requires an expression, so we are using base class
2460 // method to evaluate the expression.
2461 if (getParser().parseExpression(Value))
2463 getParser().getStreamer().EmitGPRel64Value(Value);
2465 if (getLexer().isNot(AsmToken::EndOfStatement))
2466 return Error(getLexer().getLoc(), "unexpected token in directive");
2467 Parser.Lex(); // Eat EndOfStatement token.
2471 bool MipsAsmParser::parseDirectiveOption() {
2472 // Get the option token.
2473 AsmToken Tok = Parser.getTok();
2474 // At the moment only identifiers are supported.
2475 if (Tok.isNot(AsmToken::Identifier)) {
2476 Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2477 Parser.eatToEndOfStatement();
2481 StringRef Option = Tok.getIdentifier();
2483 if (Option == "pic0") {
2484 getTargetStreamer().emitDirectiveOptionPic0();
2486 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2487 Error(Parser.getTok().getLoc(),
2488 "unexpected token in .option pic0 directive");
2489 Parser.eatToEndOfStatement();
2494 if (Option == "pic2") {
2495 getTargetStreamer().emitDirectiveOptionPic2();
2497 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2498 Error(Parser.getTok().getLoc(),
2499 "unexpected token in .option pic2 directive");
2500 Parser.eatToEndOfStatement();
2506 Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2507 Parser.eatToEndOfStatement();
2511 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2512 StringRef IDVal = DirectiveID.getString();
2514 if (IDVal == ".dword") {
2515 parseDataDirective(8, DirectiveID.getLoc());
2519 if (IDVal == ".ent") {
2520 // Ignore this directive for now.
2525 if (IDVal == ".end") {
2526 // Ignore this directive for now.
2531 if (IDVal == ".frame") {
2532 // Ignore this directive for now.
2533 Parser.eatToEndOfStatement();
2537 if (IDVal == ".set") {
2538 return parseDirectiveSet();
2541 if (IDVal == ".fmask") {
2542 // Ignore this directive for now.
2543 Parser.eatToEndOfStatement();
2547 if (IDVal == ".mask") {
2548 // Ignore this directive for now.
2549 Parser.eatToEndOfStatement();
2553 if (IDVal == ".gpword") {
2554 parseDirectiveGpWord();
2558 if (IDVal == ".gpdword") {
2559 parseDirectiveGpDWord();
2563 if (IDVal == ".word") {
2564 parseDataDirective(4, DirectiveID.getLoc());
2568 if (IDVal == ".option")
2569 return parseDirectiveOption();
2571 if (IDVal == ".abicalls") {
2572 getTargetStreamer().emitDirectiveAbiCalls();
2573 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2574 Error(Parser.getTok().getLoc(), "unexpected token in directive");
2576 Parser.eatToEndOfStatement();
2581 if (IDVal == ".cpsetup")
2582 return parseDirectiveCPSetup();
2587 extern "C" void LLVMInitializeMipsAsmParser() {
2588 RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2589 RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2590 RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2591 RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2594 #define GET_REGISTER_MATCHER
2595 #define GET_MATCHER_IMPLEMENTATION
2596 #include "MipsGenAsmMatcher.inc"