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