[mips][mips64r6] ssnop is deprecated on MIPS32r6/MIPS64r6
[oota-llvm.git] / lib / Target / Mips / AsmParser / MipsAsmParser.cpp
1 //===-- MipsAsmParser.cpp - Parse Mips assembly to MCInst instructions ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "mips-asm-parser"
33
34 namespace llvm {
35 class MCInstrInfo;
36 }
37
38 namespace {
39 class MipsAssemblerOptions {
40 public:
41   MipsAssemblerOptions() : aTReg(1), reorder(true), macro(true) {}
42
43   unsigned getATRegNum() { return aTReg; }
44   bool setATReg(unsigned Reg);
45
46   bool isReorder() { return reorder; }
47   void setReorder() { reorder = true; }
48   void setNoreorder() { reorder = false; }
49
50   bool isMacro() { return macro; }
51   void setMacro() { macro = true; }
52   void setNomacro() { macro = false; }
53
54 private:
55   unsigned aTReg;
56   bool reorder;
57   bool macro;
58 };
59 }
60
61 namespace {
62 class MipsAsmParser : public MCTargetAsmParser {
63   MipsTargetStreamer &getTargetStreamer() {
64     MCTargetStreamer &TS = *Parser.getStreamer().getTargetStreamer();
65     return static_cast<MipsTargetStreamer &>(TS);
66   }
67
68   MCSubtargetInfo &STI;
69   MCAsmParser &Parser;
70   MipsAssemblerOptions Options;
71
72 #define GET_ASSEMBLER_HEADER
73 #include "MipsGenAsmMatcher.inc"
74
75   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
76
77   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
78                                OperandVector &Operands, MCStreamer &Out,
79                                unsigned &ErrorInfo,
80                                bool MatchingInlineAsm) override;
81
82   /// Parse a register as used in CFI directives
83   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
84
85   bool ParseParenSuffix(StringRef Name, OperandVector &Operands);
86
87   bool ParseBracketSuffix(StringRef Name, OperandVector &Operands);
88
89   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
90                         SMLoc NameLoc, OperandVector &Operands) override;
91
92   bool ParseDirective(AsmToken DirectiveID) override;
93
94   MipsAsmParser::OperandMatchResultTy parseMemOperand(OperandVector &Operands);
95
96   MipsAsmParser::OperandMatchResultTy
97   MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
98                                     StringRef Identifier, SMLoc S);
99
100   MipsAsmParser::OperandMatchResultTy
101   MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S);
102
103   MipsAsmParser::OperandMatchResultTy ParseAnyRegister(OperandVector &Operands);
104
105   MipsAsmParser::OperandMatchResultTy ParseImm(OperandVector &Operands);
106
107   MipsAsmParser::OperandMatchResultTy ParseJumpTarget(OperandVector &Operands);
108
109   MipsAsmParser::OperandMatchResultTy parseInvNum(OperandVector &Operands);
110
111   MipsAsmParser::OperandMatchResultTy ParseLSAImm(OperandVector &Operands);
112
113   bool searchSymbolAlias(OperandVector &Operands);
114
115   bool ParseOperand(OperandVector &, StringRef Mnemonic);
116
117   bool needsExpansion(MCInst &Inst);
118
119   void expandInstruction(MCInst &Inst, SMLoc IDLoc,
120                          SmallVectorImpl<MCInst> &Instructions);
121   void expandLoadImm(MCInst &Inst, SMLoc IDLoc,
122                      SmallVectorImpl<MCInst> &Instructions);
123   void expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
124                             SmallVectorImpl<MCInst> &Instructions);
125   void expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
126                             SmallVectorImpl<MCInst> &Instructions);
127   void expandMemInst(MCInst &Inst, SMLoc IDLoc,
128                      SmallVectorImpl<MCInst> &Instructions, bool isLoad,
129                      bool isImmOpnd);
130   bool reportParseError(StringRef ErrorMsg);
131   bool reportParseError(SMLoc Loc, StringRef ErrorMsg);
132
133   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
134   bool parseRelocOperand(const MCExpr *&Res);
135
136   const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
137
138   bool isEvaluated(const MCExpr *Expr);
139   bool parseSetFeature(uint64_t Feature);
140   bool parseDirectiveCPLoad(SMLoc Loc);
141   bool parseDirectiveCPSetup();
142   bool parseDirectiveNaN();
143   bool parseDirectiveSet();
144   bool parseDirectiveOption();
145
146   bool parseSetAtDirective();
147   bool parseSetNoAtDirective();
148   bool parseSetMacroDirective();
149   bool parseSetNoMacroDirective();
150   bool parseSetReorderDirective();
151   bool parseSetNoReorderDirective();
152   bool parseSetNoMips16Directive();
153
154   bool parseSetAssignment();
155
156   bool parseDataDirective(unsigned Size, SMLoc L);
157   bool parseDirectiveGpWord();
158   bool parseDirectiveGpDWord();
159
160   MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
161
162   bool isGP64() const {
163     return (STI.getFeatureBits() & Mips::FeatureGP64Bit) != 0;
164   }
165
166   bool isFP64() const {
167     return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
168   }
169
170   bool isN32() const { return STI.getFeatureBits() & Mips::FeatureN32; }
171   bool isN64() const { return STI.getFeatureBits() & Mips::FeatureN64; }
172
173   bool isMicroMips() const {
174     return STI.getFeatureBits() & Mips::FeatureMicroMips;
175   }
176
177   bool hasMips4() const { return STI.getFeatureBits() & Mips::FeatureMips4; }
178   bool hasMips32() const { return STI.getFeatureBits() & Mips::FeatureMips32; }
179   bool hasMips32r6() const {
180     return STI.getFeatureBits() & Mips::FeatureMips32r6;
181   }
182   bool hasMips64r6() const {
183     return STI.getFeatureBits() & Mips::FeatureMips64r6;
184   }
185
186   bool parseRegister(unsigned &RegNum);
187
188   bool eatComma(StringRef ErrorStr);
189
190   int matchCPURegisterName(StringRef Symbol);
191
192   int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
193
194   int matchFPURegisterName(StringRef Name);
195
196   int matchFCCRegisterName(StringRef Name);
197
198   int matchACRegisterName(StringRef Name);
199
200   int matchMSA128RegisterName(StringRef Name);
201
202   int matchMSA128CtrlRegisterName(StringRef Name);
203
204   unsigned getReg(int RC, int RegNo);
205
206   unsigned getGPR(int RegNo);
207
208   int getATReg();
209
210   bool processInstruction(MCInst &Inst, SMLoc IDLoc,
211                           SmallVectorImpl<MCInst> &Instructions);
212
213   // Helper function that checks if the value of a vector index is within the
214   // boundaries of accepted values for each RegisterKind
215   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
216   bool validateMSAIndex(int Val, int RegKind);
217
218   void setFeatureBits(unsigned Feature, StringRef FeatureString) {
219     if (!(STI.getFeatureBits() & Feature)) {
220       setAvailableFeatures(
221           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
222     }
223   }
224
225   void clearFeatureBits(unsigned Feature, StringRef FeatureString) {
226     if (STI.getFeatureBits() & Feature) {
227       setAvailableFeatures(
228           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
229     }
230   }
231
232 public:
233   enum MipsMatchResultTy {
234     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY
235 #define GET_OPERAND_DIAGNOSTIC_TYPES
236 #include "MipsGenAsmMatcher.inc"
237 #undef GET_OPERAND_DIAGNOSTIC_TYPES
238
239   };
240
241   MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
242                 const MCInstrInfo &MII,
243                 const MCTargetOptions &Options)
244       : MCTargetAsmParser(), STI(sti), Parser(parser) {
245     // Initialize the set of available features.
246     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
247
248     // Assert exactly one ABI was chosen.
249     assert((((STI.getFeatureBits() & Mips::FeatureO32) != 0) +
250             ((STI.getFeatureBits() & Mips::FeatureEABI) != 0) +
251             ((STI.getFeatureBits() & Mips::FeatureN32) != 0) +
252             ((STI.getFeatureBits() & Mips::FeatureN64) != 0)) == 1);
253   }
254
255   MCAsmParser &getParser() const { return Parser; }
256   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
257
258   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
259   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
260
261   /// Warn if RegNo is the current assembler temporary.
262   void WarnIfAssemblerTemporary(int RegNo, SMLoc Loc);
263 };
264 }
265
266 namespace {
267
268 /// MipsOperand - Instances of this class represent a parsed Mips machine
269 /// instruction.
270 class MipsOperand : public MCParsedAsmOperand {
271 public:
272   /// Broad categories of register classes
273   /// The exact class is finalized by the render method.
274   enum RegKind {
275     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64())
276     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
277                           /// isFP64())
278     RegKind_FCC = 4,      /// FCC
279     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
280     RegKind_MSACtrl = 16, /// MSA control registers
281     RegKind_COP2 = 32,    /// COP2
282     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
283                           /// context).
284     RegKind_CCR = 128,    /// CCR
285     RegKind_HWRegs = 256, /// HWRegs
286     RegKind_COP3 = 512,   /// COP3
287
288     /// Potentially any (e.g. $1)
289     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
290                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
291                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3
292   };
293
294 private:
295   enum KindTy {
296     k_Immediate,     /// An immediate (possibly involving symbol references)
297     k_Memory,        /// Base + Offset Memory Address
298     k_PhysRegister,  /// A physical register from the Mips namespace
299     k_RegisterIndex, /// A register index in one or more RegKind.
300     k_Token          /// A simple token
301   } Kind;
302
303 public:
304   MipsOperand(KindTy K, MipsAsmParser &Parser)
305       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
306
307 private:
308   /// For diagnostics, and checking the assembler temporary
309   MipsAsmParser &AsmParser;
310
311   struct Token {
312     const char *Data;
313     unsigned Length;
314   };
315
316   struct PhysRegOp {
317     unsigned Num; /// Register Number
318   };
319
320   struct RegIdxOp {
321     unsigned Index; /// Index into the register class
322     RegKind Kind;   /// Bitfield of the kinds it could possibly be
323     const MCRegisterInfo *RegInfo;
324   };
325
326   struct ImmOp {
327     const MCExpr *Val;
328   };
329
330   struct MemOp {
331     MipsOperand *Base;
332     const MCExpr *Off;
333   };
334
335   union {
336     struct Token Tok;
337     struct PhysRegOp PhysReg;
338     struct RegIdxOp RegIdx;
339     struct ImmOp Imm;
340     struct MemOp Mem;
341   };
342
343   SMLoc StartLoc, EndLoc;
344
345   /// Internal constructor for register kinds
346   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
347                                                 const MCRegisterInfo *RegInfo,
348                                                 SMLoc S, SMLoc E,
349                                                 MipsAsmParser &Parser) {
350     auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
351     Op->RegIdx.Index = Index;
352     Op->RegIdx.RegInfo = RegInfo;
353     Op->RegIdx.Kind = RegKind;
354     Op->StartLoc = S;
355     Op->EndLoc = E;
356     return Op;
357   }
358
359 public:
360   /// Coerce the register to GPR32 and return the real register for the current
361   /// target.
362   unsigned getGPR32Reg() const {
363     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
364     AsmParser.WarnIfAssemblerTemporary(RegIdx.Index, StartLoc);
365     unsigned ClassID = Mips::GPR32RegClassID;
366     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
367   }
368
369   /// Coerce the register to GPR64 and return the real register for the current
370   /// target.
371   unsigned getGPR64Reg() const {
372     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
373     unsigned ClassID = Mips::GPR64RegClassID;
374     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
375   }
376
377 private:
378   /// Coerce the register to AFGR64 and return the real register for the current
379   /// target.
380   unsigned getAFGR64Reg() const {
381     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
382     if (RegIdx.Index % 2 != 0)
383       AsmParser.Warning(StartLoc, "Float register should be even.");
384     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
385         .getRegister(RegIdx.Index / 2);
386   }
387
388   /// Coerce the register to FGR64 and return the real register for the current
389   /// target.
390   unsigned getFGR64Reg() const {
391     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
392     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
393         .getRegister(RegIdx.Index);
394   }
395
396   /// Coerce the register to FGR32 and return the real register for the current
397   /// target.
398   unsigned getFGR32Reg() const {
399     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
400     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
401         .getRegister(RegIdx.Index);
402   }
403
404   /// Coerce the register to FGRH32 and return the real register for the current
405   /// target.
406   unsigned getFGRH32Reg() const {
407     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
408     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
409         .getRegister(RegIdx.Index);
410   }
411
412   /// Coerce the register to FCC and return the real register for the current
413   /// target.
414   unsigned getFCCReg() const {
415     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
416     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
417         .getRegister(RegIdx.Index);
418   }
419
420   /// Coerce the register to MSA128 and return the real register for the current
421   /// target.
422   unsigned getMSA128Reg() const {
423     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
424     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
425     // identical
426     unsigned ClassID = Mips::MSA128BRegClassID;
427     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
428   }
429
430   /// Coerce the register to MSACtrl and return the real register for the
431   /// current target.
432   unsigned getMSACtrlReg() const {
433     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
434     unsigned ClassID = Mips::MSACtrlRegClassID;
435     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
436   }
437
438   /// Coerce the register to COP2 and return the real register for the
439   /// current target.
440   unsigned getCOP2Reg() const {
441     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
442     unsigned ClassID = Mips::COP2RegClassID;
443     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
444   }
445
446   /// Coerce the register to COP3 and return the real register for the
447   /// current target.
448   unsigned getCOP3Reg() const {
449     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
450     unsigned ClassID = Mips::COP3RegClassID;
451     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
452   }
453
454   /// Coerce the register to ACC64DSP and return the real register for the
455   /// current target.
456   unsigned getACC64DSPReg() const {
457     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
458     unsigned ClassID = Mips::ACC64DSPRegClassID;
459     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
460   }
461
462   /// Coerce the register to HI32DSP and return the real register for the
463   /// current target.
464   unsigned getHI32DSPReg() const {
465     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
466     unsigned ClassID = Mips::HI32DSPRegClassID;
467     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
468   }
469
470   /// Coerce the register to LO32DSP and return the real register for the
471   /// current target.
472   unsigned getLO32DSPReg() const {
473     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
474     unsigned ClassID = Mips::LO32DSPRegClassID;
475     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
476   }
477
478   /// Coerce the register to CCR and return the real register for the
479   /// current target.
480   unsigned getCCRReg() const {
481     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
482     unsigned ClassID = Mips::CCRRegClassID;
483     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
484   }
485
486   /// Coerce the register to HWRegs and return the real register for the
487   /// current target.
488   unsigned getHWRegsReg() const {
489     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
490     unsigned ClassID = Mips::HWRegsRegClassID;
491     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
492   }
493
494 public:
495   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
496     // Add as immediate when possible.  Null MCExpr = 0.
497     if (!Expr)
498       Inst.addOperand(MCOperand::CreateImm(0));
499     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
500       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
501     else
502       Inst.addOperand(MCOperand::CreateExpr(Expr));
503   }
504
505   void addRegOperands(MCInst &Inst, unsigned N) const {
506     llvm_unreachable("Use a custom parser instead");
507   }
508
509   /// Render the operand to an MCInst as a GPR32
510   /// Asserts if the wrong number of operands are requested, or the operand
511   /// is not a k_RegisterIndex compatible with RegKind_GPR
512   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
513     assert(N == 1 && "Invalid number of operands!");
514     Inst.addOperand(MCOperand::CreateReg(getGPR32Reg()));
515   }
516
517   /// Render the operand to an MCInst as a GPR64
518   /// Asserts if the wrong number of operands are requested, or the operand
519   /// is not a k_RegisterIndex compatible with RegKind_GPR
520   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
521     assert(N == 1 && "Invalid number of operands!");
522     Inst.addOperand(MCOperand::CreateReg(getGPR64Reg()));
523   }
524
525   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
526     assert(N == 1 && "Invalid number of operands!");
527     Inst.addOperand(MCOperand::CreateReg(getAFGR64Reg()));
528   }
529
530   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
531     assert(N == 1 && "Invalid number of operands!");
532     Inst.addOperand(MCOperand::CreateReg(getFGR64Reg()));
533   }
534
535   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
536     assert(N == 1 && "Invalid number of operands!");
537     Inst.addOperand(MCOperand::CreateReg(getFGR32Reg()));
538   }
539
540   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
541     assert(N == 1 && "Invalid number of operands!");
542     Inst.addOperand(MCOperand::CreateReg(getFGRH32Reg()));
543   }
544
545   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
546     assert(N == 1 && "Invalid number of operands!");
547     Inst.addOperand(MCOperand::CreateReg(getFCCReg()));
548   }
549
550   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
551     assert(N == 1 && "Invalid number of operands!");
552     Inst.addOperand(MCOperand::CreateReg(getMSA128Reg()));
553   }
554
555   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
556     assert(N == 1 && "Invalid number of operands!");
557     Inst.addOperand(MCOperand::CreateReg(getMSACtrlReg()));
558   }
559
560   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
561     assert(N == 1 && "Invalid number of operands!");
562     Inst.addOperand(MCOperand::CreateReg(getCOP2Reg()));
563   }
564
565   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
566     assert(N == 1 && "Invalid number of operands!");
567     Inst.addOperand(MCOperand::CreateReg(getCOP3Reg()));
568   }
569
570   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
571     assert(N == 1 && "Invalid number of operands!");
572     Inst.addOperand(MCOperand::CreateReg(getACC64DSPReg()));
573   }
574
575   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
576     assert(N == 1 && "Invalid number of operands!");
577     Inst.addOperand(MCOperand::CreateReg(getHI32DSPReg()));
578   }
579
580   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
581     assert(N == 1 && "Invalid number of operands!");
582     Inst.addOperand(MCOperand::CreateReg(getLO32DSPReg()));
583   }
584
585   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
586     assert(N == 1 && "Invalid number of operands!");
587     Inst.addOperand(MCOperand::CreateReg(getCCRReg()));
588   }
589
590   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
591     assert(N == 1 && "Invalid number of operands!");
592     Inst.addOperand(MCOperand::CreateReg(getHWRegsReg()));
593   }
594
595   void addImmOperands(MCInst &Inst, unsigned N) const {
596     assert(N == 1 && "Invalid number of operands!");
597     const MCExpr *Expr = getImm();
598     addExpr(Inst, Expr);
599   }
600
601   void addMemOperands(MCInst &Inst, unsigned N) const {
602     assert(N == 2 && "Invalid number of operands!");
603
604     Inst.addOperand(MCOperand::CreateReg(getMemBase()->getGPR32Reg()));
605
606     const MCExpr *Expr = getMemOff();
607     addExpr(Inst, Expr);
608   }
609
610   bool isReg() const override {
611     // As a special case until we sort out the definition of div/divu, pretend
612     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
613     if (isGPRAsmReg() && RegIdx.Index == 0)
614       return true;
615
616     return Kind == k_PhysRegister;
617   }
618   bool isRegIdx() const { return Kind == k_RegisterIndex; }
619   bool isImm() const override { return Kind == k_Immediate; }
620   bool isConstantImm() const {
621     return isImm() && dyn_cast<MCConstantExpr>(getImm());
622   }
623   bool isToken() const override {
624     // Note: It's not possible to pretend that other operand kinds are tokens.
625     // The matcher emitter checks tokens first.
626     return Kind == k_Token;
627   }
628   bool isMem() const override { return Kind == k_Memory; }
629   bool isConstantMemOff() const {
630     return isMem() && dyn_cast<MCConstantExpr>(getMemOff());
631   }
632   template <unsigned Bits> bool isMemWithSimmOffset() const {
633     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff());
634   }
635   bool isInvNum() const { return Kind == k_Immediate; }
636   bool isLSAImm() const {
637     if (!isConstantImm())
638       return false;
639     int64_t Val = getConstantImm();
640     return 1 <= Val && Val <= 4;
641   }
642
643   StringRef getToken() const {
644     assert(Kind == k_Token && "Invalid access!");
645     return StringRef(Tok.Data, Tok.Length);
646   }
647
648   unsigned getReg() const override {
649     // As a special case until we sort out the definition of div/divu, pretend
650     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
651     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
652         RegIdx.Kind & RegKind_GPR)
653       return getGPR32Reg(); // FIXME: GPR64 too
654
655     assert(Kind == k_PhysRegister && "Invalid access!");
656     return PhysReg.Num;
657   }
658
659   const MCExpr *getImm() const {
660     assert((Kind == k_Immediate) && "Invalid access!");
661     return Imm.Val;
662   }
663
664   int64_t getConstantImm() const {
665     const MCExpr *Val = getImm();
666     return static_cast<const MCConstantExpr *>(Val)->getValue();
667   }
668
669   MipsOperand *getMemBase() const {
670     assert((Kind == k_Memory) && "Invalid access!");
671     return Mem.Base;
672   }
673
674   const MCExpr *getMemOff() const {
675     assert((Kind == k_Memory) && "Invalid access!");
676     return Mem.Off;
677   }
678
679   int64_t getConstantMemOff() const {
680     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
681   }
682
683   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
684                                                   MipsAsmParser &Parser) {
685     auto Op = make_unique<MipsOperand>(k_Token, Parser);
686     Op->Tok.Data = Str.data();
687     Op->Tok.Length = Str.size();
688     Op->StartLoc = S;
689     Op->EndLoc = S;
690     return Op;
691   }
692
693   /// Create a numeric register (e.g. $1). The exact register remains
694   /// unresolved until an instruction successfully matches
695   static std::unique_ptr<MipsOperand>
696   CreateNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
697                    SMLoc E, MipsAsmParser &Parser) {
698     DEBUG(dbgs() << "CreateNumericReg(" << Index << ", ...)\n");
699     return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
700   }
701
702   /// Create a register that is definitely a GPR.
703   /// This is typically only used for named registers such as $gp.
704   static std::unique_ptr<MipsOperand>
705   CreateGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
706                MipsAsmParser &Parser) {
707     return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
708   }
709
710   /// Create a register that is definitely a FGR.
711   /// This is typically only used for named registers such as $f0.
712   static std::unique_ptr<MipsOperand>
713   CreateFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
714                MipsAsmParser &Parser) {
715     return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
716   }
717
718   /// Create a register that is definitely an FCC.
719   /// This is typically only used for named registers such as $fcc0.
720   static std::unique_ptr<MipsOperand>
721   CreateFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
722                MipsAsmParser &Parser) {
723     return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
724   }
725
726   /// Create a register that is definitely an ACC.
727   /// This is typically only used for named registers such as $ac0.
728   static std::unique_ptr<MipsOperand>
729   CreateACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
730                MipsAsmParser &Parser) {
731     return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
732   }
733
734   /// Create a register that is definitely an MSA128.
735   /// This is typically only used for named registers such as $w0.
736   static std::unique_ptr<MipsOperand>
737   CreateMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
738                   SMLoc E, MipsAsmParser &Parser) {
739     return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
740   }
741
742   /// Create a register that is definitely an MSACtrl.
743   /// This is typically only used for named registers such as $msaaccess.
744   static std::unique_ptr<MipsOperand>
745   CreateMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
746                    SMLoc E, MipsAsmParser &Parser) {
747     return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
748   }
749
750   static std::unique_ptr<MipsOperand>
751   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
752     auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
753     Op->Imm.Val = Val;
754     Op->StartLoc = S;
755     Op->EndLoc = E;
756     return Op;
757   }
758
759   static std::unique_ptr<MipsOperand>
760   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
761             SMLoc E, MipsAsmParser &Parser) {
762     auto Op = make_unique<MipsOperand>(k_Memory, Parser);
763     Op->Mem.Base = Base.release();
764     Op->Mem.Off = Off;
765     Op->StartLoc = S;
766     Op->EndLoc = E;
767     return Op;
768   }
769
770   bool isGPRAsmReg() const {
771     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
772   }
773   bool isFGRAsmReg() const {
774     // AFGR64 is $0-$15 but we handle this in getAFGR64()
775     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
776   }
777   bool isHWRegsAsmReg() const {
778     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
779   }
780   bool isCCRAsmReg() const {
781     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
782   }
783   bool isFCCAsmReg() const {
784     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
785       return false;
786     if (!AsmParser.hasEightFccRegisters())
787       return RegIdx.Index == 0;
788     return RegIdx.Index <= 7;
789   }
790   bool isACCAsmReg() const {
791     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
792   }
793   bool isCOP2AsmReg() const {
794     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
795   }
796   bool isCOP3AsmReg() const {
797     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
798   }
799   bool isMSA128AsmReg() const {
800     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
801   }
802   bool isMSACtrlAsmReg() const {
803     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
804   }
805
806   /// getStartLoc - Get the location of the first token of this operand.
807   SMLoc getStartLoc() const override { return StartLoc; }
808   /// getEndLoc - Get the location of the last token of this operand.
809   SMLoc getEndLoc() const override { return EndLoc; }
810
811   virtual ~MipsOperand() {
812     switch (Kind) {
813     case k_Immediate:
814       break;
815     case k_Memory:
816       delete Mem.Base;
817       break;
818     case k_PhysRegister:
819     case k_RegisterIndex:
820     case k_Token:
821       break;
822     }
823   }
824
825   void print(raw_ostream &OS) const override {
826     switch (Kind) {
827     case k_Immediate:
828       OS << "Imm<";
829       Imm.Val->print(OS);
830       OS << ">";
831       break;
832     case k_Memory:
833       OS << "Mem<";
834       Mem.Base->print(OS);
835       OS << ", ";
836       Mem.Off->print(OS);
837       OS << ">";
838       break;
839     case k_PhysRegister:
840       OS << "PhysReg<" << PhysReg.Num << ">";
841       break;
842     case k_RegisterIndex:
843       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
844       break;
845     case k_Token:
846       OS << Tok.Data;
847       break;
848     }
849   }
850 }; // class MipsOperand
851 } // namespace
852
853 namespace llvm {
854 extern const MCInstrDesc MipsInsts[];
855 }
856 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
857   return MipsInsts[Opcode];
858 }
859
860 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
861                                        SmallVectorImpl<MCInst> &Instructions) {
862   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
863
864   Inst.setLoc(IDLoc);
865
866   if (MCID.isBranch() || MCID.isCall()) {
867     const unsigned Opcode = Inst.getOpcode();
868     MCOperand Offset;
869
870     switch (Opcode) {
871     default:
872       break;
873     case Mips::BEQ:
874     case Mips::BNE:
875     case Mips::BEQ_MM:
876     case Mips::BNE_MM:
877       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
878       Offset = Inst.getOperand(2);
879       if (!Offset.isImm())
880         break; // We'll deal with this situation later on when applying fixups.
881       if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
882         return Error(IDLoc, "branch target out of range");
883       if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
884         return Error(IDLoc, "branch to misaligned address");
885       break;
886     case Mips::BGEZ:
887     case Mips::BGTZ:
888     case Mips::BLEZ:
889     case Mips::BLTZ:
890     case Mips::BGEZAL:
891     case Mips::BLTZAL:
892     case Mips::BC1F:
893     case Mips::BC1T:
894     case Mips::BGEZ_MM:
895     case Mips::BGTZ_MM:
896     case Mips::BLEZ_MM:
897     case Mips::BLTZ_MM:
898     case Mips::BGEZAL_MM:
899     case Mips::BLTZAL_MM:
900     case Mips::BC1F_MM:
901     case Mips::BC1T_MM:
902       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
903       Offset = Inst.getOperand(1);
904       if (!Offset.isImm())
905         break; // We'll deal with this situation later on when applying fixups.
906       if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
907         return Error(IDLoc, "branch target out of range");
908       if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
909         return Error(IDLoc, "branch to misaligned address");
910       break;
911     }
912   }
913
914   // SSNOP is deprecated on MIPS32r6/MIPS64r6
915   // We still accept it but it is a normal nop.
916   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
917     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
918     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
919                                                       "nop instruction");
920   }
921
922   if (MCID.hasDelaySlot() && Options.isReorder()) {
923     // If this instruction has a delay slot and .set reorder is active,
924     // emit a NOP after it.
925     Instructions.push_back(Inst);
926     MCInst NopInst;
927     NopInst.setOpcode(Mips::SLL);
928     NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
929     NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
930     NopInst.addOperand(MCOperand::CreateImm(0));
931     Instructions.push_back(NopInst);
932     return false;
933   }
934
935   if (MCID.mayLoad() || MCID.mayStore()) {
936     // Check the offset of memory operand, if it is a symbol
937     // reference or immediate we may have to expand instructions.
938     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
939       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
940       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
941           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
942         MCOperand &Op = Inst.getOperand(i);
943         if (Op.isImm()) {
944           int MemOffset = Op.getImm();
945           if (MemOffset < -32768 || MemOffset > 32767) {
946             // Offset can't exceed 16bit value.
947             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
948             return false;
949           }
950         } else if (Op.isExpr()) {
951           const MCExpr *Expr = Op.getExpr();
952           if (Expr->getKind() == MCExpr::SymbolRef) {
953             const MCSymbolRefExpr *SR =
954                 static_cast<const MCSymbolRefExpr *>(Expr);
955             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
956               // Expand symbol.
957               expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
958               return false;
959             }
960           } else if (!isEvaluated(Expr)) {
961             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
962             return false;
963           }
964         }
965       }
966     } // for
967   }   // if load/store
968
969   if (needsExpansion(Inst))
970     expandInstruction(Inst, IDLoc, Instructions);
971   else
972     Instructions.push_back(Inst);
973
974   return false;
975 }
976
977 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
978
979   switch (Inst.getOpcode()) {
980   case Mips::LoadImm32Reg:
981   case Mips::LoadAddr32Imm:
982   case Mips::LoadAddr32Reg:
983     return true;
984   default:
985     return false;
986   }
987 }
988
989 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
990                                       SmallVectorImpl<MCInst> &Instructions) {
991   switch (Inst.getOpcode()) {
992   case Mips::LoadImm32Reg:
993     return expandLoadImm(Inst, IDLoc, Instructions);
994   case Mips::LoadAddr32Imm:
995     return expandLoadAddressImm(Inst, IDLoc, Instructions);
996   case Mips::LoadAddr32Reg:
997     return expandLoadAddressReg(Inst, IDLoc, Instructions);
998   }
999 }
1000
1001 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
1002                                   SmallVectorImpl<MCInst> &Instructions) {
1003   MCInst tmpInst;
1004   const MCOperand &ImmOp = Inst.getOperand(1);
1005   assert(ImmOp.isImm() && "expected immediate operand kind");
1006   const MCOperand &RegOp = Inst.getOperand(0);
1007   assert(RegOp.isReg() && "expected register operand kind");
1008
1009   int ImmValue = ImmOp.getImm();
1010   tmpInst.setLoc(IDLoc);
1011   if (0 <= ImmValue && ImmValue <= 65535) {
1012     // For 0 <= j <= 65535.
1013     // li d,j => ori d,$zero,j
1014     tmpInst.setOpcode(Mips::ORi);
1015     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1016     tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1017     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1018     Instructions.push_back(tmpInst);
1019   } else if (ImmValue < 0 && ImmValue >= -32768) {
1020     // For -32768 <= j < 0.
1021     // li d,j => addiu d,$zero,j
1022     tmpInst.setOpcode(Mips::ADDiu);
1023     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1024     tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1025     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1026     Instructions.push_back(tmpInst);
1027   } else {
1028     // For any other value of j that is representable as a 32-bit integer.
1029     // li d,j => lui d,hi16(j)
1030     //           ori d,d,lo16(j)
1031     tmpInst.setOpcode(Mips::LUi);
1032     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1033     tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1034     Instructions.push_back(tmpInst);
1035     tmpInst.clear();
1036     tmpInst.setOpcode(Mips::ORi);
1037     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1038     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1039     tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1040     tmpInst.setLoc(IDLoc);
1041     Instructions.push_back(tmpInst);
1042   }
1043 }
1044
1045 void
1046 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
1047                                     SmallVectorImpl<MCInst> &Instructions) {
1048   MCInst tmpInst;
1049   const MCOperand &ImmOp = Inst.getOperand(2);
1050   assert(ImmOp.isImm() && "expected immediate operand kind");
1051   const MCOperand &SrcRegOp = Inst.getOperand(1);
1052   assert(SrcRegOp.isReg() && "expected register operand kind");
1053   const MCOperand &DstRegOp = Inst.getOperand(0);
1054   assert(DstRegOp.isReg() && "expected register operand kind");
1055   int ImmValue = ImmOp.getImm();
1056   if (-32768 <= ImmValue && ImmValue <= 65535) {
1057     // For -32768 <= j <= 65535.
1058     // la d,j(s) => addiu d,s,j
1059     tmpInst.setOpcode(Mips::ADDiu);
1060     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1061     tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1062     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1063     Instructions.push_back(tmpInst);
1064   } else {
1065     // For any other value of j that is representable as a 32-bit integer.
1066     // la d,j(s) => lui d,hi16(j)
1067     //              ori d,d,lo16(j)
1068     //              addu d,d,s
1069     tmpInst.setOpcode(Mips::LUi);
1070     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1071     tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1072     Instructions.push_back(tmpInst);
1073     tmpInst.clear();
1074     tmpInst.setOpcode(Mips::ORi);
1075     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1076     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1077     tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1078     Instructions.push_back(tmpInst);
1079     tmpInst.clear();
1080     tmpInst.setOpcode(Mips::ADDu);
1081     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1082     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
1083     tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
1084     Instructions.push_back(tmpInst);
1085   }
1086 }
1087
1088 void
1089 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
1090                                     SmallVectorImpl<MCInst> &Instructions) {
1091   MCInst tmpInst;
1092   const MCOperand &ImmOp = Inst.getOperand(1);
1093   assert(ImmOp.isImm() && "expected immediate operand kind");
1094   const MCOperand &RegOp = Inst.getOperand(0);
1095   assert(RegOp.isReg() && "expected register operand kind");
1096   int ImmValue = ImmOp.getImm();
1097   if (-32768 <= ImmValue && ImmValue <= 65535) {
1098     // For -32768 <= j <= 65535.
1099     // la d,j => addiu d,$zero,j
1100     tmpInst.setOpcode(Mips::ADDiu);
1101     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1102     tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
1103     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
1104     Instructions.push_back(tmpInst);
1105   } else {
1106     // For any other value of j that is representable as a 32-bit integer.
1107     // la d,j => lui d,hi16(j)
1108     //           ori d,d,lo16(j)
1109     tmpInst.setOpcode(Mips::LUi);
1110     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1111     tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
1112     Instructions.push_back(tmpInst);
1113     tmpInst.clear();
1114     tmpInst.setOpcode(Mips::ORi);
1115     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1116     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
1117     tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
1118     Instructions.push_back(tmpInst);
1119   }
1120 }
1121
1122 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
1123                                   SmallVectorImpl<MCInst> &Instructions,
1124                                   bool isLoad, bool isImmOpnd) {
1125   const MCSymbolRefExpr *SR;
1126   MCInst TempInst;
1127   unsigned ImmOffset, HiOffset, LoOffset;
1128   const MCExpr *ExprOffset;
1129   unsigned TmpRegNum;
1130   unsigned AtRegNum = getReg(
1131       (isGP64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
1132   // 1st operand is either the source or destination register.
1133   assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1134   unsigned RegOpNum = Inst.getOperand(0).getReg();
1135   // 2nd operand is the base register.
1136   assert(Inst.getOperand(1).isReg() && "expected register operand kind");
1137   unsigned BaseRegNum = Inst.getOperand(1).getReg();
1138   // 3rd operand is either an immediate or expression.
1139   if (isImmOpnd) {
1140     assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
1141     ImmOffset = Inst.getOperand(2).getImm();
1142     LoOffset = ImmOffset & 0x0000ffff;
1143     HiOffset = (ImmOffset & 0xffff0000) >> 16;
1144     // If msb of LoOffset is 1(negative number) we must increment HiOffset.
1145     if (LoOffset & 0x8000)
1146       HiOffset++;
1147   } else
1148     ExprOffset = Inst.getOperand(2).getExpr();
1149   // All instructions will have the same location.
1150   TempInst.setLoc(IDLoc);
1151   // 1st instruction in expansion is LUi. For load instruction we can use
1152   // the dst register as a temporary if base and dst are different,
1153   // but for stores we must use $at.
1154   TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
1155   TempInst.setOpcode(Mips::LUi);
1156   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1157   if (isImmOpnd)
1158     TempInst.addOperand(MCOperand::CreateImm(HiOffset));
1159   else {
1160     if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1161       SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
1162       const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
1163           SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
1164           getContext());
1165       TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1166     } else {
1167       const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
1168       TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
1169     }
1170   }
1171   // Add the instruction to the list.
1172   Instructions.push_back(TempInst);
1173   // Prepare TempInst for next instruction.
1174   TempInst.clear();
1175   // Add temp register to base.
1176   TempInst.setOpcode(Mips::ADDu);
1177   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1178   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1179   TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
1180   Instructions.push_back(TempInst);
1181   TempInst.clear();
1182   // And finally, create original instruction with low part
1183   // of offset and new base.
1184   TempInst.setOpcode(Inst.getOpcode());
1185   TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
1186   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
1187   if (isImmOpnd)
1188     TempInst.addOperand(MCOperand::CreateImm(LoOffset));
1189   else {
1190     if (ExprOffset->getKind() == MCExpr::SymbolRef) {
1191       const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
1192           SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
1193           getContext());
1194       TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1195     } else {
1196       const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
1197       TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
1198     }
1199   }
1200   Instructions.push_back(TempInst);
1201   TempInst.clear();
1202 }
1203
1204 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1205   // As described by the Mips32r2 spec, the registers Rd and Rs for
1206   // jalr.hb must be different.
1207   unsigned Opcode = Inst.getOpcode();
1208
1209   if (Opcode == Mips::JALR_HB &&
1210       (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()))
1211     return Match_RequiresDifferentSrcAndDst;
1212
1213   return Match_Success;
1214 }
1215
1216 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1217                                             OperandVector &Operands,
1218                                             MCStreamer &Out,
1219                                             unsigned &ErrorInfo,
1220                                             bool MatchingInlineAsm) {
1221
1222   MCInst Inst;
1223   SmallVector<MCInst, 8> Instructions;
1224   unsigned MatchResult =
1225       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
1226
1227   switch (MatchResult) {
1228   default:
1229     break;
1230   case Match_Success: {
1231     if (processInstruction(Inst, IDLoc, Instructions))
1232       return true;
1233     for (unsigned i = 0; i < Instructions.size(); i++)
1234       Out.EmitInstruction(Instructions[i], STI);
1235     return false;
1236   }
1237   case Match_MissingFeature:
1238     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1239     return true;
1240   case Match_InvalidOperand: {
1241     SMLoc ErrorLoc = IDLoc;
1242     if (ErrorInfo != ~0U) {
1243       if (ErrorInfo >= Operands.size())
1244         return Error(IDLoc, "too few operands for instruction");
1245
1246       ErrorLoc = ((MipsOperand &)*Operands[ErrorInfo]).getStartLoc();
1247       if (ErrorLoc == SMLoc())
1248         ErrorLoc = IDLoc;
1249     }
1250
1251     return Error(ErrorLoc, "invalid operand for instruction");
1252   }
1253   case Match_MnemonicFail:
1254     return Error(IDLoc, "invalid instruction");
1255   case Match_RequiresDifferentSrcAndDst:
1256     return Error(IDLoc, "source and destination must be different");
1257   }
1258   return true;
1259 }
1260
1261 void MipsAsmParser::WarnIfAssemblerTemporary(int RegIndex, SMLoc Loc) {
1262   if ((RegIndex != 0) && ((int)Options.getATRegNum() == RegIndex)) {
1263     if (RegIndex == 1)
1264       Warning(Loc, "Used $at without \".set noat\"");
1265     else
1266       Warning(Loc, Twine("Used $") + Twine(RegIndex) + " with \".set at=$" +
1267                        Twine(RegIndex) + "\"");
1268   }
1269 }
1270
1271 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
1272   int CC;
1273
1274   CC = StringSwitch<unsigned>(Name)
1275            .Case("zero", 0)
1276            .Case("at", 1)
1277            .Case("a0", 4)
1278            .Case("a1", 5)
1279            .Case("a2", 6)
1280            .Case("a3", 7)
1281            .Case("v0", 2)
1282            .Case("v1", 3)
1283            .Case("s0", 16)
1284            .Case("s1", 17)
1285            .Case("s2", 18)
1286            .Case("s3", 19)
1287            .Case("s4", 20)
1288            .Case("s5", 21)
1289            .Case("s6", 22)
1290            .Case("s7", 23)
1291            .Case("k0", 26)
1292            .Case("k1", 27)
1293            .Case("gp", 28)
1294            .Case("sp", 29)
1295            .Case("fp", 30)
1296            .Case("s8", 30)
1297            .Case("ra", 31)
1298            .Case("t0", 8)
1299            .Case("t1", 9)
1300            .Case("t2", 10)
1301            .Case("t3", 11)
1302            .Case("t4", 12)
1303            .Case("t5", 13)
1304            .Case("t6", 14)
1305            .Case("t7", 15)
1306            .Case("t8", 24)
1307            .Case("t9", 25)
1308            .Default(-1);
1309
1310   if (isN32() || isN64()) {
1311     // Although SGI documentation just cuts out t0-t3 for n32/n64,
1312     // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
1313     // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
1314     if (8 <= CC && CC <= 11)
1315       CC += 4;
1316
1317     if (CC == -1)
1318       CC = StringSwitch<unsigned>(Name)
1319                .Case("a4", 8)
1320                .Case("a5", 9)
1321                .Case("a6", 10)
1322                .Case("a7", 11)
1323                .Case("kt0", 26)
1324                .Case("kt1", 27)
1325                .Default(-1);
1326   }
1327
1328   return CC;
1329 }
1330
1331 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
1332
1333   if (Name[0] == 'f') {
1334     StringRef NumString = Name.substr(1);
1335     unsigned IntVal;
1336     if (NumString.getAsInteger(10, IntVal))
1337       return -1;     // This is not an integer.
1338     if (IntVal > 31) // Maximum index for fpu register.
1339       return -1;
1340     return IntVal;
1341   }
1342   return -1;
1343 }
1344
1345 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1346
1347   if (Name.startswith("fcc")) {
1348     StringRef NumString = Name.substr(3);
1349     unsigned IntVal;
1350     if (NumString.getAsInteger(10, IntVal))
1351       return -1;    // This is not an integer.
1352     if (IntVal > 7) // There are only 8 fcc registers.
1353       return -1;
1354     return IntVal;
1355   }
1356   return -1;
1357 }
1358
1359 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1360
1361   if (Name.startswith("ac")) {
1362     StringRef NumString = Name.substr(2);
1363     unsigned IntVal;
1364     if (NumString.getAsInteger(10, IntVal))
1365       return -1;    // This is not an integer.
1366     if (IntVal > 3) // There are only 3 acc registers.
1367       return -1;
1368     return IntVal;
1369   }
1370   return -1;
1371 }
1372
1373 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1374   unsigned IntVal;
1375
1376   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1377     return -1;
1378
1379   if (IntVal > 31)
1380     return -1;
1381
1382   return IntVal;
1383 }
1384
1385 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1386   int CC;
1387
1388   CC = StringSwitch<unsigned>(Name)
1389            .Case("msair", 0)
1390            .Case("msacsr", 1)
1391            .Case("msaaccess", 2)
1392            .Case("msasave", 3)
1393            .Case("msamodify", 4)
1394            .Case("msarequest", 5)
1395            .Case("msamap", 6)
1396            .Case("msaunmap", 7)
1397            .Default(-1);
1398
1399   return CC;
1400 }
1401
1402 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1403   if (Reg > 31)
1404     return false;
1405
1406   aTReg = Reg;
1407   return true;
1408 }
1409
1410 int MipsAsmParser::getATReg() {
1411   int AT = Options.getATRegNum();
1412   if (AT == 0)
1413     TokError("Pseudo instruction requires $at, which is not available");
1414   return AT;
1415 }
1416
1417 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1418   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1419 }
1420
1421 unsigned MipsAsmParser::getGPR(int RegNo) {
1422   return getReg(isGP64() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1423                 RegNo);
1424 }
1425
1426 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1427   if (RegNum >
1428       getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1429     return -1;
1430
1431   return getReg(RegClass, RegNum);
1432 }
1433
1434 bool MipsAsmParser::ParseOperand(OperandVector &Operands, StringRef Mnemonic) {
1435   DEBUG(dbgs() << "ParseOperand\n");
1436
1437   // Check if the current operand has a custom associated parser, if so, try to
1438   // custom parse the operand, or fallback to the general approach.
1439   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1440   if (ResTy == MatchOperand_Success)
1441     return false;
1442   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1443   // there was a match, but an error occurred, in which case, just return that
1444   // the operand parsing failed.
1445   if (ResTy == MatchOperand_ParseFail)
1446     return true;
1447
1448   DEBUG(dbgs() << ".. Generic Parser\n");
1449
1450   switch (getLexer().getKind()) {
1451   default:
1452     Error(Parser.getTok().getLoc(), "unexpected token in operand");
1453     return true;
1454   case AsmToken::Dollar: {
1455     // Parse the register.
1456     SMLoc S = Parser.getTok().getLoc();
1457
1458     // Almost all registers have been parsed by custom parsers. There is only
1459     // one exception to this. $zero (and it's alias $0) will reach this point
1460     // for div, divu, and similar instructions because it is not an operand
1461     // to the instruction definition but an explicit register. Special case
1462     // this situation for now.
1463     if (ParseAnyRegister(Operands) != MatchOperand_NoMatch)
1464       return false;
1465
1466     // Maybe it is a symbol reference.
1467     StringRef Identifier;
1468     if (Parser.parseIdentifier(Identifier))
1469       return true;
1470
1471     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1472     MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1473     // Otherwise create a symbol reference.
1474     const MCExpr *Res =
1475         MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1476
1477     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
1478     return false;
1479   }
1480   // Else drop to expression parsing.
1481   case AsmToken::LParen:
1482   case AsmToken::Minus:
1483   case AsmToken::Plus:
1484   case AsmToken::Integer:
1485   case AsmToken::String: {
1486     DEBUG(dbgs() << ".. generic integer\n");
1487     OperandMatchResultTy ResTy = ParseImm(Operands);
1488     return ResTy != MatchOperand_Success;
1489   }
1490   case AsmToken::Percent: {
1491     // It is a symbol reference or constant expression.
1492     const MCExpr *IdVal;
1493     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1494     if (parseRelocOperand(IdVal))
1495       return true;
1496
1497     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1498
1499     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1500     return false;
1501   } // case AsmToken::Percent
1502   } // switch(getLexer().getKind())
1503   return true;
1504 }
1505
1506 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1507                                                StringRef RelocStr) {
1508   const MCExpr *Res;
1509   // Check the type of the expression.
1510   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1511     // It's a constant, evaluate reloc value.
1512     int16_t Val;
1513     switch (getVariantKind(RelocStr)) {
1514     case MCSymbolRefExpr::VK_Mips_ABS_LO:
1515       // Get the 1st 16-bits.
1516       Val = MCE->getValue() & 0xffff;
1517       break;
1518     case MCSymbolRefExpr::VK_Mips_ABS_HI:
1519       // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
1520       // 16 bits being negative.
1521       Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
1522       break;
1523     case MCSymbolRefExpr::VK_Mips_HIGHER:
1524       // Get the 3rd 16-bits.
1525       Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
1526       break;
1527     case MCSymbolRefExpr::VK_Mips_HIGHEST:
1528       // Get the 4th 16-bits.
1529       Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
1530       break;
1531     default:
1532       report_fatal_error("Unsupported reloc value!");
1533     }
1534     return MCConstantExpr::Create(Val, getContext());
1535   }
1536
1537   if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1538     // It's a symbol, create a symbolic expression from the symbol.
1539     StringRef Symbol = MSRE->getSymbol().getName();
1540     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1541     Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1542     return Res;
1543   }
1544
1545   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1546     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1547
1548     // Try to create target expression.
1549     if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
1550       return MipsMCExpr::Create(VK, Expr, getContext());
1551
1552     const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1553     const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1554     Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1555     return Res;
1556   }
1557
1558   if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1559     const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1560     Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1561     return Res;
1562   }
1563   // Just return the original expression.
1564   return Expr;
1565 }
1566
1567 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1568
1569   switch (Expr->getKind()) {
1570   case MCExpr::Constant:
1571     return true;
1572   case MCExpr::SymbolRef:
1573     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1574   case MCExpr::Binary:
1575     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1576       if (!isEvaluated(BE->getLHS()))
1577         return false;
1578       return isEvaluated(BE->getRHS());
1579     }
1580   case MCExpr::Unary:
1581     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1582   case MCExpr::Target:
1583     return true;
1584   }
1585   return false;
1586 }
1587
1588 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1589   Parser.Lex();                          // Eat the % token.
1590   const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1591   if (Tok.isNot(AsmToken::Identifier))
1592     return true;
1593
1594   std::string Str = Tok.getIdentifier().str();
1595
1596   Parser.Lex(); // Eat the identifier.
1597   // Now make an expression from the rest of the operand.
1598   const MCExpr *IdVal;
1599   SMLoc EndLoc;
1600
1601   if (getLexer().getKind() == AsmToken::LParen) {
1602     while (1) {
1603       Parser.Lex(); // Eat the '(' token.
1604       if (getLexer().getKind() == AsmToken::Percent) {
1605         Parser.Lex(); // Eat the % token.
1606         const AsmToken &nextTok = Parser.getTok();
1607         if (nextTok.isNot(AsmToken::Identifier))
1608           return true;
1609         Str += "(%";
1610         Str += nextTok.getIdentifier();
1611         Parser.Lex(); // Eat the identifier.
1612         if (getLexer().getKind() != AsmToken::LParen)
1613           return true;
1614       } else
1615         break;
1616     }
1617     if (getParser().parseParenExpression(IdVal, EndLoc))
1618       return true;
1619
1620     while (getLexer().getKind() == AsmToken::RParen)
1621       Parser.Lex(); // Eat the ')' token.
1622
1623   } else
1624     return true; // Parenthesis must follow the relocation operand.
1625
1626   Res = evaluateRelocExpr(IdVal, Str);
1627   return false;
1628 }
1629
1630 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1631                                   SMLoc &EndLoc) {
1632   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
1633   OperandMatchResultTy ResTy = ParseAnyRegister(Operands);
1634   if (ResTy == MatchOperand_Success) {
1635     assert(Operands.size() == 1);
1636     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
1637     StartLoc = Operand.getStartLoc();
1638     EndLoc = Operand.getEndLoc();
1639
1640     // AFAIK, we only support numeric registers and named GPR's in CFI
1641     // directives.
1642     // Don't worry about eating tokens before failing. Using an unrecognised
1643     // register is a parse error.
1644     if (Operand.isGPRAsmReg()) {
1645       // Resolve to GPR32 or GPR64 appropriately.
1646       RegNo = isGP64() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
1647     }
1648
1649     return (RegNo == (unsigned)-1);
1650   }
1651
1652   assert(Operands.size() == 0);
1653   return (RegNo == (unsigned)-1);
1654 }
1655
1656 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1657   SMLoc S;
1658   bool Result = true;
1659
1660   while (getLexer().getKind() == AsmToken::LParen)
1661     Parser.Lex();
1662
1663   switch (getLexer().getKind()) {
1664   default:
1665     return true;
1666   case AsmToken::Identifier:
1667   case AsmToken::LParen:
1668   case AsmToken::Integer:
1669   case AsmToken::Minus:
1670   case AsmToken::Plus:
1671     if (isParenExpr)
1672       Result = getParser().parseParenExpression(Res, S);
1673     else
1674       Result = (getParser().parseExpression(Res));
1675     while (getLexer().getKind() == AsmToken::RParen)
1676       Parser.Lex();
1677     break;
1678   case AsmToken::Percent:
1679     Result = parseRelocOperand(Res);
1680   }
1681   return Result;
1682 }
1683
1684 MipsAsmParser::OperandMatchResultTy
1685 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
1686   DEBUG(dbgs() << "parseMemOperand\n");
1687   const MCExpr *IdVal = nullptr;
1688   SMLoc S;
1689   bool isParenExpr = false;
1690   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1691   // First operand is the offset.
1692   S = Parser.getTok().getLoc();
1693
1694   if (getLexer().getKind() == AsmToken::LParen) {
1695     Parser.Lex();
1696     isParenExpr = true;
1697   }
1698
1699   if (getLexer().getKind() != AsmToken::Dollar) {
1700     if (parseMemOffset(IdVal, isParenExpr))
1701       return MatchOperand_ParseFail;
1702
1703     const AsmToken &Tok = Parser.getTok(); // Get the next token.
1704     if (Tok.isNot(AsmToken::LParen)) {
1705       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
1706       if (Mnemonic.getToken() == "la") {
1707         SMLoc E =
1708             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1709         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1710         return MatchOperand_Success;
1711       }
1712       if (Tok.is(AsmToken::EndOfStatement)) {
1713         SMLoc E =
1714             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1715
1716         // Zero register assumed, add a memory operand with ZERO as its base.
1717         // "Base" will be managed by k_Memory.
1718         auto Base = MipsOperand::CreateGPRReg(0, getContext().getRegisterInfo(),
1719                                               S, E, *this);
1720         Operands.push_back(
1721             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
1722         return MatchOperand_Success;
1723       }
1724       Error(Parser.getTok().getLoc(), "'(' expected");
1725       return MatchOperand_ParseFail;
1726     }
1727
1728     Parser.Lex(); // Eat the '(' token.
1729   }
1730
1731   Res = ParseAnyRegister(Operands);
1732   if (Res != MatchOperand_Success)
1733     return Res;
1734
1735   if (Parser.getTok().isNot(AsmToken::RParen)) {
1736     Error(Parser.getTok().getLoc(), "')' expected");
1737     return MatchOperand_ParseFail;
1738   }
1739
1740   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1741
1742   Parser.Lex(); // Eat the ')' token.
1743
1744   if (!IdVal)
1745     IdVal = MCConstantExpr::Create(0, getContext());
1746
1747   // Replace the register operand with the memory operand.
1748   std::unique_ptr<MipsOperand> op(
1749       static_cast<MipsOperand *>(Operands.back().release()));
1750   // Remove the register from the operands.
1751   // "op" will be managed by k_Memory.
1752   Operands.pop_back();
1753   // Add the memory operand.
1754   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1755     int64_t Imm;
1756     if (IdVal->EvaluateAsAbsolute(Imm))
1757       IdVal = MCConstantExpr::Create(Imm, getContext());
1758     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1759       IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1760                                    getContext());
1761   }
1762
1763   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
1764   return MatchOperand_Success;
1765 }
1766
1767 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
1768
1769   MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
1770   if (Sym) {
1771     SMLoc S = Parser.getTok().getLoc();
1772     const MCExpr *Expr;
1773     if (Sym->isVariable())
1774       Expr = Sym->getVariableValue();
1775     else
1776       return false;
1777     if (Expr->getKind() == MCExpr::SymbolRef) {
1778       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
1779       const StringRef DefSymbol = Ref->getSymbol().getName();
1780       if (DefSymbol.startswith("$")) {
1781         OperandMatchResultTy ResTy =
1782             MatchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
1783         if (ResTy == MatchOperand_Success) {
1784           Parser.Lex();
1785           return true;
1786         } else if (ResTy == MatchOperand_ParseFail)
1787           llvm_unreachable("Should never ParseFail");
1788         return false;
1789       }
1790     } else if (Expr->getKind() == MCExpr::Constant) {
1791       Parser.Lex();
1792       const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
1793       Operands.push_back(
1794           MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
1795       return true;
1796     }
1797   }
1798   return false;
1799 }
1800
1801 MipsAsmParser::OperandMatchResultTy
1802 MipsAsmParser::MatchAnyRegisterNameWithoutDollar(OperandVector &Operands,
1803                                                  StringRef Identifier,
1804                                                  SMLoc S) {
1805   int Index = matchCPURegisterName(Identifier);
1806   if (Index != -1) {
1807     Operands.push_back(MipsOperand::CreateGPRReg(
1808         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1809     return MatchOperand_Success;
1810   }
1811
1812   Index = matchFPURegisterName(Identifier);
1813   if (Index != -1) {
1814     Operands.push_back(MipsOperand::CreateFGRReg(
1815         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1816     return MatchOperand_Success;
1817   }
1818
1819   Index = matchFCCRegisterName(Identifier);
1820   if (Index != -1) {
1821     Operands.push_back(MipsOperand::CreateFCCReg(
1822         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1823     return MatchOperand_Success;
1824   }
1825
1826   Index = matchACRegisterName(Identifier);
1827   if (Index != -1) {
1828     Operands.push_back(MipsOperand::CreateACCReg(
1829         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1830     return MatchOperand_Success;
1831   }
1832
1833   Index = matchMSA128RegisterName(Identifier);
1834   if (Index != -1) {
1835     Operands.push_back(MipsOperand::CreateMSA128Reg(
1836         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1837     return MatchOperand_Success;
1838   }
1839
1840   Index = matchMSA128CtrlRegisterName(Identifier);
1841   if (Index != -1) {
1842     Operands.push_back(MipsOperand::CreateMSACtrlReg(
1843         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
1844     return MatchOperand_Success;
1845   }
1846
1847   return MatchOperand_NoMatch;
1848 }
1849
1850 MipsAsmParser::OperandMatchResultTy
1851 MipsAsmParser::MatchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
1852   auto Token = Parser.getLexer().peekTok(false);
1853
1854   if (Token.is(AsmToken::Identifier)) {
1855     DEBUG(dbgs() << ".. identifier\n");
1856     StringRef Identifier = Token.getIdentifier();
1857     OperandMatchResultTy ResTy =
1858         MatchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
1859     return ResTy;
1860   } else if (Token.is(AsmToken::Integer)) {
1861     DEBUG(dbgs() << ".. integer\n");
1862     Operands.push_back(MipsOperand::CreateNumericReg(
1863         Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
1864         *this));
1865     return MatchOperand_Success;
1866   }
1867
1868   DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
1869
1870   return MatchOperand_NoMatch;
1871 }
1872
1873 MipsAsmParser::OperandMatchResultTy
1874 MipsAsmParser::ParseAnyRegister(OperandVector &Operands) {
1875   DEBUG(dbgs() << "ParseAnyRegister\n");
1876
1877   auto Token = Parser.getTok();
1878
1879   SMLoc S = Token.getLoc();
1880
1881   if (Token.isNot(AsmToken::Dollar)) {
1882     DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
1883     if (Token.is(AsmToken::Identifier)) {
1884       if (searchSymbolAlias(Operands))
1885         return MatchOperand_Success;
1886     }
1887     DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
1888     return MatchOperand_NoMatch;
1889   }
1890   DEBUG(dbgs() << ".. $\n");
1891
1892   OperandMatchResultTy ResTy = MatchAnyRegisterWithoutDollar(Operands, S);
1893   if (ResTy == MatchOperand_Success) {
1894     Parser.Lex(); // $
1895     Parser.Lex(); // identifier
1896   }
1897   return ResTy;
1898 }
1899
1900 MipsAsmParser::OperandMatchResultTy
1901 MipsAsmParser::ParseImm(OperandVector &Operands) {
1902   switch (getLexer().getKind()) {
1903   default:
1904     return MatchOperand_NoMatch;
1905   case AsmToken::LParen:
1906   case AsmToken::Minus:
1907   case AsmToken::Plus:
1908   case AsmToken::Integer:
1909   case AsmToken::String:
1910     break;
1911   }
1912
1913   const MCExpr *IdVal;
1914   SMLoc S = Parser.getTok().getLoc();
1915   if (getParser().parseExpression(IdVal))
1916     return MatchOperand_ParseFail;
1917
1918   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1919   Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
1920   return MatchOperand_Success;
1921 }
1922
1923 MipsAsmParser::OperandMatchResultTy
1924 MipsAsmParser::ParseJumpTarget(OperandVector &Operands) {
1925   DEBUG(dbgs() << "ParseJumpTarget\n");
1926
1927   SMLoc S = getLexer().getLoc();
1928
1929   // Integers and expressions are acceptable
1930   OperandMatchResultTy ResTy = ParseImm(Operands);
1931   if (ResTy != MatchOperand_NoMatch)
1932     return ResTy;
1933
1934   // Registers are a valid target and have priority over symbols.
1935   ResTy = ParseAnyRegister(Operands);
1936   if (ResTy != MatchOperand_NoMatch)
1937     return ResTy;
1938
1939   const MCExpr *Expr = nullptr;
1940   if (Parser.parseExpression(Expr)) {
1941     // We have no way of knowing if a symbol was consumed so we must ParseFail
1942     return MatchOperand_ParseFail;
1943   }
1944   Operands.push_back(
1945       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
1946   return MatchOperand_Success;
1947 }
1948
1949 MipsAsmParser::OperandMatchResultTy
1950 MipsAsmParser::parseInvNum(OperandVector &Operands) {
1951   const MCExpr *IdVal;
1952   // If the first token is '$' we may have register operand.
1953   if (Parser.getTok().is(AsmToken::Dollar))
1954     return MatchOperand_NoMatch;
1955   SMLoc S = Parser.getTok().getLoc();
1956   if (getParser().parseExpression(IdVal))
1957     return MatchOperand_ParseFail;
1958   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
1959   assert(MCE && "Unexpected MCExpr type.");
1960   int64_t Val = MCE->getValue();
1961   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1962   Operands.push_back(MipsOperand::CreateImm(
1963       MCConstantExpr::Create(0 - Val, getContext()), S, E, *this));
1964   return MatchOperand_Success;
1965 }
1966
1967 MipsAsmParser::OperandMatchResultTy
1968 MipsAsmParser::ParseLSAImm(OperandVector &Operands) {
1969   switch (getLexer().getKind()) {
1970   default:
1971     return MatchOperand_NoMatch;
1972   case AsmToken::LParen:
1973   case AsmToken::Plus:
1974   case AsmToken::Minus:
1975   case AsmToken::Integer:
1976     break;
1977   }
1978
1979   const MCExpr *Expr;
1980   SMLoc S = Parser.getTok().getLoc();
1981
1982   if (getParser().parseExpression(Expr))
1983     return MatchOperand_ParseFail;
1984
1985   int64_t Val;
1986   if (!Expr->EvaluateAsAbsolute(Val)) {
1987     Error(S, "expected immediate value");
1988     return MatchOperand_ParseFail;
1989   }
1990
1991   // The LSA instruction allows a 2-bit unsigned immediate. For this reason
1992   // and because the CPU always adds one to the immediate field, the allowed
1993   // range becomes 1..4. We'll only check the range here and will deal
1994   // with the addition/subtraction when actually decoding/encoding
1995   // the instruction.
1996   if (Val < 1 || Val > 4) {
1997     Error(S, "immediate not in range (1..4)");
1998     return MatchOperand_ParseFail;
1999   }
2000
2001   Operands.push_back(
2002       MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
2003   return MatchOperand_Success;
2004 }
2005
2006 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
2007
2008   MCSymbolRefExpr::VariantKind VK =
2009       StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
2010           .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
2011           .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
2012           .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
2013           .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
2014           .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
2015           .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
2016           .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
2017           .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
2018           .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
2019           .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
2020           .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
2021           .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
2022           .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
2023           .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
2024           .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
2025           .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
2026           .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
2027           .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
2028           .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
2029           .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
2030           .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
2031           .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
2032           .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
2033           .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
2034           .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
2035           .Default(MCSymbolRefExpr::VK_None);
2036
2037   assert(VK != MCSymbolRefExpr::VK_None);
2038
2039   return VK;
2040 }
2041
2042 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
2043 /// either this.
2044 /// ::= '(', register, ')'
2045 /// handle it before we iterate so we don't get tripped up by the lack of
2046 /// a comma.
2047 bool MipsAsmParser::ParseParenSuffix(StringRef Name, OperandVector &Operands) {
2048   if (getLexer().is(AsmToken::LParen)) {
2049     Operands.push_back(
2050         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
2051     Parser.Lex();
2052     if (ParseOperand(Operands, Name)) {
2053       SMLoc Loc = getLexer().getLoc();
2054       Parser.eatToEndOfStatement();
2055       return Error(Loc, "unexpected token in argument list");
2056     }
2057     if (Parser.getTok().isNot(AsmToken::RParen)) {
2058       SMLoc Loc = getLexer().getLoc();
2059       Parser.eatToEndOfStatement();
2060       return Error(Loc, "unexpected token, expected ')'");
2061     }
2062     Operands.push_back(
2063         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
2064     Parser.Lex();
2065   }
2066   return false;
2067 }
2068
2069 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
2070 /// either one of these.
2071 /// ::= '[', register, ']'
2072 /// ::= '[', integer, ']'
2073 /// handle it before we iterate so we don't get tripped up by the lack of
2074 /// a comma.
2075 bool MipsAsmParser::ParseBracketSuffix(StringRef Name,
2076                                        OperandVector &Operands) {
2077   if (getLexer().is(AsmToken::LBrac)) {
2078     Operands.push_back(
2079         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
2080     Parser.Lex();
2081     if (ParseOperand(Operands, Name)) {
2082       SMLoc Loc = getLexer().getLoc();
2083       Parser.eatToEndOfStatement();
2084       return Error(Loc, "unexpected token in argument list");
2085     }
2086     if (Parser.getTok().isNot(AsmToken::RBrac)) {
2087       SMLoc Loc = getLexer().getLoc();
2088       Parser.eatToEndOfStatement();
2089       return Error(Loc, "unexpected token, expected ']'");
2090     }
2091     Operands.push_back(
2092         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
2093     Parser.Lex();
2094   }
2095   return false;
2096 }
2097
2098 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2099                                      SMLoc NameLoc, OperandVector &Operands) {
2100   DEBUG(dbgs() << "ParseInstruction\n");
2101   // Check if we have valid mnemonic
2102   if (!mnemonicIsValid(Name, 0)) {
2103     Parser.eatToEndOfStatement();
2104     return Error(NameLoc, "Unknown instruction");
2105   }
2106   // First operand in MCInst is instruction mnemonic.
2107   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
2108
2109   // Read the remaining operands.
2110   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2111     // Read the first operand.
2112     if (ParseOperand(Operands, Name)) {
2113       SMLoc Loc = getLexer().getLoc();
2114       Parser.eatToEndOfStatement();
2115       return Error(Loc, "unexpected token in argument list");
2116     }
2117     if (getLexer().is(AsmToken::LBrac) && ParseBracketSuffix(Name, Operands))
2118       return true;
2119     // AFAIK, parenthesis suffixes are never on the first operand
2120
2121     while (getLexer().is(AsmToken::Comma)) {
2122       Parser.Lex(); // Eat the comma.
2123       // Parse and remember the operand.
2124       if (ParseOperand(Operands, Name)) {
2125         SMLoc Loc = getLexer().getLoc();
2126         Parser.eatToEndOfStatement();
2127         return Error(Loc, "unexpected token in argument list");
2128       }
2129       // Parse bracket and parenthesis suffixes before we iterate
2130       if (getLexer().is(AsmToken::LBrac)) {
2131         if (ParseBracketSuffix(Name, Operands))
2132           return true;
2133       } else if (getLexer().is(AsmToken::LParen) &&
2134                  ParseParenSuffix(Name, Operands))
2135         return true;
2136     }
2137   }
2138   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2139     SMLoc Loc = getLexer().getLoc();
2140     Parser.eatToEndOfStatement();
2141     return Error(Loc, "unexpected token in argument list");
2142   }
2143   Parser.Lex(); // Consume the EndOfStatement.
2144   return false;
2145 }
2146
2147 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2148   SMLoc Loc = getLexer().getLoc();
2149   Parser.eatToEndOfStatement();
2150   return Error(Loc, ErrorMsg);
2151 }
2152
2153 bool MipsAsmParser::reportParseError(SMLoc Loc, StringRef ErrorMsg) {
2154   return Error(Loc, ErrorMsg);
2155 }
2156
2157 bool MipsAsmParser::parseSetNoAtDirective() {
2158   // Line should look like: ".set noat".
2159   // set at reg to 0.
2160   Options.setATReg(0);
2161   // eat noat
2162   Parser.Lex();
2163   // If this is not the end of the statement, report an error.
2164   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2165     reportParseError("unexpected token in statement");
2166     return false;
2167   }
2168   Parser.Lex(); // Consume the EndOfStatement.
2169   return false;
2170 }
2171
2172 bool MipsAsmParser::parseSetAtDirective() {
2173   // Line can be .set at - defaults to $1
2174   // or .set at=$reg
2175   int AtRegNo;
2176   getParser().Lex();
2177   if (getLexer().is(AsmToken::EndOfStatement)) {
2178     Options.setATReg(1);
2179     Parser.Lex(); // Consume the EndOfStatement.
2180     return false;
2181   } else if (getLexer().is(AsmToken::Equal)) {
2182     getParser().Lex(); // Eat the '='.
2183     if (getLexer().isNot(AsmToken::Dollar)) {
2184       reportParseError("unexpected token in statement");
2185       return false;
2186     }
2187     Parser.Lex(); // Eat the '$'.
2188     const AsmToken &Reg = Parser.getTok();
2189     if (Reg.is(AsmToken::Identifier)) {
2190       AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2191     } else if (Reg.is(AsmToken::Integer)) {
2192       AtRegNo = Reg.getIntVal();
2193     } else {
2194       reportParseError("unexpected token in statement");
2195       return false;
2196     }
2197
2198     if (AtRegNo < 0 || AtRegNo > 31) {
2199       reportParseError("unexpected token in statement");
2200       return false;
2201     }
2202
2203     if (!Options.setATReg(AtRegNo)) {
2204       reportParseError("unexpected token in statement");
2205       return false;
2206     }
2207     getParser().Lex(); // Eat the register.
2208
2209     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2210       reportParseError("unexpected token in statement");
2211       return false;
2212     }
2213     Parser.Lex(); // Consume the EndOfStatement.
2214     return false;
2215   } else {
2216     reportParseError("unexpected token in statement");
2217     return false;
2218   }
2219 }
2220
2221 bool MipsAsmParser::parseSetReorderDirective() {
2222   Parser.Lex();
2223   // If this is not the end of the statement, report an error.
2224   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2225     reportParseError("unexpected token in statement");
2226     return false;
2227   }
2228   Options.setReorder();
2229   getTargetStreamer().emitDirectiveSetReorder();
2230   Parser.Lex(); // Consume the EndOfStatement.
2231   return false;
2232 }
2233
2234 bool MipsAsmParser::parseSetNoReorderDirective() {
2235   Parser.Lex();
2236   // If this is not the end of the statement, report an error.
2237   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238     reportParseError("unexpected token in statement");
2239     return false;
2240   }
2241   Options.setNoreorder();
2242   getTargetStreamer().emitDirectiveSetNoReorder();
2243   Parser.Lex(); // Consume the EndOfStatement.
2244   return false;
2245 }
2246
2247 bool MipsAsmParser::parseSetMacroDirective() {
2248   Parser.Lex();
2249   // If this is not the end of the statement, report an error.
2250   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2251     reportParseError("unexpected token in statement");
2252     return false;
2253   }
2254   Options.setMacro();
2255   Parser.Lex(); // Consume the EndOfStatement.
2256   return false;
2257 }
2258
2259 bool MipsAsmParser::parseSetNoMacroDirective() {
2260   Parser.Lex();
2261   // If this is not the end of the statement, report an error.
2262   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2263     reportParseError("`noreorder' must be set before `nomacro'");
2264     return false;
2265   }
2266   if (Options.isReorder()) {
2267     reportParseError("`noreorder' must be set before `nomacro'");
2268     return false;
2269   }
2270   Options.setNomacro();
2271   Parser.Lex(); // Consume the EndOfStatement.
2272   return false;
2273 }
2274
2275 bool MipsAsmParser::parseSetNoMips16Directive() {
2276   Parser.Lex();
2277   // If this is not the end of the statement, report an error.
2278   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2279     reportParseError("unexpected token in statement");
2280     return false;
2281   }
2282   // For now do nothing.
2283   Parser.Lex(); // Consume the EndOfStatement.
2284   return false;
2285 }
2286
2287 bool MipsAsmParser::parseSetAssignment() {
2288   StringRef Name;
2289   const MCExpr *Value;
2290
2291   if (Parser.parseIdentifier(Name))
2292     reportParseError("expected identifier after .set");
2293
2294   if (getLexer().isNot(AsmToken::Comma))
2295     return reportParseError("unexpected token in .set directive");
2296   Lex(); // Eat comma
2297
2298   if (Parser.parseExpression(Value))
2299     return reportParseError("expected valid expression after comma");
2300
2301   // Check if the Name already exists as a symbol.
2302   MCSymbol *Sym = getContext().LookupSymbol(Name);
2303   if (Sym)
2304     return reportParseError("symbol already defined");
2305   Sym = getContext().GetOrCreateSymbol(Name);
2306   Sym->setVariableValue(Value);
2307
2308   return false;
2309 }
2310
2311 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2312   Parser.Lex();
2313   if (getLexer().isNot(AsmToken::EndOfStatement))
2314     return reportParseError("unexpected token in .set directive");
2315
2316   switch (Feature) {
2317   default:
2318     llvm_unreachable("Unimplemented feature");
2319   case Mips::FeatureDSP:
2320     setFeatureBits(Mips::FeatureDSP, "dsp");
2321     getTargetStreamer().emitDirectiveSetDsp();
2322     break;
2323   case Mips::FeatureMicroMips:
2324     getTargetStreamer().emitDirectiveSetMicroMips();
2325     break;
2326   case Mips::FeatureMips16:
2327     getTargetStreamer().emitDirectiveSetMips16();
2328     break;
2329   case Mips::FeatureMips32r2:
2330     setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2331     getTargetStreamer().emitDirectiveSetMips32R2();
2332     break;
2333   case Mips::FeatureMips64:
2334     setFeatureBits(Mips::FeatureMips64, "mips64");
2335     getTargetStreamer().emitDirectiveSetMips64();
2336     break;
2337   case Mips::FeatureMips64r2:
2338     setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2339     getTargetStreamer().emitDirectiveSetMips64R2();
2340     break;
2341   }
2342   return false;
2343 }
2344
2345 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2346   if (!getLexer().is(AsmToken::Dollar))
2347     return false;
2348
2349   Parser.Lex();
2350
2351   const AsmToken &Reg = Parser.getTok();
2352   if (Reg.is(AsmToken::Identifier)) {
2353     RegNum = matchCPURegisterName(Reg.getIdentifier());
2354   } else if (Reg.is(AsmToken::Integer)) {
2355     RegNum = Reg.getIntVal();
2356   } else {
2357     return false;
2358   }
2359
2360   Parser.Lex();
2361   return true;
2362 }
2363
2364 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2365   if (getLexer().isNot(AsmToken::Comma)) {
2366     SMLoc Loc = getLexer().getLoc();
2367     Parser.eatToEndOfStatement();
2368     return Error(Loc, ErrorStr);
2369   }
2370
2371   Parser.Lex(); // Eat the comma.
2372   return true;
2373 }
2374
2375 bool MipsAsmParser::parseDirectiveCPLoad(SMLoc Loc) {
2376   if (Options.isReorder())
2377     Warning(Loc, ".cpload in reorder section");
2378
2379   // FIXME: Warn if cpload is used in Mips16 mode.
2380
2381   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
2382   OperandMatchResultTy ResTy = ParseAnyRegister(Reg);
2383   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
2384     reportParseError("expected register containing function address");
2385     return false;
2386   }
2387
2388   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
2389   if (!RegOpnd.isGPRAsmReg()) {
2390     reportParseError(RegOpnd.getStartLoc(), "invalid register");
2391     return false;
2392   }
2393
2394   getTargetStreamer().emitDirectiveCpload(RegOpnd.getGPR32Reg());
2395   return false;
2396 }
2397
2398 bool MipsAsmParser::parseDirectiveCPSetup() {
2399   unsigned FuncReg;
2400   unsigned Save;
2401   bool SaveIsReg = true;
2402
2403   if (!parseRegister(FuncReg))
2404     return reportParseError("expected register containing function address");
2405   FuncReg = getGPR(FuncReg);
2406
2407   if (!eatComma("expected comma parsing directive"))
2408     return true;
2409
2410   if (!parseRegister(Save)) {
2411     const AsmToken &Tok = Parser.getTok();
2412     if (Tok.is(AsmToken::Integer)) {
2413       Save = Tok.getIntVal();
2414       SaveIsReg = false;
2415       Parser.Lex();
2416     } else
2417       return reportParseError("expected save register or stack offset");
2418   } else
2419     Save = getGPR(Save);
2420
2421   if (!eatComma("expected comma parsing directive"))
2422     return true;
2423
2424   StringRef Name;
2425   if (Parser.parseIdentifier(Name))
2426     reportParseError("expected identifier");
2427   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2428
2429   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, *Sym, SaveIsReg);
2430   return false;
2431 }
2432
2433 bool MipsAsmParser::parseDirectiveNaN() {
2434   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2435     const AsmToken &Tok = Parser.getTok();
2436
2437     if (Tok.getString() == "2008") {
2438       Parser.Lex();
2439       getTargetStreamer().emitDirectiveNaN2008();
2440       return false;
2441     } else if (Tok.getString() == "legacy") {
2442       Parser.Lex();
2443       getTargetStreamer().emitDirectiveNaNLegacy();
2444       return false;
2445     }
2446   }
2447   // If we don't recognize the option passed to the .nan
2448   // directive (e.g. no option or unknown option), emit an error.
2449   reportParseError("invalid option in .nan directive");
2450   return false;
2451 }
2452
2453 bool MipsAsmParser::parseDirectiveSet() {
2454
2455   // Get the next token.
2456   const AsmToken &Tok = Parser.getTok();
2457
2458   if (Tok.getString() == "noat") {
2459     return parseSetNoAtDirective();
2460   } else if (Tok.getString() == "at") {
2461     return parseSetAtDirective();
2462   } else if (Tok.getString() == "reorder") {
2463     return parseSetReorderDirective();
2464   } else if (Tok.getString() == "noreorder") {
2465     return parseSetNoReorderDirective();
2466   } else if (Tok.getString() == "macro") {
2467     return parseSetMacroDirective();
2468   } else if (Tok.getString() == "nomacro") {
2469     return parseSetNoMacroDirective();
2470   } else if (Tok.getString() == "mips16") {
2471     return parseSetFeature(Mips::FeatureMips16);
2472   } else if (Tok.getString() == "nomips16") {
2473     return parseSetNoMips16Directive();
2474   } else if (Tok.getString() == "nomicromips") {
2475     getTargetStreamer().emitDirectiveSetNoMicroMips();
2476     Parser.eatToEndOfStatement();
2477     return false;
2478   } else if (Tok.getString() == "micromips") {
2479     return parseSetFeature(Mips::FeatureMicroMips);
2480   } else if (Tok.getString() == "mips32r2") {
2481     return parseSetFeature(Mips::FeatureMips32r2);
2482   } else if (Tok.getString() == "mips64") {
2483     return parseSetFeature(Mips::FeatureMips64);
2484   } else if (Tok.getString() == "mips64r2") {
2485     return parseSetFeature(Mips::FeatureMips64r2);
2486   } else if (Tok.getString() == "dsp") {
2487     return parseSetFeature(Mips::FeatureDSP);
2488   } else {
2489     // It is just an identifier, look for an assignment.
2490     parseSetAssignment();
2491     return false;
2492   }
2493
2494   return true;
2495 }
2496
2497 /// parseDataDirective
2498 ///  ::= .word [ expression (, expression)* ]
2499 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2500   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2501     for (;;) {
2502       const MCExpr *Value;
2503       if (getParser().parseExpression(Value))
2504         return true;
2505
2506       getParser().getStreamer().EmitValue(Value, Size);
2507
2508       if (getLexer().is(AsmToken::EndOfStatement))
2509         break;
2510
2511       // FIXME: Improve diagnostic.
2512       if (getLexer().isNot(AsmToken::Comma))
2513         return Error(L, "unexpected token in directive");
2514       Parser.Lex();
2515     }
2516   }
2517
2518   Parser.Lex();
2519   return false;
2520 }
2521
2522 /// parseDirectiveGpWord
2523 ///  ::= .gpword local_sym
2524 bool MipsAsmParser::parseDirectiveGpWord() {
2525   const MCExpr *Value;
2526   // EmitGPRel32Value requires an expression, so we are using base class
2527   // method to evaluate the expression.
2528   if (getParser().parseExpression(Value))
2529     return true;
2530   getParser().getStreamer().EmitGPRel32Value(Value);
2531
2532   if (getLexer().isNot(AsmToken::EndOfStatement))
2533     return Error(getLexer().getLoc(), "unexpected token in directive");
2534   Parser.Lex(); // Eat EndOfStatement token.
2535   return false;
2536 }
2537
2538 /// parseDirectiveGpDWord
2539 ///  ::= .gpdword local_sym
2540 bool MipsAsmParser::parseDirectiveGpDWord() {
2541   const MCExpr *Value;
2542   // EmitGPRel64Value requires an expression, so we are using base class
2543   // method to evaluate the expression.
2544   if (getParser().parseExpression(Value))
2545     return true;
2546   getParser().getStreamer().EmitGPRel64Value(Value);
2547
2548   if (getLexer().isNot(AsmToken::EndOfStatement))
2549     return Error(getLexer().getLoc(), "unexpected token in directive");
2550   Parser.Lex(); // Eat EndOfStatement token.
2551   return false;
2552 }
2553
2554 bool MipsAsmParser::parseDirectiveOption() {
2555   // Get the option token.
2556   AsmToken Tok = Parser.getTok();
2557   // At the moment only identifiers are supported.
2558   if (Tok.isNot(AsmToken::Identifier)) {
2559     Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2560     Parser.eatToEndOfStatement();
2561     return false;
2562   }
2563
2564   StringRef Option = Tok.getIdentifier();
2565
2566   if (Option == "pic0") {
2567     getTargetStreamer().emitDirectiveOptionPic0();
2568     Parser.Lex();
2569     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2570       Error(Parser.getTok().getLoc(),
2571             "unexpected token in .option pic0 directive");
2572       Parser.eatToEndOfStatement();
2573     }
2574     return false;
2575   }
2576
2577   if (Option == "pic2") {
2578     getTargetStreamer().emitDirectiveOptionPic2();
2579     Parser.Lex();
2580     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2581       Error(Parser.getTok().getLoc(),
2582             "unexpected token in .option pic2 directive");
2583       Parser.eatToEndOfStatement();
2584     }
2585     return false;
2586   }
2587
2588   // Unknown option.
2589   Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2590   Parser.eatToEndOfStatement();
2591   return false;
2592 }
2593
2594 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2595   StringRef IDVal = DirectiveID.getString();
2596
2597   if (IDVal == ".cpload")
2598     return parseDirectiveCPLoad(DirectiveID.getLoc());
2599   if (IDVal == ".dword") {
2600     parseDataDirective(8, DirectiveID.getLoc());
2601     return false;
2602   }
2603
2604   if (IDVal == ".ent") {
2605     // Ignore this directive for now.
2606     Parser.Lex();
2607     return false;
2608   }
2609
2610   if (IDVal == ".end") {
2611     // Ignore this directive for now.
2612     Parser.Lex();
2613     return false;
2614   }
2615
2616   if (IDVal == ".frame") {
2617     // Ignore this directive for now.
2618     Parser.eatToEndOfStatement();
2619     return false;
2620   }
2621
2622   if (IDVal == ".set") {
2623     return parseDirectiveSet();
2624   }
2625
2626   if (IDVal == ".fmask") {
2627     // Ignore this directive for now.
2628     Parser.eatToEndOfStatement();
2629     return false;
2630   }
2631
2632   if (IDVal == ".mask") {
2633     // Ignore this directive for now.
2634     Parser.eatToEndOfStatement();
2635     return false;
2636   }
2637
2638   if (IDVal == ".nan")
2639     return parseDirectiveNaN();
2640
2641   if (IDVal == ".gpword") {
2642     parseDirectiveGpWord();
2643     return false;
2644   }
2645
2646   if (IDVal == ".gpdword") {
2647     parseDirectiveGpDWord();
2648     return false;
2649   }
2650
2651   if (IDVal == ".word") {
2652     parseDataDirective(4, DirectiveID.getLoc());
2653     return false;
2654   }
2655
2656   if (IDVal == ".option")
2657     return parseDirectiveOption();
2658
2659   if (IDVal == ".abicalls") {
2660     getTargetStreamer().emitDirectiveAbiCalls();
2661     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2662       Error(Parser.getTok().getLoc(), "unexpected token in directive");
2663       // Clear line
2664       Parser.eatToEndOfStatement();
2665     }
2666     return false;
2667   }
2668
2669   if (IDVal == ".cpsetup")
2670     return parseDirectiveCPSetup();
2671
2672   return true;
2673 }
2674
2675 extern "C" void LLVMInitializeMipsAsmParser() {
2676   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2677   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2678   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2679   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2680 }
2681
2682 #define GET_REGISTER_MATCHER
2683 #define GET_MATCHER_IMPLEMENTATION
2684 #include "MipsGenAsmMatcher.inc"