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