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