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