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