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