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