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 parseDirectiveNaN();
148 bool parseDirectiveSet();
149 bool parseDirectiveOption();
151 bool parseSetAtDirective();
152 bool parseSetNoAtDirective();
153 bool parseSetMacroDirective();
154 bool parseSetNoMacroDirective();
155 bool parseSetReorderDirective();
156 bool parseSetNoReorderDirective();
157 bool parseSetNoMips16Directive();
159 bool parseSetAssignment();
161 bool parseDataDirective(unsigned Size, SMLoc L);
162 bool parseDirectiveGpWord();
163 bool parseDirectiveGpDWord();
165 MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
167 bool isGP64() const {
168 return (STI.getFeatureBits() & Mips::FeatureGP64Bit) != 0;
171 bool isFP64() const {
172 return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
175 bool isN32() const { return STI.getFeatureBits() & Mips::FeatureN32; }
176 bool isN64() const { return STI.getFeatureBits() & Mips::FeatureN64; }
178 bool isMicroMips() const {
179 return STI.getFeatureBits() & Mips::FeatureMicroMips;
182 bool parseRegister(unsigned &RegNum);
184 bool eatComma(StringRef ErrorStr);
186 int matchCPURegisterName(StringRef Symbol);
188 int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
190 int matchFPURegisterName(StringRef Name);
192 int matchFCCRegisterName(StringRef Name);
194 int matchACRegisterName(StringRef Name);
196 int matchMSA128RegisterName(StringRef Name);
198 int matchMSA128CtrlRegisterName(StringRef Name);
200 unsigned getReg(int RC, int RegNo);
202 unsigned getGPR(int RegNo);
206 bool processInstruction(MCInst &Inst, SMLoc IDLoc,
207 SmallVectorImpl<MCInst> &Instructions);
209 // Helper function that checks if the value of a vector index is within the
210 // boundaries of accepted values for each RegisterKind
211 // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
212 bool validateMSAIndex(int Val, int RegKind);
214 void setFeatureBits(unsigned Feature, StringRef FeatureString) {
215 if (!(STI.getFeatureBits() & Feature)) {
216 setAvailableFeatures(ComputeAvailableFeatures(
217 STI.ToggleFeature(FeatureString)));
221 void clearFeatureBits(unsigned Feature, StringRef FeatureString) {
222 if (STI.getFeatureBits() & Feature) {
223 setAvailableFeatures(ComputeAvailableFeatures(
224 STI.ToggleFeature(FeatureString)));
229 MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
230 const MCInstrInfo &MII)
231 : MCTargetAsmParser(), STI(sti), Parser(parser) {
232 // Initialize the set of available features.
233 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
235 // Assert exactly one ABI was chosen.
236 assert((((STI.getFeatureBits() & Mips::FeatureO32) != 0) +
237 ((STI.getFeatureBits() & Mips::FeatureEABI) != 0) +
238 ((STI.getFeatureBits() & Mips::FeatureN32) != 0) +
239 ((STI.getFeatureBits() & Mips::FeatureN64) != 0)) == 1);
242 MCAsmParser &getParser() const { return Parser; }
243 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
245 /// Warn if RegNo is the current assembler temporary.
246 void WarnIfAssemblerTemporary(int RegNo, SMLoc Loc);
252 /// MipsOperand - Instances of this class represent a parsed Mips machine
254 class MipsOperand : public MCParsedAsmOperand {
256 /// Broad categories of register classes
257 /// The exact class is finalized by the render method.
259 RegKind_GPR = 1, /// GPR32 and GPR64 (depending on isGP64())
260 RegKind_FGR = 2, /// FGR32, FGR64, AFGR64 (depending on context and
262 RegKind_FCC = 4, /// FCC
263 RegKind_MSA128 = 8, /// MSA128[BHWD] (makes no difference which)
264 RegKind_MSACtrl = 16, /// MSA control registers
265 RegKind_COP2 = 32, /// COP2
266 RegKind_ACC = 64, /// HI32DSP, LO32DSP, and ACC64DSP (depending on
268 RegKind_CCR = 128, /// CCR
269 RegKind_HWRegs = 256, /// HWRegs
271 /// Potentially any (e.g. $1)
272 RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
273 RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
274 RegKind_CCR | RegKind_HWRegs
279 k_Immediate, /// An immediate (possibly involving symbol references)
280 k_Memory, /// Base + Offset Memory Address
281 k_PhysRegister, /// A physical register from the Mips namespace
282 k_RegisterIndex, /// A register index in one or more RegKind.
283 k_Token /// A simple token
286 MipsOperand(KindTy K, MipsAsmParser &Parser)
287 : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
289 /// For diagnostics, and checking the assembler temporary
290 MipsAsmParser &AsmParser;
298 unsigned Num; /// Register Number
302 unsigned Index; /// Index into the register class
303 RegKind Kind; /// Bitfield of the kinds it could possibly be
304 const MCRegisterInfo *RegInfo;
318 struct PhysRegOp PhysReg;
319 struct RegIdxOp RegIdx;
324 SMLoc StartLoc, EndLoc;
326 /// Internal constructor for register kinds
327 static MipsOperand *CreateReg(unsigned Index, RegKind RegKind,
328 const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
329 MipsAsmParser &Parser) {
330 MipsOperand *Op = new MipsOperand(k_RegisterIndex, Parser);
331 Op->RegIdx.Index = Index;
332 Op->RegIdx.RegInfo = RegInfo;
333 Op->RegIdx.Kind = RegKind;
340 /// Coerce the register to GPR32 and return the real register for the current
342 unsigned getGPR32Reg() const {
343 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
344 AsmParser.WarnIfAssemblerTemporary(RegIdx.Index, StartLoc);
345 unsigned ClassID = Mips::GPR32RegClassID;
346 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
349 /// Coerce the register to GPR64 and return the real register for the current
351 unsigned getGPR64Reg() const {
352 assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
353 unsigned ClassID = Mips::GPR64RegClassID;
354 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
358 /// Coerce the register to AFGR64 and return the real register for the current
360 unsigned getAFGR64Reg() const {
361 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
362 if (RegIdx.Index % 2 != 0)
363 AsmParser.Warning(StartLoc, "Float register should be even.");
364 return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
365 .getRegister(RegIdx.Index / 2);
368 /// Coerce the register to FGR64 and return the real register for the current
370 unsigned getFGR64Reg() const {
371 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
372 return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
373 .getRegister(RegIdx.Index);
376 /// Coerce the register to FGR32 and return the real register for the current
378 unsigned getFGR32Reg() const {
379 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
380 return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
381 .getRegister(RegIdx.Index);
384 /// Coerce the register to FGRH32 and return the real register for the current
386 unsigned getFGRH32Reg() const {
387 assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
388 return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
389 .getRegister(RegIdx.Index);
392 /// Coerce the register to FCC and return the real register for the current
394 unsigned getFCCReg() const {
395 assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
396 return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
397 .getRegister(RegIdx.Index);
400 /// Coerce the register to MSA128 and return the real register for the current
402 unsigned getMSA128Reg() const {
403 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
404 // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
406 unsigned ClassID = Mips::MSA128BRegClassID;
407 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
410 /// Coerce the register to MSACtrl and return the real register for the
412 unsigned getMSACtrlReg() const {
413 assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
414 unsigned ClassID = Mips::MSACtrlRegClassID;
415 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
418 /// Coerce the register to COP2 and return the real register for the
420 unsigned getCOP2Reg() const {
421 assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
422 unsigned ClassID = Mips::COP2RegClassID;
423 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
426 /// Coerce the register to ACC64DSP and return the real register for the
428 unsigned getACC64DSPReg() const {
429 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
430 unsigned ClassID = Mips::ACC64DSPRegClassID;
431 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
434 /// Coerce the register to HI32DSP and return the real register for the
436 unsigned getHI32DSPReg() const {
437 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
438 unsigned ClassID = Mips::HI32DSPRegClassID;
439 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
442 /// Coerce the register to LO32DSP and return the real register for the
444 unsigned getLO32DSPReg() const {
445 assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
446 unsigned ClassID = Mips::LO32DSPRegClassID;
447 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
450 /// Coerce the register to CCR and return the real register for the
452 unsigned getCCRReg() const {
453 assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
454 unsigned ClassID = Mips::CCRRegClassID;
455 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
458 /// Coerce the register to HWRegs and return the real register for the
460 unsigned getHWRegsReg() const {
461 assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
462 unsigned ClassID = Mips::HWRegsRegClassID;
463 return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
467 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
468 // Add as immediate when possible. Null MCExpr = 0.
470 Inst.addOperand(MCOperand::CreateImm(0));
471 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
472 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
474 Inst.addOperand(MCOperand::CreateExpr(Expr));
477 void addRegOperands(MCInst &Inst, unsigned N) const {
478 llvm_unreachable("Use a custom parser instead");
481 /// Render the operand to an MCInst as a GPR32
482 /// Asserts if the wrong number of operands are requested, or the operand
483 /// is not a k_RegisterIndex compatible with RegKind_GPR
484 void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
485 assert(N == 1 && "Invalid number of operands!");
486 Inst.addOperand(MCOperand::CreateReg(getGPR32Reg()));
489 /// Render the operand to an MCInst as a GPR64
490 /// Asserts if the wrong number of operands are requested, or the operand
491 /// is not a k_RegisterIndex compatible with RegKind_GPR
492 void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
493 assert(N == 1 && "Invalid number of operands!");
494 Inst.addOperand(MCOperand::CreateReg(getGPR64Reg()));
497 void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
498 assert(N == 1 && "Invalid number of operands!");
499 Inst.addOperand(MCOperand::CreateReg(getAFGR64Reg()));
502 void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
503 assert(N == 1 && "Invalid number of operands!");
504 Inst.addOperand(MCOperand::CreateReg(getFGR64Reg()));
507 void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
508 assert(N == 1 && "Invalid number of operands!");
509 Inst.addOperand(MCOperand::CreateReg(getFGR32Reg()));
512 void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
513 assert(N == 1 && "Invalid number of operands!");
514 Inst.addOperand(MCOperand::CreateReg(getFGRH32Reg()));
517 void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
518 assert(N == 1 && "Invalid number of operands!");
519 Inst.addOperand(MCOperand::CreateReg(getFCCReg()));
522 void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
523 assert(N == 1 && "Invalid number of operands!");
524 Inst.addOperand(MCOperand::CreateReg(getMSA128Reg()));
527 void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
528 assert(N == 1 && "Invalid number of operands!");
529 Inst.addOperand(MCOperand::CreateReg(getMSACtrlReg()));
532 void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
533 assert(N == 1 && "Invalid number of operands!");
534 Inst.addOperand(MCOperand::CreateReg(getCOP2Reg()));
537 void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
538 assert(N == 1 && "Invalid number of operands!");
539 Inst.addOperand(MCOperand::CreateReg(getACC64DSPReg()));
542 void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
543 assert(N == 1 && "Invalid number of operands!");
544 Inst.addOperand(MCOperand::CreateReg(getHI32DSPReg()));
547 void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
548 assert(N == 1 && "Invalid number of operands!");
549 Inst.addOperand(MCOperand::CreateReg(getLO32DSPReg()));
552 void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
553 assert(N == 1 && "Invalid number of operands!");
554 Inst.addOperand(MCOperand::CreateReg(getCCRReg()));
557 void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
558 assert(N == 1 && "Invalid number of operands!");
559 Inst.addOperand(MCOperand::CreateReg(getHWRegsReg()));
562 void addImmOperands(MCInst &Inst, unsigned N) const {
563 assert(N == 1 && "Invalid number of operands!");
564 const MCExpr *Expr = getImm();
568 void addMemOperands(MCInst &Inst, unsigned N) const {
569 assert(N == 2 && "Invalid number of operands!");
571 Inst.addOperand(MCOperand::CreateReg(getMemBase()->getGPR32Reg()));
573 const MCExpr *Expr = getMemOff();
578 // As a special case until we sort out the definition of div/divu, pretend
579 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
580 if (isGPRAsmReg() && RegIdx.Index == 0)
583 return Kind == k_PhysRegister;
585 bool isRegIdx() const { return Kind == k_RegisterIndex; }
586 bool isImm() const { return Kind == k_Immediate; }
587 bool isConstantImm() const {
588 return isImm() && dyn_cast<MCConstantExpr>(getImm());
590 bool isToken() const {
591 // Note: It's not possible to pretend that other operand kinds are tokens.
592 // The matcher emitter checks tokens first.
593 return Kind == k_Token;
595 bool isMem() const { return Kind == k_Memory; }
596 bool isInvNum() const { return Kind == k_Immediate; }
597 bool isLSAImm() const {
598 if (!isConstantImm())
600 int64_t Val = getConstantImm();
601 return 1 <= Val && Val <= 4;
604 StringRef getToken() const {
605 assert(Kind == k_Token && "Invalid access!");
606 return StringRef(Tok.Data, Tok.Length);
609 unsigned getReg() const {
610 // As a special case until we sort out the definition of div/divu, pretend
611 // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
612 if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
613 RegIdx.Kind & RegKind_GPR)
614 return getGPR32Reg(); // FIXME: GPR64 too
616 assert(Kind == k_PhysRegister && "Invalid access!");
620 const MCExpr *getImm() const {
621 assert((Kind == k_Immediate) && "Invalid access!");
625 int64_t getConstantImm() const {
626 const MCExpr *Val = getImm();
627 return static_cast<const MCConstantExpr *>(Val)->getValue();
630 MipsOperand *getMemBase() const {
631 assert((Kind == k_Memory) && "Invalid access!");
635 const MCExpr *getMemOff() const {
636 assert((Kind == k_Memory) && "Invalid access!");
640 static MipsOperand *CreateToken(StringRef Str, SMLoc S,
641 MipsAsmParser &Parser) {
642 MipsOperand *Op = new MipsOperand(k_Token, Parser);
643 Op->Tok.Data = Str.data();
644 Op->Tok.Length = Str.size();
650 /// Create a numeric register (e.g. $1). The exact register remains
651 /// unresolved until an instruction successfully matches
652 static MipsOperand *CreateNumericReg(unsigned Index,
653 const MCRegisterInfo *RegInfo, SMLoc S,
654 SMLoc E, MipsAsmParser &Parser) {
655 DEBUG(dbgs() << "CreateNumericReg(" << Index << ", ...)\n");
656 return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
659 /// Create a register that is definitely a GPR.
660 /// This is typically only used for named registers such as $gp.
661 static MipsOperand *CreateGPRReg(unsigned Index,
662 const MCRegisterInfo *RegInfo, SMLoc S,
663 SMLoc E, MipsAsmParser &Parser) {
664 return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
667 /// Create a register that is definitely a FGR.
668 /// This is typically only used for named registers such as $f0.
669 static MipsOperand *CreateFGRReg(unsigned Index,
670 const MCRegisterInfo *RegInfo, SMLoc S,
671 SMLoc E, MipsAsmParser &Parser) {
672 return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
675 /// Create a register that is definitely an FCC.
676 /// This is typically only used for named registers such as $fcc0.
677 static MipsOperand *CreateFCCReg(unsigned Index,
678 const MCRegisterInfo *RegInfo, SMLoc S,
679 SMLoc E, MipsAsmParser &Parser) {
680 return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
683 /// Create a register that is definitely an ACC.
684 /// This is typically only used for named registers such as $ac0.
685 static MipsOperand *CreateACCReg(unsigned Index,
686 const MCRegisterInfo *RegInfo, SMLoc S,
687 SMLoc E, MipsAsmParser &Parser) {
688 return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
691 /// Create a register that is definitely an MSA128.
692 /// This is typically only used for named registers such as $w0.
693 static MipsOperand *CreateMSA128Reg(unsigned Index,
694 const MCRegisterInfo *RegInfo, SMLoc S,
695 SMLoc E, MipsAsmParser &Parser) {
696 return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
699 /// Create a register that is definitely an MSACtrl.
700 /// This is typically only used for named registers such as $msaaccess.
701 static MipsOperand *CreateMSACtrlReg(unsigned Index,
702 const MCRegisterInfo *RegInfo, SMLoc S,
703 SMLoc E, MipsAsmParser &Parser) {
704 return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
707 static MipsOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E,
708 MipsAsmParser &Parser) {
709 MipsOperand *Op = new MipsOperand(k_Immediate, Parser);
716 static MipsOperand *CreateMem(MipsOperand *Base, const MCExpr *Off, SMLoc S,
717 SMLoc E, MipsAsmParser &Parser) {
718 MipsOperand *Op = new MipsOperand(k_Memory, Parser);
726 bool isGPRAsmReg() const {
727 return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
729 bool isFGRAsmReg() const {
730 // AFGR64 is $0-$15 but we handle this in getAFGR64()
731 return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
733 bool isHWRegsAsmReg() const {
734 return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
736 bool isCCRAsmReg() const {
737 return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
739 bool isFCCAsmReg() const {
740 return isRegIdx() && RegIdx.Kind & RegKind_FCC && RegIdx.Index <= 7;
742 bool isACCAsmReg() const {
743 return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
745 bool isCOP2AsmReg() const {
746 return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
748 bool isMSA128AsmReg() const {
749 return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
751 bool isMSACtrlAsmReg() const {
752 return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
755 /// getStartLoc - Get the location of the first token of this operand.
756 SMLoc getStartLoc() const { return StartLoc; }
757 /// getEndLoc - Get the location of the last token of this operand.
758 SMLoc getEndLoc() const { return EndLoc; }
760 virtual ~MipsOperand() {
768 case k_RegisterIndex:
774 virtual void print(raw_ostream &OS) const {
789 OS << "PhysReg<" << PhysReg.Num << ">";
791 case k_RegisterIndex:
792 OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
799 }; // class MipsOperand
803 extern const MCInstrDesc MipsInsts[];
805 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
806 return MipsInsts[Opcode];
809 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
810 SmallVectorImpl<MCInst> &Instructions) {
811 const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
815 if (MCID.isBranch() || MCID.isCall()) {
816 const unsigned Opcode = Inst.getOpcode();
826 assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
827 Offset = Inst.getOperand(2);
829 break; // We'll deal with this situation later on when applying fixups.
830 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
831 return Error(IDLoc, "branch target out of range");
832 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
833 return Error(IDLoc, "branch to misaligned address");
847 case Mips::BGEZAL_MM:
848 case Mips::BLTZAL_MM:
851 assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
852 Offset = Inst.getOperand(1);
854 break; // We'll deal with this situation later on when applying fixups.
855 if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
856 return Error(IDLoc, "branch target out of range");
857 if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
858 return Error(IDLoc, "branch to misaligned address");
863 if (MCID.hasDelaySlot() && Options.isReorder()) {
864 // If this instruction has a delay slot and .set reorder is active,
865 // emit a NOP after it.
866 Instructions.push_back(Inst);
868 NopInst.setOpcode(Mips::SLL);
869 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
870 NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
871 NopInst.addOperand(MCOperand::CreateImm(0));
872 Instructions.push_back(NopInst);
876 if (MCID.mayLoad() || MCID.mayStore()) {
877 // Check the offset of memory operand, if it is a symbol
878 // reference or immediate we may have to expand instructions.
879 for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
880 const MCOperandInfo &OpInfo = MCID.OpInfo[i];
881 if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
882 (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
883 MCOperand &Op = Inst.getOperand(i);
885 int MemOffset = Op.getImm();
886 if (MemOffset < -32768 || MemOffset > 32767) {
887 // Offset can't exceed 16bit value.
888 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
891 } else if (Op.isExpr()) {
892 const MCExpr *Expr = Op.getExpr();
893 if (Expr->getKind() == MCExpr::SymbolRef) {
894 const MCSymbolRefExpr *SR =
895 static_cast<const MCSymbolRefExpr *>(Expr);
896 if (SR->getKind() == MCSymbolRefExpr::VK_None) {
898 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
901 } else if (!isEvaluated(Expr)) {
902 expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
910 if (needsExpansion(Inst))
911 expandInstruction(Inst, IDLoc, Instructions);
913 Instructions.push_back(Inst);
918 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
920 switch (Inst.getOpcode()) {
921 case Mips::LoadImm32Reg:
922 case Mips::LoadAddr32Imm:
923 case Mips::LoadAddr32Reg:
930 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
931 SmallVectorImpl<MCInst> &Instructions) {
932 switch (Inst.getOpcode()) {
933 case Mips::LoadImm32Reg:
934 return expandLoadImm(Inst, IDLoc, Instructions);
935 case Mips::LoadAddr32Imm:
936 return expandLoadAddressImm(Inst, IDLoc, Instructions);
937 case Mips::LoadAddr32Reg:
938 return expandLoadAddressReg(Inst, IDLoc, Instructions);
942 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
943 SmallVectorImpl<MCInst> &Instructions) {
945 const MCOperand &ImmOp = Inst.getOperand(1);
946 assert(ImmOp.isImm() && "expected immediate operand kind");
947 const MCOperand &RegOp = Inst.getOperand(0);
948 assert(RegOp.isReg() && "expected register operand kind");
950 int ImmValue = ImmOp.getImm();
951 tmpInst.setLoc(IDLoc);
952 if (0 <= ImmValue && ImmValue <= 65535) {
953 // For 0 <= j <= 65535.
954 // li d,j => ori d,$zero,j
955 tmpInst.setOpcode(Mips::ORi);
956 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
957 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
958 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
959 Instructions.push_back(tmpInst);
960 } else if (ImmValue < 0 && ImmValue >= -32768) {
961 // For -32768 <= j < 0.
962 // li d,j => addiu d,$zero,j
963 tmpInst.setOpcode(Mips::ADDiu);
964 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
965 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
966 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
967 Instructions.push_back(tmpInst);
969 // For any other value of j that is representable as a 32-bit integer.
970 // li d,j => lui d,hi16(j)
972 tmpInst.setOpcode(Mips::LUi);
973 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
974 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
975 Instructions.push_back(tmpInst);
977 tmpInst.setOpcode(Mips::ORi);
978 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
979 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
980 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
981 tmpInst.setLoc(IDLoc);
982 Instructions.push_back(tmpInst);
987 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
988 SmallVectorImpl<MCInst> &Instructions) {
990 const MCOperand &ImmOp = Inst.getOperand(2);
991 assert(ImmOp.isImm() && "expected immediate operand kind");
992 const MCOperand &SrcRegOp = Inst.getOperand(1);
993 assert(SrcRegOp.isReg() && "expected register operand kind");
994 const MCOperand &DstRegOp = Inst.getOperand(0);
995 assert(DstRegOp.isReg() && "expected register operand kind");
996 int ImmValue = ImmOp.getImm();
997 if (-32768 <= ImmValue && ImmValue <= 65535) {
998 // For -32768 <= j <= 65535.
999 // la d,j(s) => addiu d,s,j
1000 tmpInst.setOpcode(Mips::ADDiu);
1001 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1002 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1003 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1004 Instructions.push_back(tmpInst);
1006 // For any other value of j that is representable as a 32-bit integer.
1007 // la d,j(s) => lui d,hi16(j)
1010 tmpInst.setOpcode(Mips::LUi);
1011 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1012 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1013 Instructions.push_back(tmpInst);
1015 tmpInst.setOpcode(Mips::ORi);
1016 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1017 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1018 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1019 Instructions.push_back(tmpInst);
1021 tmpInst.setOpcode(Mips::ADDu);
1022 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1023 tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1024 tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1025 Instructions.push_back(tmpInst);
1030 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
1031 SmallVectorImpl<MCInst> &Instructions) {
1033 const MCOperand &ImmOp = Inst.getOperand(1);
1034 assert(ImmOp.isImm() && "expected immediate operand kind");
1035 const MCOperand &RegOp = Inst.getOperand(0);
1036 assert(RegOp.isReg() && "expected register operand kind");
1037 int ImmValue = ImmOp.getImm();
1038 if (-32768 <= ImmValue && ImmValue <= 65535) {
1039 // For -32768 <= j <= 65535.
1040 // la d,j => addiu d,$zero,j
1041 tmpInst.setOpcode(Mips::ADDiu);
1042 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1043 tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1044 tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1045 Instructions.push_back(tmpInst);
1047 // For any other value of j that is representable as a 32-bit integer.
1048 // la d,j => lui d,hi16(j)
1050 tmpInst.setOpcode(Mips::LUi);
1051 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1052 tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1053 Instructions.push_back(tmpInst);
1055 tmpInst.setOpcode(Mips::ORi);
1056 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1057 tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1058 tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1059 Instructions.push_back(tmpInst);
1063 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
1064 SmallVectorImpl<MCInst> &Instructions,
1065 bool isLoad, bool isImmOpnd) {
1066 const MCSymbolRefExpr *SR;
1068 unsigned ImmOffset, HiOffset, LoOffset;
1069 const MCExpr *ExprOffset;
1071 unsigned AtRegNum = getReg(
1072 (isGP64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
1073 // 1st operand is either the source or destination register.
1074 assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1075 unsigned RegOpNum = Inst.getOperand(0).getReg();
1076 // 2nd operand is the base register.
1077 assert(Inst.getOperand(1).isReg() && "expected register operand kind");
1078 unsigned BaseRegNum = Inst.getOperand(1).getReg();
1079 // 3rd operand is either an immediate or expression.
1081 assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
1082 ImmOffset = Inst.getOperand(2).getImm();
1083 LoOffset = ImmOffset & 0x0000ffff;
1084 HiOffset = (ImmOffset & 0xffff0000) >> 16;
1085 // If msb of LoOffset is 1(negative number) we must increment HiOffset.
1086 if (LoOffset & 0x8000)
1089 ExprOffset = Inst.getOperand(2).getExpr();
1090 // All instructions will have the same location.
1091 TempInst.setLoc(IDLoc);
1092 // 1st instruction in expansion is LUi. For load instruction we can use
1093 // the dst register as a temporary if base and dst are different,
1094 // but for stores we must use $at.
1095 TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
1096 TempInst.setOpcode(Mips::LUi);
1097 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1099 TempInst.addOperand(MCOperand::CreateImm(HiOffset));
1101 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1102 SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
1103 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
1104 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
1106 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1108 const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
1109 TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1112 // Add the instruction to the list.
1113 Instructions.push_back(TempInst);
1114 // Prepare TempInst for next instruction.
1116 // Add temp register to base.
1117 TempInst.setOpcode(Mips::ADDu);
1118 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1119 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1120 TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
1121 Instructions.push_back(TempInst);
1123 // And finally, create original instruction with low part
1124 // of offset and new base.
1125 TempInst.setOpcode(Inst.getOpcode());
1126 TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
1127 TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1129 TempInst.addOperand(MCOperand::CreateImm(LoOffset));
1131 if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1132 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
1133 SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
1135 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1137 const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
1138 TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1141 Instructions.push_back(TempInst);
1145 bool MipsAsmParser::MatchAndEmitInstruction(
1146 SMLoc IDLoc, unsigned &Opcode,
1147 SmallVectorImpl<MCParsedAsmOperand *> &Operands, MCStreamer &Out,
1148 unsigned &ErrorInfo, bool MatchingInlineAsm) {
1150 SmallVector<MCInst, 8> Instructions;
1151 unsigned MatchResult =
1152 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
1154 switch (MatchResult) {
1157 case Match_Success: {
1158 if (processInstruction(Inst, IDLoc, Instructions))
1160 for (unsigned i = 0; i < Instructions.size(); i++)
1161 Out.EmitInstruction(Instructions[i], STI);
1164 case Match_MissingFeature:
1165 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1167 case Match_InvalidOperand: {
1168 SMLoc ErrorLoc = IDLoc;
1169 if (ErrorInfo != ~0U) {
1170 if (ErrorInfo >= Operands.size())
1171 return Error(IDLoc, "too few operands for instruction");
1173 ErrorLoc = ((MipsOperand *)Operands[ErrorInfo])->getStartLoc();
1174 if (ErrorLoc == SMLoc())
1178 return Error(ErrorLoc, "invalid operand for instruction");
1180 case Match_MnemonicFail:
1181 return Error(IDLoc, "invalid instruction");
1186 void MipsAsmParser::WarnIfAssemblerTemporary(int RegIndex, SMLoc Loc) {
1187 if ((RegIndex != 0) && ((int)Options.getATRegNum() == RegIndex)) {
1189 Warning(Loc, "Used $at without \".set noat\"");
1191 Warning(Loc, Twine("Used $") + Twine(RegIndex) + " with \".set at=$" +
1192 Twine(RegIndex) + "\"");
1196 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
1199 CC = StringSwitch<unsigned>(Name)
1235 if (isN32() || isN64()) {
1236 // Although SGI documentation just cuts out t0-t3 for n32/n64,
1237 // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
1238 // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
1239 if (8 <= CC && CC <= 11)
1243 CC = StringSwitch<unsigned>(Name)
1256 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
1258 if (Name[0] == 'f') {
1259 StringRef NumString = Name.substr(1);
1261 if (NumString.getAsInteger(10, IntVal))
1262 return -1; // This is not an integer.
1263 if (IntVal > 31) // Maximum index for fpu register.
1270 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1272 if (Name.startswith("fcc")) {
1273 StringRef NumString = Name.substr(3);
1275 if (NumString.getAsInteger(10, IntVal))
1276 return -1; // This is not an integer.
1277 if (IntVal > 7) // There are only 8 fcc registers.
1284 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1286 if (Name.startswith("ac")) {
1287 StringRef NumString = Name.substr(2);
1289 if (NumString.getAsInteger(10, IntVal))
1290 return -1; // This is not an integer.
1291 if (IntVal > 3) // There are only 3 acc registers.
1298 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1301 if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1310 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1313 CC = StringSwitch<unsigned>(Name)
1316 .Case("msaaccess", 2)
1318 .Case("msamodify", 4)
1319 .Case("msarequest", 5)
1321 .Case("msaunmap", 7)
1327 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1335 int MipsAsmParser::getATReg() {
1336 int AT = Options.getATRegNum();
1338 TokError("Pseudo instruction requires $at, which is not available");
1342 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1343 return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1346 unsigned MipsAsmParser::getGPR(int RegNo) {
1347 return getReg(isGP64() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1351 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1353 getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1356 return getReg(RegClass, RegNum);
1360 MipsAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1361 StringRef Mnemonic) {
1362 DEBUG(dbgs() << "ParseOperand\n");
1364 // Check if the current operand has a custom associated parser, if so, try to
1365 // custom parse the operand, or fallback to the general approach.
1366 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1367 if (ResTy == MatchOperand_Success)
1369 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1370 // there was a match, but an error occurred, in which case, just return that
1371 // the operand parsing failed.
1372 if (ResTy == MatchOperand_ParseFail)
1375 DEBUG(dbgs() << ".. Generic Parser\n");
1377 switch (getLexer().getKind()) {
1379 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1381 case AsmToken::Dollar: {
1382 // Parse the register.
1383 SMLoc S = Parser.getTok().getLoc();
1385 // Almost all registers have been parsed by custom parsers. There is only
1386 // one exception to this. $zero (and it's alias $0) will reach this point
1387 // for div, divu, and similar instructions because it is not an operand
1388 // to the instruction definition but an explicit register. Special case
1389 // this situation for now.
1390 if (ParseAnyRegister(Operands) != MatchOperand_NoMatch)
1393 // Maybe it is a symbol reference.
1394 StringRef Identifier;
1395 if (Parser.parseIdentifier(Identifier))
1398 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1399 MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1400 // Otherwise create a symbol reference.
1402 MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1404 Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
1407 // Else drop to expression parsing.
1408 case AsmToken::LParen:
1409 case AsmToken::Minus:
1410 case AsmToken::Plus:
1411 case AsmToken::Integer:
1412 case AsmToken::String: {
1413 DEBUG(dbgs() << ".. generic integer\n");
1414 OperandMatchResultTy ResTy = ParseImm(Operands);
1415 return ResTy != MatchOperand_Success;
1417 case AsmToken::Percent: {
1418 // It is a symbol reference or constant expression.
1419 const MCExpr *IdVal;
1420 SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1421 if (parseRelocOperand(IdVal))
1424 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1426 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1428 } // case AsmToken::Percent
1429 } // switch(getLexer().getKind())
1433 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1434 StringRef RelocStr) {
1436 // Check the type of the expression.
1437 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1438 // It's a constant, evaluate reloc value.
1440 switch (getVariantKind(RelocStr)) {
1441 case MCSymbolRefExpr::VK_Mips_ABS_LO:
1442 // Get the 1st 16-bits.
1443 Val = MCE->getValue() & 0xffff;
1445 case MCSymbolRefExpr::VK_Mips_ABS_HI:
1446 // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
1447 // 16 bits being negative.
1448 Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
1450 case MCSymbolRefExpr::VK_Mips_HIGHER:
1451 // Get the 3rd 16-bits.
1452 Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
1454 case MCSymbolRefExpr::VK_Mips_HIGHEST:
1455 // Get the 4th 16-bits.
1456 Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
1459 report_fatal_error("Unsupported reloc value!");
1461 return MCConstantExpr::Create(Val, getContext());
1464 if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1465 // It's a symbol, create a symbolic expression from the symbol.
1466 StringRef Symbol = MSRE->getSymbol().getName();
1467 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1468 Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1472 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1473 MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1475 // Try to create target expression.
1476 if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
1477 return MipsMCExpr::Create(VK, Expr, getContext());
1479 const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1480 const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1481 Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1485 if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1486 const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1487 Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1490 // Just return the original expression.
1494 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1496 switch (Expr->getKind()) {
1497 case MCExpr::Constant:
1499 case MCExpr::SymbolRef:
1500 return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1501 case MCExpr::Binary:
1502 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1503 if (!isEvaluated(BE->getLHS()))
1505 return isEvaluated(BE->getRHS());
1508 return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1509 case MCExpr::Target:
1515 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1516 Parser.Lex(); // Eat the % token.
1517 const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1518 if (Tok.isNot(AsmToken::Identifier))
1521 std::string Str = Tok.getIdentifier().str();
1523 Parser.Lex(); // Eat the identifier.
1524 // Now make an expression from the rest of the operand.
1525 const MCExpr *IdVal;
1528 if (getLexer().getKind() == AsmToken::LParen) {
1530 Parser.Lex(); // Eat the '(' token.
1531 if (getLexer().getKind() == AsmToken::Percent) {
1532 Parser.Lex(); // Eat the % token.
1533 const AsmToken &nextTok = Parser.getTok();
1534 if (nextTok.isNot(AsmToken::Identifier))
1537 Str += nextTok.getIdentifier();
1538 Parser.Lex(); // Eat the identifier.
1539 if (getLexer().getKind() != AsmToken::LParen)
1544 if (getParser().parseParenExpression(IdVal, EndLoc))
1547 while (getLexer().getKind() == AsmToken::RParen)
1548 Parser.Lex(); // Eat the ')' token.
1551 return true; // Parenthesis must follow the relocation operand.
1553 Res = evaluateRelocExpr(IdVal, Str);
1557 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1559 SmallVector<MCParsedAsmOperand *, 1> Operands;
1560 OperandMatchResultTy ResTy = ParseAnyRegister(Operands);
1561 if (ResTy == MatchOperand_Success) {
1562 assert(Operands.size() == 1);
1563 MipsOperand &Operand = *static_cast<MipsOperand *>(Operands.front());
1564 StartLoc = Operand.getStartLoc();
1565 EndLoc = Operand.getEndLoc();
1567 // AFAIK, we only support numeric registers and named GPR's in CFI
1569 // Don't worry about eating tokens before failing. Using an unrecognised
1570 // register is a parse error.
1571 if (Operand.isGPRAsmReg()) {
1572 // Resolve to GPR32 or GPR64 appropriately.
1573 RegNo = isGP64() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
1578 return (RegNo == (unsigned)-1);
1581 assert(Operands.size() == 0);
1582 return (RegNo == (unsigned)-1);
1585 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1589 while (getLexer().getKind() == AsmToken::LParen)
1592 switch (getLexer().getKind()) {
1595 case AsmToken::Identifier:
1596 case AsmToken::LParen:
1597 case AsmToken::Integer:
1598 case AsmToken::Minus:
1599 case AsmToken::Plus:
1601 Result = getParser().parseParenExpression(Res, S);
1603 Result = (getParser().parseExpression(Res));
1604 while (getLexer().getKind() == AsmToken::RParen)
1607 case AsmToken::Percent:
1608 Result = parseRelocOperand(Res);
1613 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMemOperand(
1614 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1615 DEBUG(dbgs() << "parseMemOperand\n");
1616 const MCExpr *IdVal = 0;
1618 bool isParenExpr = false;
1619 MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1620 // First operand is the offset.
1621 S = Parser.getTok().getLoc();
1623 if (getLexer().getKind() == AsmToken::LParen) {
1628 if (getLexer().getKind() != AsmToken::Dollar) {
1629 if (parseMemOffset(IdVal, isParenExpr))
1630 return MatchOperand_ParseFail;
1632 const AsmToken &Tok = Parser.getTok(); // Get the next token.
1633 if (Tok.isNot(AsmToken::LParen)) {
1634 MipsOperand *Mnemonic = static_cast<MipsOperand *>(Operands[0]);
1635 if (Mnemonic->getToken() == "la") {
1637 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1638 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1639 return MatchOperand_Success;
1641 if (Tok.is(AsmToken::EndOfStatement)) {
1643 SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1645 // Zero register assumed, add a memory operand with ZERO as its base.
1646 // "Base" will be managed by k_Memory.
1647 MipsOperand *Base = MipsOperand::CreateGPRReg(
1648 0, getContext().getRegisterInfo(), S, E, *this);
1649 Operands.push_back(MipsOperand::CreateMem(Base, IdVal, S, E, *this));
1650 return MatchOperand_Success;
1652 Error(Parser.getTok().getLoc(), "'(' expected");
1653 return MatchOperand_ParseFail;
1656 Parser.Lex(); // Eat the '(' token.
1659 Res = ParseAnyRegister(Operands);
1660 if (Res != MatchOperand_Success)
1663 if (Parser.getTok().isNot(AsmToken::RParen)) {
1664 Error(Parser.getTok().getLoc(), "')' expected");
1665 return MatchOperand_ParseFail;
1668 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1670 Parser.Lex(); // Eat the ')' token.
1673 IdVal = MCConstantExpr::Create(0, getContext());
1675 // Replace the register operand with the memory operand.
1676 MipsOperand *op = static_cast<MipsOperand *>(Operands.back());
1677 // Remove the register from the operands.
1678 // "op" will be managed by k_Memory.
1679 Operands.pop_back();
1680 // Add the memory operand.
1681 if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1683 if (IdVal->EvaluateAsAbsolute(Imm))
1684 IdVal = MCConstantExpr::Create(Imm, getContext());
1685 else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1686 IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1690 Operands.push_back(MipsOperand::CreateMem(op, IdVal, S, E, *this));
1691 return MatchOperand_Success;
1694 bool MipsAsmParser::searchSymbolAlias(
1695 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1697 MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
1699 SMLoc S = Parser.getTok().getLoc();
1701 if (Sym->isVariable())
1702 Expr = Sym->getVariableValue();
1705 if (Expr->getKind() == MCExpr::SymbolRef) {
1706 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
1707 const StringRef DefSymbol = Ref->getSymbol().getName();
1708 if (DefSymbol.startswith("$")) {
1709 OperandMatchResultTy ResTy =
1710 MatchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
1711 if (ResTy == MatchOperand_Success) {
1714 } else if (ResTy == MatchOperand_ParseFail)
1715 llvm_unreachable("Should never ParseFail");
1718 } else if (Expr->getKind() == MCExpr::Constant) {
1720 const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
1722 MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this);
1723 Operands.push_back(op);
1730 MipsAsmParser::OperandMatchResultTy
1731 MipsAsmParser::MatchAnyRegisterNameWithoutDollar(
1732 SmallVectorImpl<MCParsedAsmOperand *> &Operands, StringRef Identifier,
1734 int Index = matchCPURegisterName(Identifier);
1736 Operands.push_back(MipsOperand::CreateGPRReg(
1737 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1738 return MatchOperand_Success;
1741 Index = matchFPURegisterName(Identifier);
1743 Operands.push_back(MipsOperand::CreateFGRReg(
1744 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1745 return MatchOperand_Success;
1748 Index = matchFCCRegisterName(Identifier);
1750 Operands.push_back(MipsOperand::CreateFCCReg(
1751 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1752 return MatchOperand_Success;
1755 Index = matchACRegisterName(Identifier);
1757 Operands.push_back(MipsOperand::CreateACCReg(
1758 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1759 return MatchOperand_Success;
1762 Index = matchMSA128RegisterName(Identifier);
1764 Operands.push_back(MipsOperand::CreateMSA128Reg(
1765 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1766 return MatchOperand_Success;
1769 Index = matchMSA128CtrlRegisterName(Identifier);
1771 Operands.push_back(MipsOperand::CreateMSACtrlReg(
1772 Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1773 return MatchOperand_Success;
1776 return MatchOperand_NoMatch;
1779 MipsAsmParser::OperandMatchResultTy
1780 MipsAsmParser::MatchAnyRegisterWithoutDollar(
1781 SmallVectorImpl<MCParsedAsmOperand *> &Operands, SMLoc S) {
1782 auto Token = Parser.getLexer().peekTok(false);
1784 if (Token.is(AsmToken::Identifier)) {
1785 DEBUG(dbgs() << ".. identifier\n");
1786 StringRef Identifier = Token.getIdentifier();
1787 OperandMatchResultTy ResTy =
1788 MatchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
1790 } else if (Token.is(AsmToken::Integer)) {
1791 DEBUG(dbgs() << ".. integer\n");
1792 Operands.push_back(MipsOperand::CreateNumericReg(
1793 Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
1795 return MatchOperand_Success;
1798 DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
1800 return MatchOperand_NoMatch;
1803 MipsAsmParser::OperandMatchResultTy MipsAsmParser::ParseAnyRegister(
1804 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1805 DEBUG(dbgs() << "ParseAnyRegister\n");
1807 auto Token = Parser.getTok();
1809 SMLoc S = Token.getLoc();
1811 if (Token.isNot(AsmToken::Dollar)) {
1812 DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
1813 if (Token.is(AsmToken::Identifier)) {
1814 if (searchSymbolAlias(Operands))
1815 return MatchOperand_Success;
1817 DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
1818 return MatchOperand_NoMatch;
1820 DEBUG(dbgs() << ".. $\n");
1822 OperandMatchResultTy ResTy = MatchAnyRegisterWithoutDollar(Operands, S);
1823 if (ResTy == MatchOperand_Success) {
1825 Parser.Lex(); // identifier
1830 MipsAsmParser::OperandMatchResultTy
1831 MipsAsmParser::ParseImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1832 switch (getLexer().getKind()) {
1834 return MatchOperand_NoMatch;
1835 case AsmToken::LParen:
1836 case AsmToken::Minus:
1837 case AsmToken::Plus:
1838 case AsmToken::Integer:
1839 case AsmToken::String:
1843 const MCExpr *IdVal;
1844 SMLoc S = Parser.getTok().getLoc();
1845 if (getParser().parseExpression(IdVal))
1846 return MatchOperand_ParseFail;
1848 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1849 Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1850 return MatchOperand_Success;
1853 MipsAsmParser::OperandMatchResultTy MipsAsmParser::ParseJumpTarget(
1854 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1855 DEBUG(dbgs() << "ParseJumpTarget\n");
1857 SMLoc S = getLexer().getLoc();
1859 // Integers and expressions are acceptable
1860 OperandMatchResultTy ResTy = ParseImm(Operands);
1861 if (ResTy != MatchOperand_NoMatch)
1864 // Registers are a valid target and have priority over symbols.
1865 ResTy = ParseAnyRegister(Operands);
1866 if (ResTy != MatchOperand_NoMatch)
1869 const MCExpr *Expr = nullptr;
1870 if (Parser.parseExpression(Expr)) {
1871 // We have no way of knowing if a symbol was consumed so we must ParseFail
1872 return MatchOperand_ParseFail;
1875 MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
1876 return MatchOperand_Success;
1879 MipsAsmParser::OperandMatchResultTy
1880 MipsAsmParser::parseInvNum(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1881 const MCExpr *IdVal;
1882 // If the first token is '$' we may have register operand.
1883 if (Parser.getTok().is(AsmToken::Dollar))
1884 return MatchOperand_NoMatch;
1885 SMLoc S = Parser.getTok().getLoc();
1886 if (getParser().parseExpression(IdVal))
1887 return MatchOperand_ParseFail;
1888 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
1889 assert(MCE && "Unexpected MCExpr type.");
1890 int64_t Val = MCE->getValue();
1891 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1892 Operands.push_back(MipsOperand::CreateImm(
1893 MCConstantExpr::Create(0 - Val, getContext()), S, E, *this));
1894 return MatchOperand_Success;
1897 MipsAsmParser::OperandMatchResultTy
1898 MipsAsmParser::ParseLSAImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1899 switch (getLexer().getKind()) {
1901 return MatchOperand_NoMatch;
1902 case AsmToken::LParen:
1903 case AsmToken::Plus:
1904 case AsmToken::Minus:
1905 case AsmToken::Integer:
1910 SMLoc S = Parser.getTok().getLoc();
1912 if (getParser().parseExpression(Expr))
1913 return MatchOperand_ParseFail;
1916 if (!Expr->EvaluateAsAbsolute(Val)) {
1917 Error(S, "expected immediate value");
1918 return MatchOperand_ParseFail;
1921 // The LSA instruction allows a 2-bit unsigned immediate. For this reason
1922 // and because the CPU always adds one to the immediate field, the allowed
1923 // range becomes 1..4. We'll only check the range here and will deal
1924 // with the addition/subtraction when actually decoding/encoding
1926 if (Val < 1 || Val > 4) {
1927 Error(S, "immediate not in range (1..4)");
1928 return MatchOperand_ParseFail;
1932 MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
1933 return MatchOperand_Success;
1936 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
1938 MCSymbolRefExpr::VariantKind VK =
1939 StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
1940 .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
1941 .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
1942 .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
1943 .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
1944 .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
1945 .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
1946 .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
1947 .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
1948 .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
1949 .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
1950 .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
1951 .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
1952 .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
1953 .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
1954 .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
1955 .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
1956 .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
1957 .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
1958 .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
1959 .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
1960 .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
1961 .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
1962 .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
1963 .Default(MCSymbolRefExpr::VK_None);
1965 assert (VK != MCSymbolRefExpr::VK_None);
1970 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
1972 /// ::= '(', register, ')'
1973 /// handle it before we iterate so we don't get tripped up by the lack of
1975 bool MipsAsmParser::ParseParenSuffix(
1976 StringRef Name, SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1977 if (getLexer().is(AsmToken::LParen)) {
1979 MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
1981 if (ParseOperand(Operands, Name)) {
1982 SMLoc Loc = getLexer().getLoc();
1983 Parser.eatToEndOfStatement();
1984 return Error(Loc, "unexpected token in argument list");
1986 if (Parser.getTok().isNot(AsmToken::RParen)) {
1987 SMLoc Loc = getLexer().getLoc();
1988 Parser.eatToEndOfStatement();
1989 return Error(Loc, "unexpected token, expected ')'");
1992 MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
1998 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
1999 /// either one of these.
2000 /// ::= '[', register, ']'
2001 /// ::= '[', integer, ']'
2002 /// handle it before we iterate so we don't get tripped up by the lack of
2004 bool MipsAsmParser::ParseBracketSuffix(
2005 StringRef Name, SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2006 if (getLexer().is(AsmToken::LBrac)) {
2008 MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
2010 if (ParseOperand(Operands, Name)) {
2011 SMLoc Loc = getLexer().getLoc();
2012 Parser.eatToEndOfStatement();
2013 return Error(Loc, "unexpected token in argument list");
2015 if (Parser.getTok().isNot(AsmToken::RBrac)) {
2016 SMLoc Loc = getLexer().getLoc();
2017 Parser.eatToEndOfStatement();
2018 return Error(Loc, "unexpected token, expected ']'");
2021 MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
2027 bool MipsAsmParser::ParseInstruction(
2028 ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
2029 SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2030 DEBUG(dbgs() << "ParseInstruction\n");
2031 // Check if we have valid mnemonic
2032 if (!mnemonicIsValid(Name, 0)) {
2033 Parser.eatToEndOfStatement();
2034 return Error(NameLoc, "Unknown instruction");
2036 // First operand in MCInst is instruction mnemonic.
2037 Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
2039 // Read the remaining operands.
2040 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2041 // Read the first operand.
2042 if (ParseOperand(Operands, Name)) {
2043 SMLoc Loc = getLexer().getLoc();
2044 Parser.eatToEndOfStatement();
2045 return Error(Loc, "unexpected token in argument list");
2047 if (getLexer().is(AsmToken::LBrac) && ParseBracketSuffix(Name, Operands))
2049 // AFAIK, parenthesis suffixes are never on the first operand
2051 while (getLexer().is(AsmToken::Comma)) {
2052 Parser.Lex(); // Eat the comma.
2053 // Parse and remember the operand.
2054 if (ParseOperand(Operands, Name)) {
2055 SMLoc Loc = getLexer().getLoc();
2056 Parser.eatToEndOfStatement();
2057 return Error(Loc, "unexpected token in argument list");
2059 // Parse bracket and parenthesis suffixes before we iterate
2060 if (getLexer().is(AsmToken::LBrac)) {
2061 if (ParseBracketSuffix(Name, Operands))
2063 } else if (getLexer().is(AsmToken::LParen) &&
2064 ParseParenSuffix(Name, Operands))
2068 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2069 SMLoc Loc = getLexer().getLoc();
2070 Parser.eatToEndOfStatement();
2071 return Error(Loc, "unexpected token in argument list");
2073 Parser.Lex(); // Consume the EndOfStatement.
2077 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2078 SMLoc Loc = getLexer().getLoc();
2079 Parser.eatToEndOfStatement();
2080 return Error(Loc, ErrorMsg);
2083 bool MipsAsmParser::parseSetNoAtDirective() {
2084 // Line should look like: ".set noat".
2086 Options.setATReg(0);
2089 // If this is not the end of the statement, report an error.
2090 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2091 reportParseError("unexpected token in statement");
2094 Parser.Lex(); // Consume the EndOfStatement.
2098 bool MipsAsmParser::parseSetAtDirective() {
2099 // Line can be .set at - defaults to $1
2103 if (getLexer().is(AsmToken::EndOfStatement)) {
2104 Options.setATReg(1);
2105 Parser.Lex(); // Consume the EndOfStatement.
2107 } else if (getLexer().is(AsmToken::Equal)) {
2108 getParser().Lex(); // Eat the '='.
2109 if (getLexer().isNot(AsmToken::Dollar)) {
2110 reportParseError("unexpected token in statement");
2113 Parser.Lex(); // Eat the '$'.
2114 const AsmToken &Reg = Parser.getTok();
2115 if (Reg.is(AsmToken::Identifier)) {
2116 AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2117 } else if (Reg.is(AsmToken::Integer)) {
2118 AtRegNo = Reg.getIntVal();
2120 reportParseError("unexpected token in statement");
2124 if (AtRegNo < 0 || AtRegNo > 31) {
2125 reportParseError("unexpected token in statement");
2129 if (!Options.setATReg(AtRegNo)) {
2130 reportParseError("unexpected token in statement");
2133 getParser().Lex(); // Eat the register.
2135 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2136 reportParseError("unexpected token in statement");
2139 Parser.Lex(); // Consume the EndOfStatement.
2142 reportParseError("unexpected token in statement");
2147 bool MipsAsmParser::parseSetReorderDirective() {
2149 // If this is not the end of the statement, report an error.
2150 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2151 reportParseError("unexpected token in statement");
2154 Options.setReorder();
2155 getTargetStreamer().emitDirectiveSetReorder();
2156 Parser.Lex(); // Consume the EndOfStatement.
2160 bool MipsAsmParser::parseSetNoReorderDirective() {
2162 // If this is not the end of the statement, report an error.
2163 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2164 reportParseError("unexpected token in statement");
2167 Options.setNoreorder();
2168 getTargetStreamer().emitDirectiveSetNoReorder();
2169 Parser.Lex(); // Consume the EndOfStatement.
2173 bool MipsAsmParser::parseSetMacroDirective() {
2175 // If this is not the end of the statement, report an error.
2176 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2177 reportParseError("unexpected token in statement");
2181 Parser.Lex(); // Consume the EndOfStatement.
2185 bool MipsAsmParser::parseSetNoMacroDirective() {
2187 // If this is not the end of the statement, report an error.
2188 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2189 reportParseError("`noreorder' must be set before `nomacro'");
2192 if (Options.isReorder()) {
2193 reportParseError("`noreorder' must be set before `nomacro'");
2196 Options.setNomacro();
2197 Parser.Lex(); // Consume the EndOfStatement.
2201 bool MipsAsmParser::parseSetNoMips16Directive() {
2203 // If this is not the end of the statement, report an error.
2204 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2205 reportParseError("unexpected token in statement");
2208 // For now do nothing.
2209 Parser.Lex(); // Consume the EndOfStatement.
2213 bool MipsAsmParser::parseSetAssignment() {
2215 const MCExpr *Value;
2217 if (Parser.parseIdentifier(Name))
2218 reportParseError("expected identifier after .set");
2220 if (getLexer().isNot(AsmToken::Comma))
2221 return reportParseError("unexpected token in .set directive");
2224 if (Parser.parseExpression(Value))
2225 return reportParseError("expected valid expression after comma");
2227 // Check if the Name already exists as a symbol.
2228 MCSymbol *Sym = getContext().LookupSymbol(Name);
2230 return reportParseError("symbol already defined");
2231 Sym = getContext().GetOrCreateSymbol(Name);
2232 Sym->setVariableValue(Value);
2237 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2239 if (getLexer().isNot(AsmToken::EndOfStatement))
2240 return reportParseError("unexpected token in .set directive");
2243 default: llvm_unreachable("Unimplemented feature");
2244 case Mips::FeatureDSP:
2245 setFeatureBits(Mips::FeatureDSP, "dsp");
2246 getTargetStreamer().emitDirectiveSetDsp();
2248 case Mips::FeatureMicroMips:
2249 getTargetStreamer().emitDirectiveSetMicroMips();
2251 case Mips::FeatureMips16:
2252 getTargetStreamer().emitDirectiveSetMips16();
2254 case Mips::FeatureMips32r2:
2255 setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2256 getTargetStreamer().emitDirectiveSetMips32R2();
2258 case Mips::FeatureMips64:
2259 setFeatureBits(Mips::FeatureMips64, "mips64");
2260 getTargetStreamer().emitDirectiveSetMips64();
2262 case Mips::FeatureMips64r2:
2263 setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2264 getTargetStreamer().emitDirectiveSetMips64R2();
2270 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2271 if (!getLexer().is(AsmToken::Dollar))
2276 const AsmToken &Reg = Parser.getTok();
2277 if (Reg.is(AsmToken::Identifier)) {
2278 RegNum = matchCPURegisterName(Reg.getIdentifier());
2279 } else if (Reg.is(AsmToken::Integer)) {
2280 RegNum = Reg.getIntVal();
2289 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2290 if (getLexer().isNot(AsmToken::Comma)) {
2291 SMLoc Loc = getLexer().getLoc();
2292 Parser.eatToEndOfStatement();
2293 return Error(Loc, ErrorStr);
2296 Parser.Lex(); // Eat the comma.
2300 bool MipsAsmParser::parseDirectiveCPSetup() {
2303 bool SaveIsReg = true;
2305 if (!parseRegister(FuncReg))
2306 return reportParseError("expected register containing function address");
2307 FuncReg = getGPR(FuncReg);
2309 if (!eatComma("expected comma parsing directive"))
2312 if (!parseRegister(Save)) {
2313 const AsmToken &Tok = Parser.getTok();
2314 if (Tok.is(AsmToken::Integer)) {
2315 Save = Tok.getIntVal();
2319 return reportParseError("expected save register or stack offset");
2321 Save = getGPR(Save);
2323 if (!eatComma("expected comma parsing directive"))
2327 if (Parser.parseIdentifier(Name))
2328 reportParseError("expected identifier");
2329 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2330 unsigned GPReg = getGPR(matchCPURegisterName("gp"));
2332 // FIXME: The code below this point should be in the TargetStreamers.
2333 // Only N32 and N64 emit anything for .cpsetup
2334 // FIXME: We should only emit something for PIC mode too.
2335 if (!isN32() && !isN64())
2338 MCStreamer &TS = getStreamer();
2340 // Either store the old $gp in a register or on the stack
2342 // move $save, $gpreg
2343 Inst.setOpcode(Mips::DADDu);
2344 Inst.addOperand(MCOperand::CreateReg(Save));
2345 Inst.addOperand(MCOperand::CreateReg(GPReg));
2346 Inst.addOperand(MCOperand::CreateReg(getGPR(0)));
2348 // sd $gpreg, offset($sp)
2349 Inst.setOpcode(Mips::SD);
2350 Inst.addOperand(MCOperand::CreateReg(GPReg));
2351 Inst.addOperand(MCOperand::CreateReg(getGPR(matchCPURegisterName("sp"))));
2352 Inst.addOperand(MCOperand::CreateImm(Save));
2354 TS.EmitInstruction(Inst, STI);
2357 const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
2358 Sym->getName(), MCSymbolRefExpr::VK_Mips_GPOFF_HI,
2360 const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
2361 Sym->getName(), MCSymbolRefExpr::VK_Mips_GPOFF_LO,
2363 // lui $gp, %hi(%neg(%gp_rel(funcSym)))
2364 Inst.setOpcode(Mips::LUi);
2365 Inst.addOperand(MCOperand::CreateReg(GPReg));
2366 Inst.addOperand(MCOperand::CreateExpr(HiExpr));
2367 TS.EmitInstruction(Inst, STI);
2370 // addiu $gp, $gp, %lo(%neg(%gp_rel(funcSym)))
2371 Inst.setOpcode(Mips::ADDiu);
2372 Inst.addOperand(MCOperand::CreateReg(GPReg));
2373 Inst.addOperand(MCOperand::CreateReg(GPReg));
2374 Inst.addOperand(MCOperand::CreateExpr(LoExpr));
2375 TS.EmitInstruction(Inst, STI);
2378 // daddu $gp, $gp, $funcreg
2379 Inst.setOpcode(Mips::DADDu);
2380 Inst.addOperand(MCOperand::CreateReg(GPReg));
2381 Inst.addOperand(MCOperand::CreateReg(GPReg));
2382 Inst.addOperand(MCOperand::CreateReg(FuncReg));
2383 TS.EmitInstruction(Inst, STI);
2387 bool MipsAsmParser::parseDirectiveNaN() {
2388 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2389 const AsmToken &Tok = Parser.getTok();
2391 if (Tok.getString() == "2008") {
2393 getTargetStreamer().emitDirectiveNaN2008();
2395 } else if (Tok.getString() == "legacy") {
2397 getTargetStreamer().emitDirectiveNaNLegacy();
2401 // If we don't recognize the option passed to the .nan
2402 // directive (e.g. no option or unknown option), emit an error.
2403 reportParseError("invalid option in .nan directive");
2407 bool MipsAsmParser::parseDirectiveSet() {
2409 // Get the next token.
2410 const AsmToken &Tok = Parser.getTok();
2412 if (Tok.getString() == "noat") {
2413 return parseSetNoAtDirective();
2414 } else if (Tok.getString() == "at") {
2415 return parseSetAtDirective();
2416 } else if (Tok.getString() == "reorder") {
2417 return parseSetReorderDirective();
2418 } else if (Tok.getString() == "noreorder") {
2419 return parseSetNoReorderDirective();
2420 } else if (Tok.getString() == "macro") {
2421 return parseSetMacroDirective();
2422 } else if (Tok.getString() == "nomacro") {
2423 return parseSetNoMacroDirective();
2424 } else if (Tok.getString() == "mips16") {
2425 return parseSetFeature(Mips::FeatureMips16);
2426 } else if (Tok.getString() == "nomips16") {
2427 return parseSetNoMips16Directive();
2428 } else if (Tok.getString() == "nomicromips") {
2429 getTargetStreamer().emitDirectiveSetNoMicroMips();
2430 Parser.eatToEndOfStatement();
2432 } else if (Tok.getString() == "micromips") {
2433 return parseSetFeature(Mips::FeatureMicroMips);
2434 } else if (Tok.getString() == "mips32r2") {
2435 return parseSetFeature(Mips::FeatureMips32r2);
2436 } else if (Tok.getString() == "mips64") {
2437 return parseSetFeature(Mips::FeatureMips64);
2438 } else if (Tok.getString() == "mips64r2") {
2439 return parseSetFeature(Mips::FeatureMips64r2);
2440 } else if (Tok.getString() == "dsp") {
2441 return parseSetFeature(Mips::FeatureDSP);
2443 // It is just an identifier, look for an assignment.
2444 parseSetAssignment();
2451 /// parseDataDirective
2452 /// ::= .word [ expression (, expression)* ]
2453 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2454 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2456 const MCExpr *Value;
2457 if (getParser().parseExpression(Value))
2460 getParser().getStreamer().EmitValue(Value, Size);
2462 if (getLexer().is(AsmToken::EndOfStatement))
2465 // FIXME: Improve diagnostic.
2466 if (getLexer().isNot(AsmToken::Comma))
2467 return Error(L, "unexpected token in directive");
2476 /// parseDirectiveGpWord
2477 /// ::= .gpword local_sym
2478 bool MipsAsmParser::parseDirectiveGpWord() {
2479 const MCExpr *Value;
2480 // EmitGPRel32Value requires an expression, so we are using base class
2481 // method to evaluate the expression.
2482 if (getParser().parseExpression(Value))
2484 getParser().getStreamer().EmitGPRel32Value(Value);
2486 if (getLexer().isNot(AsmToken::EndOfStatement))
2487 return Error(getLexer().getLoc(), "unexpected token in directive");
2488 Parser.Lex(); // Eat EndOfStatement token.
2492 /// parseDirectiveGpDWord
2493 /// ::= .gpdword local_sym
2494 bool MipsAsmParser::parseDirectiveGpDWord() {
2495 const MCExpr *Value;
2496 // EmitGPRel64Value requires an expression, so we are using base class
2497 // method to evaluate the expression.
2498 if (getParser().parseExpression(Value))
2500 getParser().getStreamer().EmitGPRel64Value(Value);
2502 if (getLexer().isNot(AsmToken::EndOfStatement))
2503 return Error(getLexer().getLoc(), "unexpected token in directive");
2504 Parser.Lex(); // Eat EndOfStatement token.
2508 bool MipsAsmParser::parseDirectiveOption() {
2509 // Get the option token.
2510 AsmToken Tok = Parser.getTok();
2511 // At the moment only identifiers are supported.
2512 if (Tok.isNot(AsmToken::Identifier)) {
2513 Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2514 Parser.eatToEndOfStatement();
2518 StringRef Option = Tok.getIdentifier();
2520 if (Option == "pic0") {
2521 getTargetStreamer().emitDirectiveOptionPic0();
2523 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2524 Error(Parser.getTok().getLoc(),
2525 "unexpected token in .option pic0 directive");
2526 Parser.eatToEndOfStatement();
2531 if (Option == "pic2") {
2532 getTargetStreamer().emitDirectiveOptionPic2();
2534 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2535 Error(Parser.getTok().getLoc(),
2536 "unexpected token in .option pic2 directive");
2537 Parser.eatToEndOfStatement();
2543 Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2544 Parser.eatToEndOfStatement();
2548 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2549 StringRef IDVal = DirectiveID.getString();
2551 if (IDVal == ".dword") {
2552 parseDataDirective(8, DirectiveID.getLoc());
2556 if (IDVal == ".ent") {
2557 // Ignore this directive for now.
2562 if (IDVal == ".end") {
2563 // Ignore this directive for now.
2568 if (IDVal == ".frame") {
2569 // Ignore this directive for now.
2570 Parser.eatToEndOfStatement();
2574 if (IDVal == ".set") {
2575 return parseDirectiveSet();
2578 if (IDVal == ".fmask") {
2579 // Ignore this directive for now.
2580 Parser.eatToEndOfStatement();
2584 if (IDVal == ".mask") {
2585 // Ignore this directive for now.
2586 Parser.eatToEndOfStatement();
2590 if (IDVal == ".nan")
2591 return parseDirectiveNaN();
2593 if (IDVal == ".gpword") {
2594 parseDirectiveGpWord();
2598 if (IDVal == ".gpdword") {
2599 parseDirectiveGpDWord();
2603 if (IDVal == ".word") {
2604 parseDataDirective(4, DirectiveID.getLoc());
2608 if (IDVal == ".option")
2609 return parseDirectiveOption();
2611 if (IDVal == ".abicalls") {
2612 getTargetStreamer().emitDirectiveAbiCalls();
2613 if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2614 Error(Parser.getTok().getLoc(), "unexpected token in directive");
2616 Parser.eatToEndOfStatement();
2621 if (IDVal == ".cpsetup")
2622 return parseDirectiveCPSetup();
2627 extern "C" void LLVMInitializeMipsAsmParser() {
2628 RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2629 RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2630 RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2631 RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2634 #define GET_REGISTER_MATCHER
2635 #define GET_MATCHER_IMPLEMENTATION
2636 #include "MipsGenAsmMatcher.inc"