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