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