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