There are a few places where subtarget features are still
[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/MipsABIInfo.h"
11 #include "MCTargetDesc/MipsMCExpr.h"
12 #include "MCTargetDesc/MipsMCTargetDesc.h"
13 #include "MipsRegisterInfo.h"
14 #include "MipsTargetStreamer.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstBuilder.h"
22 #include "llvm/MC/MCParser/MCAsmLexer.h"
23 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <memory>
34
35 using namespace llvm;
36
37 #define DEBUG_TYPE "mips-asm-parser"
38
39 namespace llvm {
40 class MCInstrInfo;
41 }
42
43 namespace {
44 class MipsAssemblerOptions {
45 public:
46   MipsAssemblerOptions(const FeatureBitset &Features_) :
47     ATReg(1), Reorder(true), Macro(true), Features(Features_) {}
48
49   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
50     ATReg = Opts->getATRegIndex();
51     Reorder = Opts->isReorder();
52     Macro = Opts->isMacro();
53     Features = Opts->getFeatures();
54   }
55
56   unsigned getATRegIndex() const { return ATReg; }
57   bool setATRegIndex(unsigned Reg) {
58     if (Reg > 31)
59       return false;
60
61     ATReg = Reg;
62     return true;
63   }
64
65   bool isReorder() const { return Reorder; }
66   void setReorder() { Reorder = true; }
67   void setNoReorder() { Reorder = false; }
68
69   bool isMacro() const { return Macro; }
70   void setMacro() { Macro = true; }
71   void setNoMacro() { Macro = false; }
72
73   const FeatureBitset &getFeatures() const { return Features; }
74   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
75
76   // Set of features that are either architecture features or referenced
77   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
78   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
79   // The reason we need this mask is explained in the selectArch function.
80   // FIXME: Ideally we would like TableGen to generate this information.
81   static const FeatureBitset AllArchRelatedMask;
82
83 private:
84   unsigned ATReg;
85   bool Reorder;
86   bool Macro;
87   FeatureBitset Features;
88 };
89 }
90
91 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
92     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
93     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
94     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
95     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
96     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
97     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
98     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
99     Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008
100 };
101
102 namespace {
103 class MipsAsmParser : public MCTargetAsmParser {
104   MipsTargetStreamer &getTargetStreamer() {
105     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
106     return static_cast<MipsTargetStreamer &>(TS);
107   }
108
109   MCSubtargetInfo &STI;
110   MipsABIInfo ABI;
111   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
112   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
113                        // nullptr, which indicates that no function is currently
114                        // selected. This usually happens after an '.end func'
115                        // directive.
116   bool IsLittleEndian;
117
118   // Print a warning along with its fix-it message at the given range.
119   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
120                              SMRange Range, bool ShowColors = true);
121
122 #define GET_ASSEMBLER_HEADER
123 #include "MipsGenAsmMatcher.inc"
124
125   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
126
127   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
128                                OperandVector &Operands, MCStreamer &Out,
129                                uint64_t &ErrorInfo,
130                                FeatureBitset &ErrorMissingFeature,
131                                bool MatchingInlineAsm) override;
132
133   /// Parse a register as used in CFI directives
134   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
135
136   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
137
138   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
139
140   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
141                         SMLoc NameLoc, OperandVector &Operands) override;
142
143   bool ParseDirective(AsmToken DirectiveID) override;
144
145   MipsAsmParser::OperandMatchResultTy parseMemOperand(OperandVector &Operands);
146
147   MipsAsmParser::OperandMatchResultTy
148   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
149                                     StringRef Identifier, SMLoc S);
150
151   MipsAsmParser::OperandMatchResultTy
152   matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S);
153
154   MipsAsmParser::OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
155
156   MipsAsmParser::OperandMatchResultTy parseImm(OperandVector &Operands);
157
158   MipsAsmParser::OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
159
160   MipsAsmParser::OperandMatchResultTy parseInvNum(OperandVector &Operands);
161
162   MipsAsmParser::OperandMatchResultTy parseLSAImm(OperandVector &Operands);
163
164   MipsAsmParser::OperandMatchResultTy
165   parseRegisterPair (OperandVector &Operands);
166
167   MipsAsmParser::OperandMatchResultTy
168   parseMovePRegPair(OperandVector &Operands);
169
170   MipsAsmParser::OperandMatchResultTy
171   parseRegisterList (OperandVector  &Operands);
172
173   bool searchSymbolAlias(OperandVector &Operands);
174
175   bool parseOperand(OperandVector &, StringRef Mnemonic);
176
177   bool needsExpansion(MCInst &Inst);
178
179   // Expands assembly pseudo instructions.
180   // Returns false on success, true otherwise.
181   bool expandInstruction(MCInst &Inst, SMLoc IDLoc,
182                          SmallVectorImpl<MCInst> &Instructions);
183
184   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
185                          SmallVectorImpl<MCInst> &Instructions);
186
187   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
188                      bool Is32BitImm, SMLoc IDLoc,
189                      SmallVectorImpl<MCInst> &Instructions);
190
191   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
192                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
193                                SmallVectorImpl<MCInst> &Instructions);
194
195   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
196                      SmallVectorImpl<MCInst> &Instructions);
197
198   bool expandLoadAddressImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
199                             SmallVectorImpl<MCInst> &Instructions);
200
201   bool expandLoadAddressReg(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
202                             SmallVectorImpl<MCInst> &Instructions);
203   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
204                                   SmallVectorImpl<MCInst> &Instructions);
205
206   void expandMemInst(MCInst &Inst, SMLoc IDLoc,
207                      SmallVectorImpl<MCInst> &Instructions, bool isLoad,
208                      bool isImmOpnd);
209
210   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
211                                SmallVectorImpl<MCInst> &Instructions);
212
213   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc,
214                        SmallVectorImpl<MCInst> &Instructions);
215
216   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc,
217                           SmallVectorImpl<MCInst> &Instructions);
218
219   bool expandUlhu(MCInst &Inst, SMLoc IDLoc,
220                   SmallVectorImpl<MCInst> &Instructions);
221
222   bool expandUlw(MCInst &Inst, SMLoc IDLoc,
223                  SmallVectorImpl<MCInst> &Instructions);
224
225   void createNop(bool hasShortDelaySlot, SMLoc IDLoc,
226                  SmallVectorImpl<MCInst> &Instructions);
227
228   void createAddu(unsigned DstReg, unsigned SrcReg, unsigned TrgReg,
229                   bool Is64Bit, SmallVectorImpl<MCInst> &Instructions);
230
231   bool reportParseError(Twine ErrorMsg);
232   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
233
234   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
235   bool parseRelocOperand(const MCExpr *&Res);
236
237   const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
238
239   bool isEvaluated(const MCExpr *Expr);
240   bool parseSetMips0Directive();
241   bool parseSetArchDirective();
242   bool parseSetFeature(uint64_t Feature);
243   bool parseDirectiveCpLoad(SMLoc Loc);
244   bool parseDirectiveCPSetup();
245   bool parseDirectiveNaN();
246   bool parseDirectiveSet();
247   bool parseDirectiveOption();
248   bool parseInsnDirective();
249
250   bool parseSetAtDirective();
251   bool parseSetNoAtDirective();
252   bool parseSetMacroDirective();
253   bool parseSetNoMacroDirective();
254   bool parseSetMsaDirective();
255   bool parseSetNoMsaDirective();
256   bool parseSetNoDspDirective();
257   bool parseSetReorderDirective();
258   bool parseSetNoReorderDirective();
259   bool parseSetMips16Directive();
260   bool parseSetNoMips16Directive();
261   bool parseSetFpDirective();
262   bool parseSetOddSPRegDirective();
263   bool parseSetNoOddSPRegDirective();
264   bool parseSetPopDirective();
265   bool parseSetPushDirective();
266   bool parseSetSoftFloatDirective();
267   bool parseSetHardFloatDirective();
268
269   bool parseSetAssignment();
270
271   bool parseDataDirective(unsigned Size, SMLoc L);
272   bool parseDirectiveGpWord();
273   bool parseDirectiveGpDWord();
274   bool parseDirectiveModule();
275   bool parseDirectiveModuleFP();
276   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
277                        StringRef Directive);
278
279   bool parseInternalDirectiveReallowModule();
280
281   MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
282
283   bool eatComma(StringRef ErrorStr);
284
285   int matchCPURegisterName(StringRef Symbol);
286
287   int matchHWRegsRegisterName(StringRef Symbol);
288
289   int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
290
291   int matchFPURegisterName(StringRef Name);
292
293   int matchFCCRegisterName(StringRef Name);
294
295   int matchACRegisterName(StringRef Name);
296
297   int matchMSA128RegisterName(StringRef Name);
298
299   int matchMSA128CtrlRegisterName(StringRef Name);
300
301   unsigned getReg(int RC, int RegNo);
302
303   unsigned getGPR(int RegNo);
304
305   /// Returns the internal register number for the current AT. Also checks if
306   /// the current AT is unavailable (set to $0) and gives an error if it is.
307   /// This should be used in pseudo-instruction expansions which need AT.
308   unsigned getATReg(SMLoc Loc);
309
310   bool processInstruction(MCInst &Inst, SMLoc IDLoc,
311                           SmallVectorImpl<MCInst> &Instructions);
312
313   // Helper function that checks if the value of a vector index is within the
314   // boundaries of accepted values for each RegisterKind
315   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
316   bool validateMSAIndex(int Val, int RegKind);
317
318   // Selects a new architecture by updating the FeatureBits with the necessary
319   // info including implied dependencies.
320   // Internally, it clears all the feature bits related to *any* architecture
321   // and selects the new one using the ToggleFeature functionality of the
322   // MCSubtargetInfo object that handles implied dependencies. The reason we
323   // clear all the arch related bits manually is because ToggleFeature only
324   // clears the features that imply the feature being cleared and not the
325   // features implied by the feature being cleared. This is easier to see
326   // with an example:
327   //  --------------------------------------------------
328   // | Feature         | Implies                        |
329   // | -------------------------------------------------|
330   // | FeatureMips1    | None                           |
331   // | FeatureMips2    | FeatureMips1                   |
332   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
333   // | FeatureMips4    | FeatureMips3                   |
334   // | ...             |                                |
335   //  --------------------------------------------------
336   //
337   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
338   // FeatureMipsGP64 | FeatureMips1)
339   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
340   void selectArch(StringRef ArchFeature) {
341     FeatureBitset FeatureBits = STI.getFeatureBits();
342     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
343     STI.setFeatureBits(FeatureBits);
344     setAvailableFeatures(
345         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
346     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
347   }
348
349   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
350     if (!(STI.getFeatureBits()[Feature])) {
351       setAvailableFeatures(
352           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
353       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
354     }
355   }
356
357   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
358     if (STI.getFeatureBits()[Feature]) {
359       setAvailableFeatures(
360           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
361       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
362     }
363   }
364
365 public:
366   enum MipsMatchResultTy {
367     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY
368 #define GET_OPERAND_DIAGNOSTIC_TYPES
369 #include "MipsGenAsmMatcher.inc"
370 #undef GET_OPERAND_DIAGNOSTIC_TYPES
371
372   };
373
374   MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
375                 const MCInstrInfo &MII, const MCTargetOptions &Options)
376       : MCTargetAsmParser(), STI(sti),
377         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
378                                           sti.getCPU(), Options)) {
379     MCAsmParserExtension::Initialize(parser);
380
381     parser.addAliasForDirective(".asciiz", ".asciz");
382
383     // Initialize the set of available features.
384     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
385     
386     // Remember the initial assembler options. The user can not modify these.
387     AssemblerOptions.push_back(
388         llvm::make_unique<MipsAssemblerOptions>(STI.getFeatureBits()));
389     
390     // Create an assembler options environment for the user to modify.
391     AssemblerOptions.push_back(
392         llvm::make_unique<MipsAssemblerOptions>(STI.getFeatureBits()));
393
394     getTargetStreamer().updateABIInfo(*this);
395
396     if (!isABI_O32() && !useOddSPReg() != 0)
397       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
398
399     CurrentFn = nullptr;
400
401     Triple TheTriple(sti.getTargetTriple());
402     if ((TheTriple.getArch() == Triple::mips) ||
403         (TheTriple.getArch() == Triple::mips64))
404       IsLittleEndian = false;
405     else
406       IsLittleEndian = true;
407   }
408
409   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
410   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
411
412   bool isGP64bit() const { return STI.getFeatureBits()[Mips::FeatureGP64Bit]; }
413   bool isFP64bit() const { return STI.getFeatureBits()[Mips::FeatureFP64Bit]; }
414   const MipsABIInfo &getABI() const { return ABI; }
415   bool isABI_N32() const { return ABI.IsN32(); }
416   bool isABI_N64() const { return ABI.IsN64(); }
417   bool isABI_O32() const { return ABI.IsO32(); }
418   bool isABI_FPXX() const { return STI.getFeatureBits()[Mips::FeatureFPXX]; }
419
420   bool useOddSPReg() const {
421     return !(STI.getFeatureBits()[Mips::FeatureNoOddSPReg]);
422   }
423
424   bool inMicroMipsMode() const {
425     return STI.getFeatureBits()[Mips::FeatureMicroMips];
426   }
427   bool hasMips1() const { return STI.getFeatureBits()[Mips::FeatureMips1]; }
428   bool hasMips2() const { return STI.getFeatureBits()[Mips::FeatureMips2]; }
429   bool hasMips3() const { return STI.getFeatureBits()[Mips::FeatureMips3]; }
430   bool hasMips4() const { return STI.getFeatureBits()[Mips::FeatureMips4]; }
431   bool hasMips5() const { return STI.getFeatureBits()[Mips::FeatureMips5]; }
432   bool hasMips32() const {
433     return STI.getFeatureBits()[Mips::FeatureMips32];
434   }
435   bool hasMips64() const {
436     return STI.getFeatureBits()[Mips::FeatureMips64];
437   }
438   bool hasMips32r2() const {
439     return STI.getFeatureBits()[Mips::FeatureMips32r2];
440   }
441   bool hasMips64r2() const {
442     return STI.getFeatureBits()[Mips::FeatureMips64r2];
443   }
444   bool hasMips32r3() const {
445     return (STI.getFeatureBits()[Mips::FeatureMips32r3]);
446   }
447   bool hasMips64r3() const {
448     return (STI.getFeatureBits()[Mips::FeatureMips64r3]);
449   }
450   bool hasMips32r5() const {
451     return (STI.getFeatureBits()[Mips::FeatureMips32r5]);
452   }
453   bool hasMips64r5() const {
454     return (STI.getFeatureBits()[Mips::FeatureMips64r5]);
455   }
456   bool hasMips32r6() const {
457     return STI.getFeatureBits()[Mips::FeatureMips32r6];
458   }
459   bool hasMips64r6() const {
460     return STI.getFeatureBits()[Mips::FeatureMips64r6];
461   }
462
463   bool hasDSP() const { return STI.getFeatureBits()[Mips::FeatureDSP]; }
464   bool hasDSPR2() const { return STI.getFeatureBits()[Mips::FeatureDSPR2]; }
465   bool hasMSA() const { return STI.getFeatureBits()[Mips::FeatureMSA]; }
466   bool hasCnMips() const {
467     return (STI.getFeatureBits()[Mips::FeatureCnMips]);
468   }
469
470   bool inMips16Mode() const {
471     return STI.getFeatureBits()[Mips::FeatureMips16];
472   }
473
474   bool useSoftFloat() const {
475     return STI.getFeatureBits()[Mips::FeatureSoftFloat];
476   }
477
478   /// Warn if RegIndex is the same as the current AT.
479   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
480
481   void warnIfNoMacro(SMLoc Loc);
482
483   bool isLittle() const { return IsLittleEndian; }
484 };
485 }
486
487 namespace {
488
489 /// MipsOperand - Instances of this class represent a parsed Mips machine
490 /// instruction.
491 class MipsOperand : public MCParsedAsmOperand {
492 public:
493   /// Broad categories of register classes
494   /// The exact class is finalized by the render method.
495   enum RegKind {
496     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
497     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
498                           /// isFP64bit())
499     RegKind_FCC = 4,      /// FCC
500     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
501     RegKind_MSACtrl = 16, /// MSA control registers
502     RegKind_COP2 = 32,    /// COP2
503     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
504                           /// context).
505     RegKind_CCR = 128,    /// CCR
506     RegKind_HWRegs = 256, /// HWRegs
507     RegKind_COP3 = 512,   /// COP3
508     RegKind_COP0 = 1024,  /// COP0
509     /// Potentially any (e.g. $1)
510     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
511                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
512                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
513   };
514
515 private:
516   enum KindTy {
517     k_Immediate,     /// An immediate (possibly involving symbol references)
518     k_Memory,        /// Base + Offset Memory Address
519     k_PhysRegister,  /// A physical register from the Mips namespace
520     k_RegisterIndex, /// A register index in one or more RegKind.
521     k_Token,         /// A simple token
522     k_RegList,       /// A physical register list
523     k_RegPair        /// A pair of physical register
524   } Kind;
525
526 public:
527   MipsOperand(KindTy K, MipsAsmParser &Parser)
528       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
529
530 private:
531   /// For diagnostics, and checking the assembler temporary
532   MipsAsmParser &AsmParser;
533
534   struct Token {
535     const char *Data;
536     unsigned Length;
537   };
538
539   struct PhysRegOp {
540     unsigned Num; /// Register Number
541   };
542
543   struct RegIdxOp {
544     unsigned Index; /// Index into the register class
545     RegKind Kind;   /// Bitfield of the kinds it could possibly be
546     const MCRegisterInfo *RegInfo;
547   };
548
549   struct ImmOp {
550     const MCExpr *Val;
551   };
552
553   struct MemOp {
554     MipsOperand *Base;
555     const MCExpr *Off;
556   };
557
558   struct RegListOp {
559     SmallVector<unsigned, 10> *List;
560   };
561
562   union {
563     struct Token Tok;
564     struct PhysRegOp PhysReg;
565     struct RegIdxOp RegIdx;
566     struct ImmOp Imm;
567     struct MemOp Mem;
568     struct RegListOp RegList;
569   };
570
571   SMLoc StartLoc, EndLoc;
572
573   /// Internal constructor for register kinds
574   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
575                                                 const MCRegisterInfo *RegInfo,
576                                                 SMLoc S, SMLoc E,
577                                                 MipsAsmParser &Parser) {
578     auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
579     Op->RegIdx.Index = Index;
580     Op->RegIdx.RegInfo = RegInfo;
581     Op->RegIdx.Kind = RegKind;
582     Op->StartLoc = S;
583     Op->EndLoc = E;
584     return Op;
585   }
586
587 public:
588   /// Coerce the register to GPR32 and return the real register for the current
589   /// target.
590   unsigned getGPR32Reg() const {
591     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
592     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
593     unsigned ClassID = Mips::GPR32RegClassID;
594     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
595   }
596
597   /// Coerce the register to GPR32 and return the real register for the current
598   /// target.
599   unsigned getGPRMM16Reg() const {
600     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
601     unsigned ClassID = Mips::GPR32RegClassID;
602     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
603   }
604
605   /// Coerce the register to GPR64 and return the real register for the current
606   /// target.
607   unsigned getGPR64Reg() const {
608     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
609     unsigned ClassID = Mips::GPR64RegClassID;
610     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
611   }
612
613 private:
614   /// Coerce the register to AFGR64 and return the real register for the current
615   /// target.
616   unsigned getAFGR64Reg() const {
617     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
618     if (RegIdx.Index % 2 != 0)
619       AsmParser.Warning(StartLoc, "Float register should be even.");
620     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
621         .getRegister(RegIdx.Index / 2);
622   }
623
624   /// Coerce the register to FGR64 and return the real register for the current
625   /// target.
626   unsigned getFGR64Reg() const {
627     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
628     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
629         .getRegister(RegIdx.Index);
630   }
631
632   /// Coerce the register to FGR32 and return the real register for the current
633   /// target.
634   unsigned getFGR32Reg() const {
635     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
636     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
637         .getRegister(RegIdx.Index);
638   }
639
640   /// Coerce the register to FGRH32 and return the real register for the current
641   /// target.
642   unsigned getFGRH32Reg() const {
643     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
644     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
645         .getRegister(RegIdx.Index);
646   }
647
648   /// Coerce the register to FCC and return the real register for the current
649   /// target.
650   unsigned getFCCReg() const {
651     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
652     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
653         .getRegister(RegIdx.Index);
654   }
655
656   /// Coerce the register to MSA128 and return the real register for the current
657   /// target.
658   unsigned getMSA128Reg() const {
659     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
660     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
661     // identical
662     unsigned ClassID = Mips::MSA128BRegClassID;
663     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
664   }
665
666   /// Coerce the register to MSACtrl and return the real register for the
667   /// current target.
668   unsigned getMSACtrlReg() const {
669     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
670     unsigned ClassID = Mips::MSACtrlRegClassID;
671     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
672   }
673
674   /// Coerce the register to COP0 and return the real register for the
675   /// current target.
676   unsigned getCOP0Reg() const {
677     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
678     unsigned ClassID = Mips::COP0RegClassID;
679     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
680   }
681
682   /// Coerce the register to COP2 and return the real register for the
683   /// current target.
684   unsigned getCOP2Reg() const {
685     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
686     unsigned ClassID = Mips::COP2RegClassID;
687     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
688   }
689
690   /// Coerce the register to COP3 and return the real register for the
691   /// current target.
692   unsigned getCOP3Reg() const {
693     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
694     unsigned ClassID = Mips::COP3RegClassID;
695     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
696   }
697
698   /// Coerce the register to ACC64DSP and return the real register for the
699   /// current target.
700   unsigned getACC64DSPReg() const {
701     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
702     unsigned ClassID = Mips::ACC64DSPRegClassID;
703     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
704   }
705
706   /// Coerce the register to HI32DSP and return the real register for the
707   /// current target.
708   unsigned getHI32DSPReg() const {
709     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
710     unsigned ClassID = Mips::HI32DSPRegClassID;
711     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
712   }
713
714   /// Coerce the register to LO32DSP and return the real register for the
715   /// current target.
716   unsigned getLO32DSPReg() const {
717     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
718     unsigned ClassID = Mips::LO32DSPRegClassID;
719     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
720   }
721
722   /// Coerce the register to CCR and return the real register for the
723   /// current target.
724   unsigned getCCRReg() const {
725     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
726     unsigned ClassID = Mips::CCRRegClassID;
727     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
728   }
729
730   /// Coerce the register to HWRegs and return the real register for the
731   /// current target.
732   unsigned getHWRegsReg() const {
733     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
734     unsigned ClassID = Mips::HWRegsRegClassID;
735     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
736   }
737
738 public:
739   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
740     // Add as immediate when possible.  Null MCExpr = 0.
741     if (!Expr)
742       Inst.addOperand(MCOperand::createImm(0));
743     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
744       Inst.addOperand(MCOperand::createImm(CE->getValue()));
745     else
746       Inst.addOperand(MCOperand::createExpr(Expr));
747   }
748
749   void addRegOperands(MCInst &Inst, unsigned N) const {
750     llvm_unreachable("Use a custom parser instead");
751   }
752
753   /// Render the operand to an MCInst as a GPR32
754   /// Asserts if the wrong number of operands are requested, or the operand
755   /// is not a k_RegisterIndex compatible with RegKind_GPR
756   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
757     assert(N == 1 && "Invalid number of operands!");
758     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
759   }
760
761   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
762     assert(N == 1 && "Invalid number of operands!");
763     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
764   }
765
766   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
767     assert(N == 1 && "Invalid number of operands!");
768     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
769   }
770
771   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
772     assert(N == 1 && "Invalid number of operands!");
773     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
774   }
775
776   /// Render the operand to an MCInst as a GPR64
777   /// Asserts if the wrong number of operands are requested, or the operand
778   /// is not a k_RegisterIndex compatible with RegKind_GPR
779   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
780     assert(N == 1 && "Invalid number of operands!");
781     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
782   }
783
784   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
785     assert(N == 1 && "Invalid number of operands!");
786     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
787   }
788
789   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
790     assert(N == 1 && "Invalid number of operands!");
791     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
792   }
793
794   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
795     assert(N == 1 && "Invalid number of operands!");
796     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
797     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
798     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
799       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
800                                 "registers");
801   }
802
803   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
804     assert(N == 1 && "Invalid number of operands!");
805     Inst.addOperand(MCOperand::createReg(getFGRH32Reg()));
806   }
807
808   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
809     assert(N == 1 && "Invalid number of operands!");
810     Inst.addOperand(MCOperand::createReg(getFCCReg()));
811   }
812
813   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
814     assert(N == 1 && "Invalid number of operands!");
815     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
816   }
817
818   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
819     assert(N == 1 && "Invalid number of operands!");
820     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
821   }
822
823   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
824     assert(N == 1 && "Invalid number of operands!");
825     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
826   }
827
828   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
829     assert(N == 1 && "Invalid number of operands!");
830     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
831   }
832
833   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
834     assert(N == 1 && "Invalid number of operands!");
835     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
836   }
837
838   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
839     assert(N == 1 && "Invalid number of operands!");
840     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
841   }
842
843   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
844     assert(N == 1 && "Invalid number of operands!");
845     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
846   }
847
848   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
849     assert(N == 1 && "Invalid number of operands!");
850     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
851   }
852
853   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
854     assert(N == 1 && "Invalid number of operands!");
855     Inst.addOperand(MCOperand::createReg(getCCRReg()));
856   }
857
858   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
859     assert(N == 1 && "Invalid number of operands!");
860     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
861   }
862
863   void addImmOperands(MCInst &Inst, unsigned N) const {
864     assert(N == 1 && "Invalid number of operands!");
865     const MCExpr *Expr = getImm();
866     addExpr(Inst, Expr);
867   }
868
869   void addMemOperands(MCInst &Inst, unsigned N) const {
870     assert(N == 2 && "Invalid number of operands!");
871
872     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPR32Reg()));
873
874     const MCExpr *Expr = getMemOff();
875     addExpr(Inst, Expr);
876   }
877
878   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
879     assert(N == 2 && "Invalid number of operands!");
880
881     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
882
883     const MCExpr *Expr = getMemOff();
884     addExpr(Inst, Expr);
885   }
886
887   void addRegListOperands(MCInst &Inst, unsigned N) const {
888     assert(N == 1 && "Invalid number of operands!");
889
890     for (auto RegNo : getRegList())
891       Inst.addOperand(MCOperand::createReg(RegNo));
892   }
893
894   void addRegPairOperands(MCInst &Inst, unsigned N) const {
895     assert(N == 2 && "Invalid number of operands!");
896     unsigned RegNo = getRegPair();
897     Inst.addOperand(MCOperand::createReg(RegNo++));
898     Inst.addOperand(MCOperand::createReg(RegNo));
899   }
900
901   void addMovePRegPairOperands(MCInst &Inst, unsigned N) const {
902     assert(N == 2 && "Invalid number of operands!");
903     for (auto RegNo : getRegList())
904       Inst.addOperand(MCOperand::createReg(RegNo));
905   }
906
907   bool isReg() const override {
908     // As a special case until we sort out the definition of div/divu, pretend
909     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
910     if (isGPRAsmReg() && RegIdx.Index == 0)
911       return true;
912
913     return Kind == k_PhysRegister;
914   }
915   bool isRegIdx() const { return Kind == k_RegisterIndex; }
916   bool isImm() const override { return Kind == k_Immediate; }
917   bool isConstantImm() const {
918     return isImm() && dyn_cast<MCConstantExpr>(getImm());
919   }
920   template <unsigned Bits> bool isUImm() const {
921     return isImm() && isConstantImm() && isUInt<Bits>(getConstantImm());
922   }
923   bool isToken() const override {
924     // Note: It's not possible to pretend that other operand kinds are tokens.
925     // The matcher emitter checks tokens first.
926     return Kind == k_Token;
927   }
928   bool isMem() const override { return Kind == k_Memory; }
929   bool isConstantMemOff() const {
930     return isMem() && dyn_cast<MCConstantExpr>(getMemOff());
931   }
932   template <unsigned Bits> bool isMemWithSimmOffset() const {
933     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff());
934   }
935   bool isMemWithGRPMM16Base() const {
936     return isMem() && getMemBase()->isMM16AsmReg();
937   }
938   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
939     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
940       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
941   }
942   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
943     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
944       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
945       && (getMemBase()->getGPR32Reg() == Mips::SP);
946   }
947   bool isRegList16() const {
948     if (!isRegList())
949       return false;
950
951     int Size = RegList.List->size();
952     if (Size < 2 || Size > 5 || *RegList.List->begin() != Mips::S0 ||
953         RegList.List->back() != Mips::RA)
954       return false;
955
956     int PrevReg = *RegList.List->begin();
957     for (int i = 1; i < Size - 1; i++) {
958       int Reg = (*(RegList.List))[i];
959       if ( Reg != PrevReg + 1)
960         return false;
961       PrevReg = Reg;
962     }
963
964     return true;
965   }
966   bool isInvNum() const { return Kind == k_Immediate; }
967   bool isLSAImm() const {
968     if (!isConstantImm())
969       return false;
970     int64_t Val = getConstantImm();
971     return 1 <= Val && Val <= 4;
972   }
973   bool isRegList() const { return Kind == k_RegList; }
974   bool isMovePRegPair() const {
975     if (Kind != k_RegList || RegList.List->size() != 2)
976       return false;
977
978     unsigned R0 = RegList.List->front();
979     unsigned R1 = RegList.List->back();
980
981     if ((R0 == Mips::A1 && R1 == Mips::A2) ||
982         (R0 == Mips::A1 && R1 == Mips::A3) ||
983         (R0 == Mips::A2 && R1 == Mips::A3) ||
984         (R0 == Mips::A0 && R1 == Mips::S5) ||
985         (R0 == Mips::A0 && R1 == Mips::S6) ||
986         (R0 == Mips::A0 && R1 == Mips::A1) ||
987         (R0 == Mips::A0 && R1 == Mips::A2) ||
988         (R0 == Mips::A0 && R1 == Mips::A3))
989       return true;
990
991     return false;
992   }
993
994   StringRef getToken() const {
995     assert(Kind == k_Token && "Invalid access!");
996     return StringRef(Tok.Data, Tok.Length);
997   }
998   bool isRegPair() const { return Kind == k_RegPair; }
999
1000   unsigned getReg() const override {
1001     // As a special case until we sort out the definition of div/divu, pretend
1002     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
1003     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1004         RegIdx.Kind & RegKind_GPR)
1005       return getGPR32Reg(); // FIXME: GPR64 too
1006
1007     assert(Kind == k_PhysRegister && "Invalid access!");
1008     return PhysReg.Num;
1009   }
1010
1011   const MCExpr *getImm() const {
1012     assert((Kind == k_Immediate) && "Invalid access!");
1013     return Imm.Val;
1014   }
1015
1016   int64_t getConstantImm() const {
1017     const MCExpr *Val = getImm();
1018     return static_cast<const MCConstantExpr *>(Val)->getValue();
1019   }
1020
1021   MipsOperand *getMemBase() const {
1022     assert((Kind == k_Memory) && "Invalid access!");
1023     return Mem.Base;
1024   }
1025
1026   const MCExpr *getMemOff() const {
1027     assert((Kind == k_Memory) && "Invalid access!");
1028     return Mem.Off;
1029   }
1030
1031   int64_t getConstantMemOff() const {
1032     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1033   }
1034
1035   const SmallVectorImpl<unsigned> &getRegList() const {
1036     assert((Kind == k_RegList) && "Invalid access!");
1037     return *(RegList.List);
1038   }
1039
1040   unsigned getRegPair() const {
1041     assert((Kind == k_RegPair) && "Invalid access!");
1042     return RegIdx.Index;
1043   }
1044
1045   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1046                                                   MipsAsmParser &Parser) {
1047     auto Op = make_unique<MipsOperand>(k_Token, Parser);
1048     Op->Tok.Data = Str.data();
1049     Op->Tok.Length = Str.size();
1050     Op->StartLoc = S;
1051     Op->EndLoc = S;
1052     return Op;
1053   }
1054
1055   /// Create a numeric register (e.g. $1). The exact register remains
1056   /// unresolved until an instruction successfully matches
1057   static std::unique_ptr<MipsOperand>
1058   createNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1059                    SMLoc E, MipsAsmParser &Parser) {
1060     DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1061     return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
1062   }
1063
1064   /// Create a register that is definitely a GPR.
1065   /// This is typically only used for named registers such as $gp.
1066   static std::unique_ptr<MipsOperand>
1067   createGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1068                MipsAsmParser &Parser) {
1069     return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
1070   }
1071
1072   /// Create a register that is definitely a FGR.
1073   /// This is typically only used for named registers such as $f0.
1074   static std::unique_ptr<MipsOperand>
1075   createFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1076                MipsAsmParser &Parser) {
1077     return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
1078   }
1079
1080   /// Create a register that is definitely a HWReg.
1081   /// This is typically only used for named registers such as $hwr_cpunum.
1082   static std::unique_ptr<MipsOperand>
1083   createHWRegsReg(unsigned Index, const MCRegisterInfo *RegInfo,
1084                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1085     return CreateReg(Index, RegKind_HWRegs, RegInfo, S, E, Parser);
1086   }
1087
1088   /// Create a register that is definitely an FCC.
1089   /// This is typically only used for named registers such as $fcc0.
1090   static std::unique_ptr<MipsOperand>
1091   createFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1092                MipsAsmParser &Parser) {
1093     return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
1094   }
1095
1096   /// Create a register that is definitely an ACC.
1097   /// This is typically only used for named registers such as $ac0.
1098   static std::unique_ptr<MipsOperand>
1099   createACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1100                MipsAsmParser &Parser) {
1101     return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
1102   }
1103
1104   /// Create a register that is definitely an MSA128.
1105   /// This is typically only used for named registers such as $w0.
1106   static std::unique_ptr<MipsOperand>
1107   createMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1108                   SMLoc E, MipsAsmParser &Parser) {
1109     return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
1110   }
1111
1112   /// Create a register that is definitely an MSACtrl.
1113   /// This is typically only used for named registers such as $msaaccess.
1114   static std::unique_ptr<MipsOperand>
1115   createMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1116                    SMLoc E, MipsAsmParser &Parser) {
1117     return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
1118   }
1119
1120   static std::unique_ptr<MipsOperand>
1121   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1122     auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
1123     Op->Imm.Val = Val;
1124     Op->StartLoc = S;
1125     Op->EndLoc = E;
1126     return Op;
1127   }
1128
1129   static std::unique_ptr<MipsOperand>
1130   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1131             SMLoc E, MipsAsmParser &Parser) {
1132     auto Op = make_unique<MipsOperand>(k_Memory, Parser);
1133     Op->Mem.Base = Base.release();
1134     Op->Mem.Off = Off;
1135     Op->StartLoc = S;
1136     Op->EndLoc = E;
1137     return Op;
1138   }
1139
1140   static std::unique_ptr<MipsOperand>
1141   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1142                 MipsAsmParser &Parser) {
1143     assert (Regs.size() > 0 && "Empty list not allowed");
1144
1145     auto Op = make_unique<MipsOperand>(k_RegList, Parser);
1146     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1147     Op->StartLoc = StartLoc;
1148     Op->EndLoc = EndLoc;
1149     return Op;
1150   }
1151
1152   static std::unique_ptr<MipsOperand>
1153   CreateRegPair(unsigned RegNo, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1154     auto Op = make_unique<MipsOperand>(k_RegPair, Parser);
1155     Op->RegIdx.Index = RegNo;
1156     Op->StartLoc = S;
1157     Op->EndLoc = E;
1158     return Op;
1159   }
1160
1161   bool isGPRAsmReg() const {
1162     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1163   }
1164   bool isMM16AsmReg() const {
1165     if (!(isRegIdx() && RegIdx.Kind))
1166       return false;
1167     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1168             || RegIdx.Index == 16 || RegIdx.Index == 17);
1169   }
1170   bool isMM16AsmRegZero() const {
1171     if (!(isRegIdx() && RegIdx.Kind))
1172       return false;
1173     return (RegIdx.Index == 0 ||
1174             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1175             RegIdx.Index == 17);
1176   }
1177   bool isMM16AsmRegMoveP() const {
1178     if (!(isRegIdx() && RegIdx.Kind))
1179       return false;
1180     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1181       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1182   }
1183   bool isFGRAsmReg() const {
1184     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1185     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1186   }
1187   bool isHWRegsAsmReg() const {
1188     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1189   }
1190   bool isCCRAsmReg() const {
1191     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1192   }
1193   bool isFCCAsmReg() const {
1194     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1195       return false;
1196     if (!AsmParser.hasEightFccRegisters())
1197       return RegIdx.Index == 0;
1198     return RegIdx.Index <= 7;
1199   }
1200   bool isACCAsmReg() const {
1201     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1202   }
1203   bool isCOP0AsmReg() const {
1204     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1205   }
1206   bool isCOP2AsmReg() const {
1207     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1208   }
1209   bool isCOP3AsmReg() const {
1210     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1211   }
1212   bool isMSA128AsmReg() const {
1213     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1214   }
1215   bool isMSACtrlAsmReg() const {
1216     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1217   }
1218
1219   /// getStartLoc - Get the location of the first token of this operand.
1220   SMLoc getStartLoc() const override { return StartLoc; }
1221   /// getEndLoc - Get the location of the last token of this operand.
1222   SMLoc getEndLoc() const override { return EndLoc; }
1223
1224   virtual ~MipsOperand() {
1225     switch (Kind) {
1226     case k_Immediate:
1227       break;
1228     case k_Memory:
1229       delete Mem.Base;
1230       break;
1231     case k_RegList:
1232       delete RegList.List;
1233     case k_PhysRegister:
1234     case k_RegisterIndex:
1235     case k_Token:
1236     case k_RegPair:
1237       break;
1238     }
1239   }
1240
1241   void print(raw_ostream &OS) const override {
1242     switch (Kind) {
1243     case k_Immediate:
1244       OS << "Imm<";
1245       OS << *Imm.Val;
1246       OS << ">";
1247       break;
1248     case k_Memory:
1249       OS << "Mem<";
1250       Mem.Base->print(OS);
1251       OS << ", ";
1252       OS << *Mem.Off;
1253       OS << ">";
1254       break;
1255     case k_PhysRegister:
1256       OS << "PhysReg<" << PhysReg.Num << ">";
1257       break;
1258     case k_RegisterIndex:
1259       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
1260       break;
1261     case k_Token:
1262       OS << Tok.Data;
1263       break;
1264     case k_RegList:
1265       OS << "RegList< ";
1266       for (auto Reg : (*RegList.List))
1267         OS << Reg << " ";
1268       OS <<  ">";
1269       break;
1270     case k_RegPair:
1271       OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">";
1272       break;
1273     }
1274   }
1275 }; // class MipsOperand
1276 } // namespace
1277
1278 namespace llvm {
1279 extern const MCInstrDesc MipsInsts[];
1280 }
1281 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1282   return MipsInsts[Opcode];
1283 }
1284
1285 static bool hasShortDelaySlot(unsigned Opcode) {
1286   switch (Opcode) {
1287     case Mips::JALS_MM:
1288     case Mips::JALRS_MM:
1289     case Mips::JALRS16_MM:
1290     case Mips::BGEZALS_MM:
1291     case Mips::BLTZALS_MM:
1292       return true;
1293     default:
1294       return false;
1295   }
1296 }
1297
1298 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1299                                        SmallVectorImpl<MCInst> &Instructions) {
1300   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1301
1302   Inst.setLoc(IDLoc);
1303
1304   if (MCID.isBranch() || MCID.isCall()) {
1305     const unsigned Opcode = Inst.getOpcode();
1306     MCOperand Offset;
1307
1308     switch (Opcode) {
1309     default:
1310       break;
1311     case Mips::BBIT0:
1312     case Mips::BBIT032:
1313     case Mips::BBIT1:
1314     case Mips::BBIT132:
1315       assert(hasCnMips() && "instruction only valid for octeon cpus");
1316       // Fall through
1317
1318     case Mips::BEQ:
1319     case Mips::BNE:
1320     case Mips::BEQ_MM:
1321     case Mips::BNE_MM:
1322       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1323       Offset = Inst.getOperand(2);
1324       if (!Offset.isImm())
1325         break; // We'll deal with this situation later on when applying fixups.
1326       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1327         return Error(IDLoc, "branch target out of range");
1328       if (OffsetToAlignment(Offset.getImm(),
1329                             1LL << (inMicroMipsMode() ? 1 : 2)))
1330         return Error(IDLoc, "branch to misaligned address");
1331       break;
1332     case Mips::BGEZ:
1333     case Mips::BGTZ:
1334     case Mips::BLEZ:
1335     case Mips::BLTZ:
1336     case Mips::BGEZAL:
1337     case Mips::BLTZAL:
1338     case Mips::BC1F:
1339     case Mips::BC1T:
1340     case Mips::BGEZ_MM:
1341     case Mips::BGTZ_MM:
1342     case Mips::BLEZ_MM:
1343     case Mips::BLTZ_MM:
1344     case Mips::BGEZAL_MM:
1345     case Mips::BLTZAL_MM:
1346     case Mips::BC1F_MM:
1347     case Mips::BC1T_MM:
1348       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1349       Offset = Inst.getOperand(1);
1350       if (!Offset.isImm())
1351         break; // We'll deal with this situation later on when applying fixups.
1352       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1353         return Error(IDLoc, "branch target out of range");
1354       if (OffsetToAlignment(Offset.getImm(),
1355                             1LL << (inMicroMipsMode() ? 1 : 2)))
1356         return Error(IDLoc, "branch to misaligned address");
1357       break;
1358     case Mips::BEQZ16_MM:
1359     case Mips::BNEZ16_MM:
1360       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1361       Offset = Inst.getOperand(1);
1362       if (!Offset.isImm())
1363         break; // We'll deal with this situation later on when applying fixups.
1364       if (!isIntN(8, Offset.getImm()))
1365         return Error(IDLoc, "branch target out of range");
1366       if (OffsetToAlignment(Offset.getImm(), 2LL))
1367         return Error(IDLoc, "branch to misaligned address");
1368       break;
1369     }
1370   }
1371
1372   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1373   // We still accept it but it is a normal nop.
1374   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1375     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1376     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1377                                                       "nop instruction");
1378   }
1379
1380   if (hasCnMips()) {
1381     const unsigned Opcode = Inst.getOpcode();
1382     MCOperand Opnd;
1383     int Imm;
1384
1385     switch (Opcode) {
1386       default:
1387         break;
1388
1389       case Mips::BBIT0:
1390       case Mips::BBIT032:
1391       case Mips::BBIT1:
1392       case Mips::BBIT132:
1393         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1394         // The offset is handled above
1395         Opnd = Inst.getOperand(1);
1396         if (!Opnd.isImm())
1397           return Error(IDLoc, "expected immediate operand kind");
1398         Imm = Opnd.getImm();
1399         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1400                               Opcode == Mips::BBIT1 ? 63 : 31))
1401           return Error(IDLoc, "immediate operand value out of range");
1402         if (Imm > 31) {
1403           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1404                                                : Mips::BBIT132);
1405           Inst.getOperand(1).setImm(Imm - 32);
1406         }
1407         break;
1408
1409       case Mips::CINS:
1410       case Mips::CINS32:
1411       case Mips::EXTS:
1412       case Mips::EXTS32:
1413         assert(MCID.getNumOperands() == 4 && "unexpected number of operands");
1414         // Check length
1415         Opnd = Inst.getOperand(3);
1416         if (!Opnd.isImm())
1417           return Error(IDLoc, "expected immediate operand kind");
1418         Imm = Opnd.getImm();
1419         if (Imm < 0 || Imm > 31)
1420           return Error(IDLoc, "immediate operand value out of range");
1421         // Check position
1422         Opnd = Inst.getOperand(2);
1423         if (!Opnd.isImm())
1424           return Error(IDLoc, "expected immediate operand kind");
1425         Imm = Opnd.getImm();
1426         if (Imm < 0 || Imm > (Opcode == Mips::CINS ||
1427                               Opcode == Mips::EXTS ? 63 : 31))
1428           return Error(IDLoc, "immediate operand value out of range");
1429         if (Imm > 31) {
1430           Inst.setOpcode(Opcode == Mips::CINS ? Mips::CINS32 : Mips::EXTS32);
1431           Inst.getOperand(2).setImm(Imm - 32);
1432         }
1433         break;
1434
1435       case Mips::SEQi:
1436       case Mips::SNEi:
1437         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1438         Opnd = Inst.getOperand(2);
1439         if (!Opnd.isImm())
1440           return Error(IDLoc, "expected immediate operand kind");
1441         Imm = Opnd.getImm();
1442         if (!isInt<10>(Imm))
1443           return Error(IDLoc, "immediate operand value out of range");
1444         break;
1445     }
1446   }
1447
1448   if (MCID.mayLoad() || MCID.mayStore()) {
1449     // Check the offset of memory operand, if it is a symbol
1450     // reference or immediate we may have to expand instructions.
1451     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1452       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1453       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1454           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1455         MCOperand &Op = Inst.getOperand(i);
1456         if (Op.isImm()) {
1457           int MemOffset = Op.getImm();
1458           if (MemOffset < -32768 || MemOffset > 32767) {
1459             // Offset can't exceed 16bit value.
1460             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
1461             return false;
1462           }
1463         } else if (Op.isExpr()) {
1464           const MCExpr *Expr = Op.getExpr();
1465           if (Expr->getKind() == MCExpr::SymbolRef) {
1466             const MCSymbolRefExpr *SR =
1467                 static_cast<const MCSymbolRefExpr *>(Expr);
1468             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
1469               // Expand symbol.
1470               expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
1471               return false;
1472             }
1473           } else if (!isEvaluated(Expr)) {
1474             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
1475             return false;
1476           }
1477         }
1478       }
1479     } // for
1480   }   // if load/store
1481
1482   if (inMicroMipsMode()) {
1483     if (MCID.mayLoad()) {
1484       // Try to create 16-bit GP relative load instruction.
1485       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1486         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1487         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1488             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1489           MCOperand &Op = Inst.getOperand(i);
1490           if (Op.isImm()) {
1491             int MemOffset = Op.getImm();
1492             MCOperand &DstReg = Inst.getOperand(0);
1493             MCOperand &BaseReg = Inst.getOperand(1);
1494             if (isIntN(9, MemOffset) && (MemOffset % 4 == 0) &&
1495                 getContext().getRegisterInfo()->getRegClass(
1496                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
1497                 BaseReg.getReg() == Mips::GP) {
1498               MCInst TmpInst;
1499               TmpInst.setLoc(IDLoc);
1500               TmpInst.setOpcode(Mips::LWGP_MM);
1501               TmpInst.addOperand(MCOperand::createReg(DstReg.getReg()));
1502               TmpInst.addOperand(MCOperand::createReg(Mips::GP));
1503               TmpInst.addOperand(MCOperand::createImm(MemOffset));
1504               Instructions.push_back(TmpInst);
1505               return false;
1506             }
1507           }
1508         }
1509       } // for
1510     }   // if load
1511
1512     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
1513
1514     MCOperand Opnd;
1515     int Imm;
1516
1517     switch (Inst.getOpcode()) {
1518       default:
1519         break;
1520       case Mips::ADDIUS5_MM:
1521         Opnd = Inst.getOperand(2);
1522         if (!Opnd.isImm())
1523           return Error(IDLoc, "expected immediate operand kind");
1524         Imm = Opnd.getImm();
1525         if (Imm < -8 || Imm > 7)
1526           return Error(IDLoc, "immediate operand value out of range");
1527         break;
1528       case Mips::ADDIUSP_MM:
1529         Opnd = Inst.getOperand(0);
1530         if (!Opnd.isImm())
1531           return Error(IDLoc, "expected immediate operand kind");
1532         Imm = Opnd.getImm();
1533         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
1534             Imm % 4 != 0)
1535           return Error(IDLoc, "immediate operand value out of range");
1536         break;
1537       case Mips::SLL16_MM:
1538       case Mips::SRL16_MM:
1539         Opnd = Inst.getOperand(2);
1540         if (!Opnd.isImm())
1541           return Error(IDLoc, "expected immediate operand kind");
1542         Imm = Opnd.getImm();
1543         if (Imm < 1 || Imm > 8)
1544           return Error(IDLoc, "immediate operand value out of range");
1545         break;
1546       case Mips::LI16_MM:
1547         Opnd = Inst.getOperand(1);
1548         if (!Opnd.isImm())
1549           return Error(IDLoc, "expected immediate operand kind");
1550         Imm = Opnd.getImm();
1551         if (Imm < -1 || Imm > 126)
1552           return Error(IDLoc, "immediate operand value out of range");
1553         break;
1554       case Mips::ADDIUR2_MM:
1555         Opnd = Inst.getOperand(2);
1556         if (!Opnd.isImm())
1557           return Error(IDLoc, "expected immediate operand kind");
1558         Imm = Opnd.getImm();
1559         if (!(Imm == 1 || Imm == -1 ||
1560               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
1561           return Error(IDLoc, "immediate operand value out of range");
1562         break;
1563       case Mips::ADDIUR1SP_MM:
1564         Opnd = Inst.getOperand(1);
1565         if (!Opnd.isImm())
1566           return Error(IDLoc, "expected immediate operand kind");
1567         Imm = Opnd.getImm();
1568         if (OffsetToAlignment(Imm, 4LL))
1569           return Error(IDLoc, "misaligned immediate operand value");
1570         if (Imm < 0 || Imm > 255)
1571           return Error(IDLoc, "immediate operand value out of range");
1572         break;
1573       case Mips::ANDI16_MM:
1574         Opnd = Inst.getOperand(2);
1575         if (!Opnd.isImm())
1576           return Error(IDLoc, "expected immediate operand kind");
1577         Imm = Opnd.getImm();
1578         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
1579               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
1580               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
1581           return Error(IDLoc, "immediate operand value out of range");
1582         break;
1583       case Mips::LBU16_MM:
1584         Opnd = Inst.getOperand(2);
1585         if (!Opnd.isImm())
1586           return Error(IDLoc, "expected immediate operand kind");
1587         Imm = Opnd.getImm();
1588         if (Imm < -1 || Imm > 14)
1589           return Error(IDLoc, "immediate operand value out of range");
1590         break;
1591       case Mips::SB16_MM:
1592         Opnd = Inst.getOperand(2);
1593         if (!Opnd.isImm())
1594           return Error(IDLoc, "expected immediate operand kind");
1595         Imm = Opnd.getImm();
1596         if (Imm < 0 || Imm > 15)
1597           return Error(IDLoc, "immediate operand value out of range");
1598         break;
1599       case Mips::LHU16_MM:
1600       case Mips::SH16_MM:
1601         Opnd = Inst.getOperand(2);
1602         if (!Opnd.isImm())
1603           return Error(IDLoc, "expected immediate operand kind");
1604         Imm = Opnd.getImm();
1605         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
1606           return Error(IDLoc, "immediate operand value out of range");
1607         break;
1608       case Mips::LW16_MM:
1609       case Mips::SW16_MM:
1610         Opnd = Inst.getOperand(2);
1611         if (!Opnd.isImm())
1612           return Error(IDLoc, "expected immediate operand kind");
1613         Imm = Opnd.getImm();
1614         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
1615           return Error(IDLoc, "immediate operand value out of range");
1616         break;
1617       case Mips::CACHE:
1618       case Mips::PREF:
1619         Opnd = Inst.getOperand(2);
1620         if (!Opnd.isImm())
1621           return Error(IDLoc, "expected immediate operand kind");
1622         Imm = Opnd.getImm();
1623         if (!isUInt<5>(Imm))
1624           return Error(IDLoc, "immediate operand value out of range");
1625         break;
1626       case Mips::ADDIUPC_MM:
1627         MCOperand Opnd = Inst.getOperand(1);
1628         if (!Opnd.isImm())
1629           return Error(IDLoc, "expected immediate operand kind");
1630         int Imm = Opnd.getImm();
1631         if ((Imm % 4 != 0) || !isIntN(25, Imm))
1632           return Error(IDLoc, "immediate operand value out of range");
1633         break;
1634     }
1635   }
1636
1637   if (needsExpansion(Inst)) {
1638     if (expandInstruction(Inst, IDLoc, Instructions))
1639       return true;
1640   } else
1641     Instructions.push_back(Inst);
1642
1643   // If this instruction has a delay slot and .set reorder is active,
1644   // emit a NOP after it.
1645   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
1646     createNop(hasShortDelaySlot(Inst.getOpcode()), IDLoc, Instructions);
1647
1648   return false;
1649 }
1650
1651 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
1652
1653   switch (Inst.getOpcode()) {
1654   case Mips::LoadImm32:
1655   case Mips::LoadImm64:
1656   case Mips::LoadAddrImm32:
1657   case Mips::LoadAddrReg32:
1658   case Mips::B_MM_Pseudo:
1659   case Mips::LWM_MM:
1660   case Mips::SWM_MM:
1661   case Mips::JalOneReg:
1662   case Mips::JalTwoReg:
1663   case Mips::BneImm:
1664   case Mips::BeqImm:
1665   case Mips::BLT:
1666   case Mips::BLE:
1667   case Mips::BGE:
1668   case Mips::BGT:
1669   case Mips::BLTU:
1670   case Mips::BLEU:
1671   case Mips::BGEU:
1672   case Mips::BGTU:
1673   case Mips::Ulhu:
1674   case Mips::Ulw:
1675     return true;
1676   default:
1677     return false;
1678   }
1679 }
1680
1681 bool MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
1682                                       SmallVectorImpl<MCInst> &Instructions) {
1683   switch (Inst.getOpcode()) {
1684   default: llvm_unreachable("unimplemented expansion");
1685   case Mips::LoadImm32:
1686     return expandLoadImm(Inst, true, IDLoc, Instructions);
1687   case Mips::LoadImm64:
1688     return expandLoadImm(Inst, false, IDLoc, Instructions);
1689   case Mips::LoadAddrImm32:
1690     return expandLoadAddressImm(Inst, true, IDLoc, Instructions);
1691   case Mips::LoadAddrReg32:
1692     return expandLoadAddressReg(Inst, true, IDLoc, Instructions);
1693   case Mips::B_MM_Pseudo:
1694     return expandUncondBranchMMPseudo(Inst, IDLoc, Instructions);
1695   case Mips::SWM_MM:
1696   case Mips::LWM_MM:
1697     return expandLoadStoreMultiple(Inst, IDLoc, Instructions);
1698   case Mips::JalOneReg:
1699   case Mips::JalTwoReg:
1700     return expandJalWithRegs(Inst, IDLoc, Instructions);
1701   case Mips::BneImm:
1702   case Mips::BeqImm:
1703     return expandBranchImm(Inst, IDLoc, Instructions);
1704   case Mips::BLT:
1705   case Mips::BLE:
1706   case Mips::BGE:
1707   case Mips::BGT:
1708   case Mips::BLTU:
1709   case Mips::BLEU:
1710   case Mips::BGEU:
1711   case Mips::BGTU:
1712     return expandCondBranches(Inst, IDLoc, Instructions);
1713   case Mips::Ulhu:
1714     return expandUlhu(Inst, IDLoc, Instructions);
1715   case Mips::Ulw:
1716     return expandUlw(Inst, IDLoc, Instructions);
1717   }
1718 }
1719
1720 namespace {
1721 template <unsigned ShiftAmount>
1722 void createLShiftOri(MCOperand Operand, unsigned RegNo, SMLoc IDLoc,
1723                      SmallVectorImpl<MCInst> &Instructions) {
1724   MCInst tmpInst;
1725   if (ShiftAmount >= 32) {
1726     tmpInst.setOpcode(Mips::DSLL32);
1727     tmpInst.addOperand(MCOperand::createReg(RegNo));
1728     tmpInst.addOperand(MCOperand::createReg(RegNo));
1729     tmpInst.addOperand(MCOperand::createImm(ShiftAmount - 32));
1730     tmpInst.setLoc(IDLoc);
1731     Instructions.push_back(tmpInst);
1732     tmpInst.clear();
1733   } else if (ShiftAmount > 0) {
1734     tmpInst.setOpcode(Mips::DSLL);
1735     tmpInst.addOperand(MCOperand::createReg(RegNo));
1736     tmpInst.addOperand(MCOperand::createReg(RegNo));
1737     tmpInst.addOperand(MCOperand::createImm(ShiftAmount));
1738     tmpInst.setLoc(IDLoc);
1739     Instructions.push_back(tmpInst);
1740     tmpInst.clear();
1741   }
1742   // There's no need for an ORi if the immediate is 0.
1743   if (Operand.isImm() && Operand.getImm() == 0)
1744     return;
1745
1746   tmpInst.setOpcode(Mips::ORi);
1747   tmpInst.addOperand(MCOperand::createReg(RegNo));
1748   tmpInst.addOperand(MCOperand::createReg(RegNo));
1749   tmpInst.addOperand(Operand);
1750   tmpInst.setLoc(IDLoc);
1751   Instructions.push_back(tmpInst);
1752 }
1753
1754 template <unsigned ShiftAmount>
1755 void createLShiftOri(int64_t Value, unsigned RegNo, SMLoc IDLoc,
1756                      SmallVectorImpl<MCInst> &Instructions) {
1757   createLShiftOri<ShiftAmount>(MCOperand::createImm(Value), RegNo, IDLoc,
1758                                Instructions);
1759 }
1760 }
1761
1762 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
1763                                       SmallVectorImpl<MCInst> &Instructions) {
1764   // Create a JALR instruction which is going to replace the pseudo-JAL.
1765   MCInst JalrInst;
1766   JalrInst.setLoc(IDLoc);
1767   const MCOperand FirstRegOp = Inst.getOperand(0);
1768   const unsigned Opcode = Inst.getOpcode();
1769
1770   if (Opcode == Mips::JalOneReg) {
1771     // jal $rs => jalr $rs
1772     if (inMicroMipsMode()) {
1773       JalrInst.setOpcode(Mips::JALR16_MM);
1774       JalrInst.addOperand(FirstRegOp);
1775     } else {
1776       JalrInst.setOpcode(Mips::JALR);
1777       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
1778       JalrInst.addOperand(FirstRegOp);
1779     }
1780   } else if (Opcode == Mips::JalTwoReg) {
1781     // jal $rd, $rs => jalr $rd, $rs
1782     JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
1783     JalrInst.addOperand(FirstRegOp);
1784     const MCOperand SecondRegOp = Inst.getOperand(1);
1785     JalrInst.addOperand(SecondRegOp);
1786   }
1787   Instructions.push_back(JalrInst);
1788
1789   // If .set reorder is active, emit a NOP after it.
1790   if (AssemblerOptions.back()->isReorder()) {
1791     // This is a 32-bit NOP because these 2 pseudo-instructions
1792     // do not have a short delay slot.
1793     MCInst NopInst;
1794     NopInst.setOpcode(Mips::SLL);
1795     NopInst.addOperand(MCOperand::createReg(Mips::ZERO));
1796     NopInst.addOperand(MCOperand::createReg(Mips::ZERO));
1797     NopInst.addOperand(MCOperand::createImm(0));
1798     Instructions.push_back(NopInst);
1799   }
1800
1801   return false;
1802 }
1803
1804 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
1805                                   unsigned SrcReg, bool Is32BitImm, SMLoc IDLoc,
1806                                   SmallVectorImpl<MCInst> &Instructions) {
1807   if (!Is32BitImm && !isGP64bit()) {
1808     Error(IDLoc, "instruction requires a 64-bit architecture");
1809     return true;
1810   }
1811
1812   bool UseSrcReg = false;
1813   if (SrcReg != Mips::NoRegister)
1814     UseSrcReg = true;
1815
1816   MCInst tmpInst;
1817
1818   unsigned TmpReg = DstReg;
1819   if (UseSrcReg && (DstReg == SrcReg)) {
1820     // At this point we need AT to perform the expansions and we exit if it is
1821     // not available.
1822     unsigned ATReg = getATReg(IDLoc);
1823     if (!ATReg)
1824       return true;
1825     TmpReg = ATReg;
1826   }
1827
1828   tmpInst.setLoc(IDLoc);
1829   // FIXME: gas has a special case for values that are 000...1111, which
1830   // becomes a li -1 and then a dsrl
1831   if (0 <= ImmValue && ImmValue <= 65535) {
1832     // For unsigned and positive signed 16-bit values (0 <= j <= 65535):
1833     // li d,j => ori d,$zero,j
1834     if (!UseSrcReg)
1835       SrcReg = isGP64bit() ? Mips::ZERO_64 : Mips::ZERO;
1836     tmpInst.setOpcode(Mips::ORi);
1837     tmpInst.addOperand(MCOperand::createReg(DstReg));
1838     tmpInst.addOperand(MCOperand::createReg(SrcReg));
1839     tmpInst.addOperand(MCOperand::createImm(ImmValue));
1840     Instructions.push_back(tmpInst);
1841   } else if (ImmValue < 0 && ImmValue >= -32768) {
1842     // For negative signed 16-bit values (-32768 <= j < 0):
1843     // li d,j => addiu d,$zero,j
1844     if (!UseSrcReg)
1845       SrcReg = Mips::ZERO;
1846     tmpInst.setOpcode(Mips::ADDiu);
1847     tmpInst.addOperand(MCOperand::createReg(DstReg));
1848     tmpInst.addOperand(MCOperand::createReg(SrcReg));
1849     tmpInst.addOperand(MCOperand::createImm(ImmValue));
1850     Instructions.push_back(tmpInst);
1851   } else if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
1852     warnIfNoMacro(IDLoc);
1853
1854     // For all other values which are representable as a 32-bit integer:
1855     // li d,j => lui d,hi16(j)
1856     //           ori d,d,lo16(j)
1857     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
1858     uint16_t Bits15To0 = ImmValue & 0xffff;
1859
1860     if (!Is32BitImm && !isInt<32>(ImmValue)) {
1861       // For DLI, expand to an ORi instead of a LUi to avoid sign-extending the
1862       // upper 32 bits.
1863       tmpInst.setOpcode(Mips::ORi);
1864       tmpInst.addOperand(MCOperand::createReg(TmpReg));
1865       tmpInst.addOperand(MCOperand::createReg(Mips::ZERO));
1866       tmpInst.addOperand(MCOperand::createImm(Bits31To16));
1867       tmpInst.setLoc(IDLoc);
1868       Instructions.push_back(tmpInst);
1869       // Move the value to the upper 16 bits by doing a 16-bit left shift.
1870       createLShiftOri<16>(0, TmpReg, IDLoc, Instructions);
1871     } else {
1872       tmpInst.setOpcode(Mips::LUi);
1873       tmpInst.addOperand(MCOperand::createReg(TmpReg));
1874       tmpInst.addOperand(MCOperand::createImm(Bits31To16));
1875       Instructions.push_back(tmpInst);
1876     }
1877     createLShiftOri<0>(Bits15To0, TmpReg, IDLoc, Instructions);
1878
1879     if (UseSrcReg)
1880       createAddu(DstReg, TmpReg, SrcReg, !Is32BitImm, Instructions);
1881
1882   } else if ((ImmValue & (0xffffLL << 48)) == 0) {
1883     if (Is32BitImm) {
1884       Error(IDLoc, "instruction requires a 32-bit immediate");
1885       return true;
1886     }
1887     warnIfNoMacro(IDLoc);
1888
1889     //            <-------  lo32 ------>
1890     // <-------  hi32 ------>
1891     // <- hi16 ->             <- lo16 ->
1892     //  _________________________________
1893     // |          |          |          |
1894     // | 16-bits  | 16-bits  | 16-bits  |
1895     // |__________|__________|__________|
1896     //
1897     // For any 64-bit value that is representable as a 48-bit integer:
1898     // li d,j => lui d,hi16(j)
1899     //           ori d,d,hi16(lo32(j))
1900     //           dsll d,d,16
1901     //           ori d,d,lo16(lo32(j))
1902     uint16_t Bits47To32 = (ImmValue >> 32) & 0xffff;
1903     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
1904     uint16_t Bits15To0 = ImmValue & 0xffff;
1905
1906     tmpInst.setOpcode(Mips::LUi);
1907     tmpInst.addOperand(MCOperand::createReg(TmpReg));
1908     tmpInst.addOperand(MCOperand::createImm(Bits47To32));
1909     Instructions.push_back(tmpInst);
1910     createLShiftOri<0>(Bits31To16, TmpReg, IDLoc, Instructions);
1911     createLShiftOri<16>(Bits15To0, TmpReg, IDLoc, Instructions);
1912
1913     if (UseSrcReg)
1914       createAddu(DstReg, TmpReg, SrcReg, !Is32BitImm, Instructions);
1915
1916   } else {
1917     if (Is32BitImm) {
1918       Error(IDLoc, "instruction requires a 32-bit immediate");
1919       return true;
1920     }
1921     warnIfNoMacro(IDLoc);
1922
1923     // <-------  hi32 ------> <-------  lo32 ------>
1924     // <- hi16 ->                        <- lo16 ->
1925     //  ___________________________________________
1926     // |          |          |          |          |
1927     // | 16-bits  | 16-bits  | 16-bits  | 16-bits  |
1928     // |__________|__________|__________|__________|
1929     //
1930     // For all other values which are representable as a 64-bit integer:
1931     // li d,j => lui d,hi16(j)
1932     //           ori d,d,lo16(hi32(j))
1933     //           dsll d,d,16
1934     //           ori d,d,hi16(lo32(j))
1935     //           dsll d,d,16
1936     //           ori d,d,lo16(lo32(j))
1937     uint16_t Bits63To48 = (ImmValue >> 48) & 0xffff;
1938     uint16_t Bits47To32 = (ImmValue >> 32) & 0xffff;
1939     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
1940     uint16_t Bits15To0 = ImmValue & 0xffff;
1941
1942     tmpInst.setOpcode(Mips::LUi);
1943     tmpInst.addOperand(MCOperand::createReg(TmpReg));
1944     tmpInst.addOperand(MCOperand::createImm(Bits63To48));
1945     Instructions.push_back(tmpInst);
1946     createLShiftOri<0>(Bits47To32, TmpReg, IDLoc, Instructions);
1947
1948     // When Bits31To16 is 0, do a left shift of 32 bits instead of doing
1949     // two left shifts of 16 bits.
1950     if (Bits31To16 == 0) {
1951       createLShiftOri<32>(Bits15To0, TmpReg, IDLoc, Instructions);
1952     } else {
1953       createLShiftOri<16>(Bits31To16, TmpReg, IDLoc, Instructions);
1954       createLShiftOri<16>(Bits15To0, TmpReg, IDLoc, Instructions);
1955     }
1956
1957     if (UseSrcReg)
1958       createAddu(DstReg, TmpReg, SrcReg, !Is32BitImm, Instructions);
1959   }
1960   return false;
1961 }
1962
1963 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
1964                                   SmallVectorImpl<MCInst> &Instructions) {
1965   const MCOperand &ImmOp = Inst.getOperand(1);
1966   assert(ImmOp.isImm() && "expected immediate operand kind");
1967   const MCOperand &DstRegOp = Inst.getOperand(0);
1968   assert(DstRegOp.isReg() && "expected register operand kind");
1969
1970   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
1971                     Is32BitImm, IDLoc, Instructions))
1972     return true;
1973
1974   return false;
1975 }
1976
1977 bool
1978 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
1979                                     SmallVectorImpl<MCInst> &Instructions) {
1980   const MCOperand &DstRegOp = Inst.getOperand(0);
1981   assert(DstRegOp.isReg() && "expected register operand kind");
1982
1983   const MCOperand &SrcRegOp = Inst.getOperand(1);
1984   assert(SrcRegOp.isReg() && "expected register operand kind");
1985
1986   const MCOperand &ImmOp = Inst.getOperand(2);
1987   assert((ImmOp.isImm() || ImmOp.isExpr()) &&
1988          "expected immediate operand kind");
1989   if (!ImmOp.isImm()) {
1990     if (loadAndAddSymbolAddress(ImmOp.getExpr(), DstRegOp.getReg(),
1991                                 SrcRegOp.getReg(), Is32BitImm, IDLoc,
1992                                 Instructions))
1993       return true;
1994
1995     return false;
1996   }
1997
1998   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), SrcRegOp.getReg(),
1999                     Is32BitImm, IDLoc, Instructions))
2000     return true;
2001
2002   return false;
2003 }
2004
2005 bool
2006 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2007                                     SmallVectorImpl<MCInst> &Instructions) {
2008   const MCOperand &DstRegOp = Inst.getOperand(0);
2009   assert(DstRegOp.isReg() && "expected register operand kind");
2010
2011   const MCOperand &ImmOp = Inst.getOperand(1);
2012   assert((ImmOp.isImm() || ImmOp.isExpr()) &&
2013          "expected immediate operand kind");
2014   if (!ImmOp.isImm()) {
2015     if (loadAndAddSymbolAddress(ImmOp.getExpr(), DstRegOp.getReg(),
2016                                 Mips::NoRegister, Is32BitImm, IDLoc,
2017                                 Instructions))
2018       return true;
2019
2020     return false;
2021   }
2022
2023   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2024                     Is32BitImm, IDLoc, Instructions))
2025     return true;
2026
2027   return false;
2028 }
2029
2030 bool MipsAsmParser::loadAndAddSymbolAddress(
2031     const MCExpr *SymExpr, unsigned DstReg, unsigned SrcReg, bool Is32BitSym,
2032     SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
2033   warnIfNoMacro(IDLoc);
2034
2035   if (Is32BitSym && isABI_N64())
2036     Warning(IDLoc, "instruction loads the 32-bit address of a 64-bit symbol");
2037
2038   MCInst tmpInst;
2039   const MCSymbolRefExpr *Symbol = cast<MCSymbolRefExpr>(SymExpr);
2040   const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::create(
2041       &Symbol->getSymbol(), MCSymbolRefExpr::VK_Mips_ABS_HI, getContext());
2042   const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::create(
2043       &Symbol->getSymbol(), MCSymbolRefExpr::VK_Mips_ABS_LO, getContext());
2044
2045   bool UseSrcReg = SrcReg != Mips::NoRegister;
2046
2047   unsigned TmpReg = DstReg;
2048   if (UseSrcReg && (DstReg == SrcReg)) {
2049     // At this point we need AT to perform the expansions and we exit if it is
2050     // not available.
2051     unsigned ATReg = getATReg(IDLoc);
2052     if (!ATReg)
2053       return true;
2054     TmpReg = ATReg;
2055   }
2056
2057   if (!Is32BitSym) {
2058     // If it's a 64-bit architecture, expand to:
2059     // la d,sym => lui  d,highest(sym)
2060     //             ori  d,d,higher(sym)
2061     //             dsll d,d,16
2062     //             ori  d,d,hi16(sym)
2063     //             dsll d,d,16
2064     //             ori  d,d,lo16(sym)
2065     const MCSymbolRefExpr *HighestExpr = MCSymbolRefExpr::create(
2066         &Symbol->getSymbol(), MCSymbolRefExpr::VK_Mips_HIGHEST, getContext());
2067     const MCSymbolRefExpr *HigherExpr = MCSymbolRefExpr::create(
2068         &Symbol->getSymbol(), MCSymbolRefExpr::VK_Mips_HIGHER, getContext());
2069
2070     tmpInst.setOpcode(Mips::LUi);
2071     tmpInst.addOperand(MCOperand::createReg(TmpReg));
2072     tmpInst.addOperand(MCOperand::createExpr(HighestExpr));
2073     Instructions.push_back(tmpInst);
2074
2075     createLShiftOri<0>(MCOperand::createExpr(HigherExpr), TmpReg, SMLoc(),
2076                        Instructions);
2077     createLShiftOri<16>(MCOperand::createExpr(HiExpr), TmpReg, SMLoc(),
2078                         Instructions);
2079     createLShiftOri<16>(MCOperand::createExpr(LoExpr), TmpReg, SMLoc(),
2080                         Instructions);
2081   } else {
2082     // Otherwise, expand to:
2083     // la d,sym => lui  d,hi16(sym)
2084     //             ori  d,d,lo16(sym)
2085     tmpInst.setOpcode(Mips::LUi);
2086     tmpInst.addOperand(MCOperand::createReg(TmpReg));
2087     tmpInst.addOperand(MCOperand::createExpr(HiExpr));
2088     Instructions.push_back(tmpInst);
2089
2090     createLShiftOri<0>(MCOperand::createExpr(LoExpr), TmpReg, SMLoc(),
2091                        Instructions);
2092   }
2093
2094   if (UseSrcReg)
2095     createAddu(DstReg, TmpReg, SrcReg, !Is32BitSym, Instructions);
2096
2097   return false;
2098 }
2099
2100 bool MipsAsmParser::expandUncondBranchMMPseudo(
2101     MCInst &Inst, SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
2102   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
2103          "unexpected number of operands");
2104
2105   MCOperand Offset = Inst.getOperand(0);
2106   if (Offset.isExpr()) {
2107     Inst.clear();
2108     Inst.setOpcode(Mips::BEQ_MM);
2109     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2110     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2111     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
2112   } else {
2113     assert(Offset.isImm() && "expected immediate operand kind");
2114     if (isIntN(11, Offset.getImm())) {
2115       // If offset fits into 11 bits then this instruction becomes microMIPS
2116       // 16-bit unconditional branch instruction.
2117       Inst.setOpcode(Mips::B16_MM);
2118     } else {
2119       if (!isIntN(17, Offset.getImm()))
2120         Error(IDLoc, "branch target out of range");
2121       if (OffsetToAlignment(Offset.getImm(), 1LL << 1))
2122         Error(IDLoc, "branch to misaligned address");
2123       Inst.clear();
2124       Inst.setOpcode(Mips::BEQ_MM);
2125       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2126       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2127       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
2128     }
2129   }
2130   Instructions.push_back(Inst);
2131
2132   // If .set reorder is active, emit a NOP after the branch instruction.
2133   if (AssemblerOptions.back()->isReorder())
2134     createNop(true, IDLoc, Instructions);
2135
2136   return false;
2137 }
2138
2139 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc,
2140                                     SmallVectorImpl<MCInst> &Instructions) {
2141   const MCOperand &DstRegOp = Inst.getOperand(0);
2142   assert(DstRegOp.isReg() && "expected register operand kind");
2143
2144   const MCOperand &ImmOp = Inst.getOperand(1);
2145   assert(ImmOp.isImm() && "expected immediate operand kind");
2146
2147   const MCOperand &MemOffsetOp = Inst.getOperand(2);
2148   assert(MemOffsetOp.isImm() && "expected immediate operand kind");
2149
2150   unsigned OpCode = 0;
2151   switch(Inst.getOpcode()) {
2152     case Mips::BneImm:
2153       OpCode = Mips::BNE;
2154       break;
2155     case Mips::BeqImm:
2156       OpCode = Mips::BEQ;
2157       break;
2158     default:
2159       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
2160       break;
2161   }
2162
2163   int64_t ImmValue = ImmOp.getImm();
2164   if (ImmValue == 0) {
2165     MCInst BranchInst;
2166     BranchInst.setOpcode(OpCode);
2167     BranchInst.addOperand(DstRegOp);
2168     BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2169     BranchInst.addOperand(MemOffsetOp);
2170     Instructions.push_back(BranchInst);
2171   } else {
2172     warnIfNoMacro(IDLoc);
2173
2174     unsigned ATReg = getATReg(IDLoc);
2175     if (!ATReg)
2176       return true;
2177
2178     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), IDLoc,
2179                       Instructions))
2180       return true;
2181
2182     MCInst BranchInst;
2183     BranchInst.setOpcode(OpCode);
2184     BranchInst.addOperand(DstRegOp);
2185     BranchInst.addOperand(MCOperand::createReg(ATReg));
2186     BranchInst.addOperand(MemOffsetOp);
2187     Instructions.push_back(BranchInst);
2188   }
2189   return false;
2190 }
2191
2192 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
2193                                   SmallVectorImpl<MCInst> &Instructions,
2194                                   bool isLoad, bool isImmOpnd) {
2195   MCInst TempInst;
2196   unsigned ImmOffset, HiOffset, LoOffset;
2197   const MCExpr *ExprOffset;
2198   unsigned TmpRegNum;
2199   // 1st operand is either the source or destination register.
2200   assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2201   unsigned RegOpNum = Inst.getOperand(0).getReg();
2202   // 2nd operand is the base register.
2203   assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2204   unsigned BaseRegNum = Inst.getOperand(1).getReg();
2205   // 3rd operand is either an immediate or expression.
2206   if (isImmOpnd) {
2207     assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
2208     ImmOffset = Inst.getOperand(2).getImm();
2209     LoOffset = ImmOffset & 0x0000ffff;
2210     HiOffset = (ImmOffset & 0xffff0000) >> 16;
2211     // If msb of LoOffset is 1(negative number) we must increment HiOffset.
2212     if (LoOffset & 0x8000)
2213       HiOffset++;
2214   } else
2215     ExprOffset = Inst.getOperand(2).getExpr();
2216   // All instructions will have the same location.
2217   TempInst.setLoc(IDLoc);
2218   // These are some of the types of expansions we perform here:
2219   // 1) lw $8, sym        => lui $8, %hi(sym)
2220   //                         lw $8, %lo(sym)($8)
2221   // 2) lw $8, offset($9) => lui $8, %hi(offset)
2222   //                         add $8, $8, $9
2223   //                         lw $8, %lo(offset)($9)
2224   // 3) lw $8, offset($8) => lui $at, %hi(offset)
2225   //                         add $at, $at, $8
2226   //                         lw $8, %lo(offset)($at)
2227   // 4) sw $8, sym        => lui $at, %hi(sym)
2228   //                         sw $8, %lo(sym)($at)
2229   // 5) sw $8, offset($8) => lui $at, %hi(offset)
2230   //                         add $at, $at, $8
2231   //                         sw $8, %lo(offset)($at)
2232   // 6) ldc1 $f0, sym     => lui $at, %hi(sym)
2233   //                         ldc1 $f0, %lo(sym)($at)
2234   //
2235   // For load instructions we can use the destination register as a temporary
2236   // if base and dst are different (examples 1 and 2) and if the base register
2237   // is general purpose otherwise we must use $at (example 6) and error if it's
2238   // not available. For stores we must use $at (examples 4 and 5) because we
2239   // must not clobber the source register setting up the offset.
2240   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
2241   int16_t RegClassOp0 = Desc.OpInfo[0].RegClass;
2242   unsigned RegClassIDOp0 =
2243       getContext().getRegisterInfo()->getRegClass(RegClassOp0).getID();
2244   bool IsGPR = (RegClassIDOp0 == Mips::GPR32RegClassID) ||
2245                (RegClassIDOp0 == Mips::GPR64RegClassID);
2246   if (isLoad && IsGPR && (BaseRegNum != RegOpNum))
2247     TmpRegNum = RegOpNum;
2248   else {
2249     // At this point we need AT to perform the expansions and we exit if it is
2250     // not available.
2251     TmpRegNum = getATReg(IDLoc);
2252     if (!TmpRegNum)
2253       return;
2254   }
2255
2256   TempInst.setOpcode(Mips::LUi);
2257   TempInst.addOperand(MCOperand::createReg(TmpRegNum));
2258   if (isImmOpnd)
2259     TempInst.addOperand(MCOperand::createImm(HiOffset));
2260   else {
2261     const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
2262     TempInst.addOperand(MCOperand::createExpr(HiExpr));
2263   }
2264   // Add the instruction to the list.
2265   Instructions.push_back(TempInst);
2266   // Prepare TempInst for next instruction.
2267   TempInst.clear();
2268   // Add temp register to base.
2269   if (BaseRegNum != Mips::ZERO) {
2270     TempInst.setOpcode(Mips::ADDu);
2271     TempInst.addOperand(MCOperand::createReg(TmpRegNum));
2272     TempInst.addOperand(MCOperand::createReg(TmpRegNum));
2273     TempInst.addOperand(MCOperand::createReg(BaseRegNum));
2274     Instructions.push_back(TempInst);
2275     TempInst.clear();
2276   }
2277   // And finally, create original instruction with low part
2278   // of offset and new base.
2279   TempInst.setOpcode(Inst.getOpcode());
2280   TempInst.addOperand(MCOperand::createReg(RegOpNum));
2281   TempInst.addOperand(MCOperand::createReg(TmpRegNum));
2282   if (isImmOpnd)
2283     TempInst.addOperand(MCOperand::createImm(LoOffset));
2284   else {
2285     const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
2286     TempInst.addOperand(MCOperand::createExpr(LoExpr));
2287   }
2288   Instructions.push_back(TempInst);
2289   TempInst.clear();
2290 }
2291
2292 bool
2293 MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
2294                                        SmallVectorImpl<MCInst> &Instructions) {
2295   unsigned OpNum = Inst.getNumOperands();
2296   unsigned Opcode = Inst.getOpcode();
2297   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
2298
2299   assert (Inst.getOperand(OpNum - 1).isImm() &&
2300           Inst.getOperand(OpNum - 2).isReg() &&
2301           Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
2302
2303   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
2304       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
2305       Inst.getOperand(OpNum - 2).getReg() == Mips::SP &&
2306       Inst.getOperand(OpNum - 3).getReg() == Mips::RA)
2307     // It can be implemented as SWM16 or LWM16 instruction.
2308     NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
2309
2310   Inst.setOpcode(NewOpcode);
2311   Instructions.push_back(Inst);
2312   return false;
2313 }
2314
2315 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
2316                                        SmallVectorImpl<MCInst> &Instructions) {
2317   unsigned PseudoOpcode = Inst.getOpcode();
2318   unsigned SrcReg = Inst.getOperand(0).getReg();
2319   unsigned TrgReg = Inst.getOperand(1).getReg();
2320   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
2321
2322   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
2323   bool ReverseOrderSLT, IsUnsigned, AcceptsEquality;
2324
2325   switch (PseudoOpcode) {
2326   case Mips::BLT:
2327   case Mips::BLTU:
2328     AcceptsEquality = false;
2329     ReverseOrderSLT = false;
2330     IsUnsigned = (PseudoOpcode == Mips::BLTU);
2331     ZeroSrcOpcode = Mips::BGTZ;
2332     ZeroTrgOpcode = Mips::BLTZ;
2333     break;
2334   case Mips::BLE:
2335   case Mips::BLEU:
2336     AcceptsEquality = true;
2337     ReverseOrderSLT = true;
2338     IsUnsigned = (PseudoOpcode == Mips::BLEU);
2339     ZeroSrcOpcode = Mips::BGEZ;
2340     ZeroTrgOpcode = Mips::BLEZ;
2341     break;
2342   case Mips::BGE:
2343   case Mips::BGEU:
2344     AcceptsEquality = true;
2345     ReverseOrderSLT = false;
2346     IsUnsigned = (PseudoOpcode == Mips::BGEU);
2347     ZeroSrcOpcode = Mips::BLEZ;
2348     ZeroTrgOpcode = Mips::BGEZ;
2349     break;
2350   case Mips::BGT:
2351   case Mips::BGTU:
2352     AcceptsEquality = false;
2353     ReverseOrderSLT = true;
2354     IsUnsigned = (PseudoOpcode == Mips::BGTU);
2355     ZeroSrcOpcode = Mips::BLTZ;
2356     ZeroTrgOpcode = Mips::BGTZ;
2357     break;
2358   default:
2359     llvm_unreachable("unknown opcode for branch pseudo-instruction");
2360   }
2361
2362   MCInst BranchInst;
2363   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
2364   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
2365   if (IsSrcRegZero && IsTrgRegZero) {
2366     // FIXME: All of these Opcode-specific if's are needed for compatibility
2367     // with GAS' behaviour. However, they may not generate the most efficient
2368     // code in some circumstances.
2369     if (PseudoOpcode == Mips::BLT) {
2370       BranchInst.setOpcode(Mips::BLTZ);
2371       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2372       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2373       Instructions.push_back(BranchInst);
2374       return false;
2375     }
2376     if (PseudoOpcode == Mips::BLE) {
2377       BranchInst.setOpcode(Mips::BLEZ);
2378       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2379       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2380       Instructions.push_back(BranchInst);
2381       Warning(IDLoc, "branch is always taken");
2382       return false;
2383     }
2384     if (PseudoOpcode == Mips::BGE) {
2385       BranchInst.setOpcode(Mips::BGEZ);
2386       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2387       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2388       Instructions.push_back(BranchInst);
2389       Warning(IDLoc, "branch is always taken");
2390       return false;
2391     }
2392     if (PseudoOpcode == Mips::BGT) {
2393       BranchInst.setOpcode(Mips::BGTZ);
2394       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2395       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2396       Instructions.push_back(BranchInst);
2397       return false;
2398     }
2399     if (PseudoOpcode == Mips::BGTU) {
2400       BranchInst.setOpcode(Mips::BNE);
2401       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2402       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2403       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2404       Instructions.push_back(BranchInst);
2405       return false;
2406     }
2407     if (AcceptsEquality) {
2408       // If both registers are $0 and the pseudo-branch accepts equality, it
2409       // will always be taken, so we emit an unconditional branch.
2410       BranchInst.setOpcode(Mips::BEQ);
2411       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2412       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2413       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2414       Instructions.push_back(BranchInst);
2415       Warning(IDLoc, "branch is always taken");
2416       return false;
2417     }
2418     // If both registers are $0 and the pseudo-branch does not accept
2419     // equality, it will never be taken, so we don't have to emit anything.
2420     return false;
2421   }
2422   if (IsSrcRegZero || IsTrgRegZero) {
2423     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
2424         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
2425       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
2426       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
2427       // the pseudo-branch will never be taken, so we don't emit anything.
2428       // This only applies to unsigned pseudo-branches.
2429       return false;
2430     }
2431     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
2432         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
2433       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
2434       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
2435       // the pseudo-branch will always be taken, so we emit an unconditional
2436       // branch.
2437       // This only applies to unsigned pseudo-branches.
2438       BranchInst.setOpcode(Mips::BEQ);
2439       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2440       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2441       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2442       Instructions.push_back(BranchInst);
2443       Warning(IDLoc, "branch is always taken");
2444       return false;
2445     }
2446     if (IsUnsigned) {
2447       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
2448       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
2449       // the pseudo-branch will be taken only when the non-zero register is
2450       // different from 0, so we emit a BNEZ.
2451       //
2452       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
2453       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
2454       // the pseudo-branch will be taken only when the non-zero register is
2455       // equal to 0, so we emit a BEQZ.
2456       //
2457       // Because only BLEU and BGEU branch on equality, we can use the
2458       // AcceptsEquality variable to decide when to emit the BEQZ.
2459       BranchInst.setOpcode(AcceptsEquality ? Mips::BEQ : Mips::BNE);
2460       BranchInst.addOperand(
2461           MCOperand::createReg(IsSrcRegZero ? TrgReg : SrcReg));
2462       BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2463       BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2464       Instructions.push_back(BranchInst);
2465       return false;
2466     }
2467     // If we have a signed pseudo-branch and one of the registers is $0,
2468     // we can use an appropriate compare-to-zero branch. We select which one
2469     // to use in the switch statement above.
2470     BranchInst.setOpcode(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode);
2471     BranchInst.addOperand(MCOperand::createReg(IsSrcRegZero ? TrgReg : SrcReg));
2472     BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2473     Instructions.push_back(BranchInst);
2474     return false;
2475   }
2476
2477   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
2478   // expansions. If it is not available, we return.
2479   unsigned ATRegNum = getATReg(IDLoc);
2480   if (!ATRegNum)
2481     return true;
2482
2483   warnIfNoMacro(IDLoc);
2484
2485   // SLT fits well with 2 of our 4 pseudo-branches:
2486   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
2487   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
2488   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
2489   // This is accomplished by using a BNEZ with the result of the SLT.
2490   //
2491   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
2492   // and BLE with BGT), so we change the BNEZ into a a BEQZ.
2493   // Because only BGE and BLE branch on equality, we can use the
2494   // AcceptsEquality variable to decide when to emit the BEQZ.
2495   // Note that the order of the SLT arguments doesn't change between
2496   // opposites.
2497   //
2498   // The same applies to the unsigned variants, except that SLTu is used
2499   // instead of SLT.
2500   MCInst SetInst;
2501   SetInst.setOpcode(IsUnsigned ? Mips::SLTu : Mips::SLT);
2502   SetInst.addOperand(MCOperand::createReg(ATRegNum));
2503   SetInst.addOperand(MCOperand::createReg(ReverseOrderSLT ? TrgReg : SrcReg));
2504   SetInst.addOperand(MCOperand::createReg(ReverseOrderSLT ? SrcReg : TrgReg));
2505   Instructions.push_back(SetInst);
2506
2507   BranchInst.setOpcode(AcceptsEquality ? Mips::BEQ : Mips::BNE);
2508   BranchInst.addOperand(MCOperand::createReg(ATRegNum));
2509   BranchInst.addOperand(MCOperand::createReg(Mips::ZERO));
2510   BranchInst.addOperand(MCOperand::createExpr(OffsetExpr));
2511   Instructions.push_back(BranchInst);
2512   return false;
2513 }
2514
2515 bool MipsAsmParser::expandUlhu(MCInst &Inst, SMLoc IDLoc,
2516                                SmallVectorImpl<MCInst> &Instructions) {
2517   if (hasMips32r6() || hasMips64r6()) {
2518     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
2519     return false;
2520   }
2521
2522   warnIfNoMacro(IDLoc);
2523
2524   const MCOperand &DstRegOp = Inst.getOperand(0);
2525   assert(DstRegOp.isReg() && "expected register operand kind");
2526
2527   const MCOperand &SrcRegOp = Inst.getOperand(1);
2528   assert(SrcRegOp.isReg() && "expected register operand kind");
2529
2530   const MCOperand &OffsetImmOp = Inst.getOperand(2);
2531   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
2532
2533   unsigned DstReg = DstRegOp.getReg();
2534   unsigned SrcReg = SrcRegOp.getReg();
2535   int64_t OffsetValue = OffsetImmOp.getImm();
2536
2537   // NOTE: We always need AT for ULHU, as it is always used as the source
2538   // register for one of the LBu's.
2539   unsigned ATReg = getATReg(IDLoc);
2540   if (!ATReg)
2541     return true;
2542
2543   // When the value of offset+1 does not fit in 16 bits, we have to load the
2544   // offset in AT, (D)ADDu the original source register (if there was one), and
2545   // then use AT as the source register for the 2 generated LBu's.
2546   bool LoadedOffsetInAT = false;
2547   if (!isInt<16>(OffsetValue + 1) || !isInt<16>(OffsetValue)) {
2548     LoadedOffsetInAT = true;
2549
2550     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
2551                       IDLoc, Instructions))
2552       return true;
2553
2554     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
2555     // because it will make our output more similar to GAS'. For example,
2556     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
2557     // instead of just an "ori $1, $9, 32768".
2558     // NOTE: If there is no source register specified in the ULHU, the parser
2559     // will interpret it as $0.
2560     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
2561       createAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), Instructions);
2562   }
2563
2564   unsigned FirstLbuDstReg = LoadedOffsetInAT ? DstReg : ATReg;
2565   unsigned SecondLbuDstReg = LoadedOffsetInAT ? ATReg : DstReg;
2566   unsigned LbuSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
2567
2568   int64_t FirstLbuOffset = 0, SecondLbuOffset = 0;
2569   if (isLittle()) {
2570     FirstLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
2571     SecondLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
2572   } else {
2573     FirstLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
2574     SecondLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
2575   }
2576
2577   unsigned SllReg = LoadedOffsetInAT ? DstReg : ATReg;
2578
2579   MCInst TmpInst;
2580   TmpInst.setOpcode(Mips::LBu);
2581   TmpInst.addOperand(MCOperand::createReg(FirstLbuDstReg));
2582   TmpInst.addOperand(MCOperand::createReg(LbuSrcReg));
2583   TmpInst.addOperand(MCOperand::createImm(FirstLbuOffset));
2584   Instructions.push_back(TmpInst);
2585
2586   TmpInst.clear();
2587   TmpInst.setOpcode(Mips::LBu);
2588   TmpInst.addOperand(MCOperand::createReg(SecondLbuDstReg));
2589   TmpInst.addOperand(MCOperand::createReg(LbuSrcReg));
2590   TmpInst.addOperand(MCOperand::createImm(SecondLbuOffset));
2591   Instructions.push_back(TmpInst);
2592
2593   TmpInst.clear();
2594   TmpInst.setOpcode(Mips::SLL);
2595   TmpInst.addOperand(MCOperand::createReg(SllReg));
2596   TmpInst.addOperand(MCOperand::createReg(SllReg));
2597   TmpInst.addOperand(MCOperand::createImm(8));
2598   Instructions.push_back(TmpInst);
2599
2600   TmpInst.clear();
2601   TmpInst.setOpcode(Mips::OR);
2602   TmpInst.addOperand(MCOperand::createReg(DstReg));
2603   TmpInst.addOperand(MCOperand::createReg(DstReg));
2604   TmpInst.addOperand(MCOperand::createReg(ATReg));
2605   Instructions.push_back(TmpInst);
2606
2607   return false;
2608 }
2609
2610 bool MipsAsmParser::expandUlw(MCInst &Inst, SMLoc IDLoc,
2611                               SmallVectorImpl<MCInst> &Instructions) {
2612   if (hasMips32r6() || hasMips64r6()) {
2613     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
2614     return false;
2615   }
2616
2617   const MCOperand &DstRegOp = Inst.getOperand(0);
2618   assert(DstRegOp.isReg() && "expected register operand kind");
2619
2620   const MCOperand &SrcRegOp = Inst.getOperand(1);
2621   assert(SrcRegOp.isReg() && "expected register operand kind");
2622
2623   const MCOperand &OffsetImmOp = Inst.getOperand(2);
2624   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
2625
2626   unsigned SrcReg = SrcRegOp.getReg();
2627   int64_t OffsetValue = OffsetImmOp.getImm();
2628   unsigned ATReg = 0;
2629
2630   // When the value of offset+3 does not fit in 16 bits, we have to load the
2631   // offset in AT, (D)ADDu the original source register (if there was one), and
2632   // then use AT as the source register for the generated LWL and LWR.
2633   bool LoadedOffsetInAT = false;
2634   if (!isInt<16>(OffsetValue + 3) || !isInt<16>(OffsetValue)) {
2635     ATReg = getATReg(IDLoc);
2636     if (!ATReg)
2637       return true;
2638     LoadedOffsetInAT = true;
2639
2640     warnIfNoMacro(IDLoc);
2641
2642     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
2643                       IDLoc, Instructions))
2644       return true;
2645
2646     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
2647     // because it will make our output more similar to GAS'. For example,
2648     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
2649     // instead of just an "ori $1, $9, 32768".
2650     // NOTE: If there is no source register specified in the ULW, the parser
2651     // will interpret it as $0.
2652     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
2653       createAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), Instructions);
2654   }
2655
2656   unsigned FinalSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
2657   int64_t LeftLoadOffset = 0, RightLoadOffset  = 0;
2658   if (isLittle()) {
2659     LeftLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
2660     RightLoadOffset  = LoadedOffsetInAT ? 0 : OffsetValue;
2661   } else {
2662     LeftLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue;
2663     RightLoadOffset  = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
2664   }
2665
2666   MCInst LeftLoadInst;
2667   LeftLoadInst.setOpcode(Mips::LWL);
2668   LeftLoadInst.addOperand(DstRegOp);
2669   LeftLoadInst.addOperand(MCOperand::createReg(FinalSrcReg));
2670   LeftLoadInst.addOperand(MCOperand::createImm(LeftLoadOffset));
2671   Instructions.push_back(LeftLoadInst);
2672
2673   MCInst RightLoadInst;
2674   RightLoadInst.setOpcode(Mips::LWR);
2675   RightLoadInst.addOperand(DstRegOp);
2676   RightLoadInst.addOperand(MCOperand::createReg(FinalSrcReg));
2677   RightLoadInst.addOperand(MCOperand::createImm(RightLoadOffset ));
2678   Instructions.push_back(RightLoadInst);
2679
2680   return false;
2681 }
2682
2683 void MipsAsmParser::createNop(bool hasShortDelaySlot, SMLoc IDLoc,
2684                               SmallVectorImpl<MCInst> &Instructions) {
2685   MCInst NopInst;
2686   if (hasShortDelaySlot) {
2687     NopInst.setOpcode(Mips::MOVE16_MM);
2688     NopInst.addOperand(MCOperand::createReg(Mips::ZERO));
2689     NopInst.addOperand(MCOperand::createReg(Mips::ZERO));
2690   } else {
2691     NopInst.setOpcode(Mips::SLL);
2692     NopInst.addOperand(MCOperand::createReg(Mips::ZERO));
2693     NopInst.addOperand(MCOperand::createReg(Mips::ZERO));
2694     NopInst.addOperand(MCOperand::createImm(0));
2695   }
2696   Instructions.push_back(NopInst);
2697 }
2698
2699 void MipsAsmParser::createAddu(unsigned DstReg, unsigned SrcReg,
2700                                unsigned TrgReg, bool Is64Bit,
2701                                SmallVectorImpl<MCInst> &Instructions) {
2702   MCInst AdduInst;
2703   AdduInst.setOpcode(Is64Bit ? Mips::DADDu : Mips::ADDu);
2704   AdduInst.addOperand(MCOperand::createReg(DstReg));
2705   AdduInst.addOperand(MCOperand::createReg(SrcReg));
2706   AdduInst.addOperand(MCOperand::createReg(TrgReg));
2707   Instructions.push_back(AdduInst);
2708 }
2709
2710 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
2711   // As described by the Mips32r2 spec, the registers Rd and Rs for
2712   // jalr.hb must be different.
2713   unsigned Opcode = Inst.getOpcode();
2714
2715   if (Opcode == Mips::JALR_HB &&
2716       (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()))
2717     return Match_RequiresDifferentSrcAndDst;
2718
2719   return Match_Success;
2720 }
2721
2722 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2723                                             OperandVector &Operands,
2724                                             MCStreamer &Out,
2725                                             uint64_t &ErrorInfo,
2726                                             FeatureBitset &ErrorMissingFeature,
2727                                             bool MatchingInlineAsm) {
2728
2729   MCInst Inst;
2730   SmallVector<MCInst, 8> Instructions;
2731   unsigned MatchResult =
2732       MatchInstructionImpl(Operands, Inst, ErrorInfo, ErrorMissingFeature, MatchingInlineAsm);
2733
2734   switch (MatchResult) {
2735   case Match_Success: {
2736     if (processInstruction(Inst, IDLoc, Instructions))
2737       return true;
2738     for (unsigned i = 0; i < Instructions.size(); i++)
2739       Out.EmitInstruction(Instructions[i], STI);
2740     return false;
2741   }
2742   case Match_MissingFeature:
2743     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
2744     return true;
2745   case Match_InvalidOperand: {
2746     SMLoc ErrorLoc = IDLoc;
2747     if (ErrorInfo != ~0ULL) {
2748       if (ErrorInfo >= Operands.size())
2749         return Error(IDLoc, "too few operands for instruction");
2750
2751       ErrorLoc = ((MipsOperand &)*Operands[ErrorInfo]).getStartLoc();
2752       if (ErrorLoc == SMLoc())
2753         ErrorLoc = IDLoc;
2754     }
2755
2756     return Error(ErrorLoc, "invalid operand for instruction");
2757   }
2758   case Match_MnemonicFail:
2759     return Error(IDLoc, "invalid instruction");
2760   case Match_RequiresDifferentSrcAndDst:
2761     return Error(IDLoc, "source and destination must be different");
2762   }
2763
2764   llvm_unreachable("Implement any new match types added!");
2765 }
2766
2767 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
2768   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
2769     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
2770                      ") without \".set noat\"");
2771 }
2772
2773 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
2774   if (!AssemblerOptions.back()->isMacro())
2775     Warning(Loc, "macro instruction expanded into multiple instructions");
2776 }
2777
2778 void
2779 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
2780                                      SMRange Range, bool ShowColors) {
2781   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
2782                                   Range, SMFixIt(Range, FixMsg),
2783                                   ShowColors);
2784 }
2785
2786 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
2787   int CC;
2788
2789   CC = StringSwitch<unsigned>(Name)
2790            .Case("zero", 0)
2791            .Case("at", 1)
2792            .Case("a0", 4)
2793            .Case("a1", 5)
2794            .Case("a2", 6)
2795            .Case("a3", 7)
2796            .Case("v0", 2)
2797            .Case("v1", 3)
2798            .Case("s0", 16)
2799            .Case("s1", 17)
2800            .Case("s2", 18)
2801            .Case("s3", 19)
2802            .Case("s4", 20)
2803            .Case("s5", 21)
2804            .Case("s6", 22)
2805            .Case("s7", 23)
2806            .Case("k0", 26)
2807            .Case("k1", 27)
2808            .Case("gp", 28)
2809            .Case("sp", 29)
2810            .Case("fp", 30)
2811            .Case("s8", 30)
2812            .Case("ra", 31)
2813            .Case("t0", 8)
2814            .Case("t1", 9)
2815            .Case("t2", 10)
2816            .Case("t3", 11)
2817            .Case("t4", 12)
2818            .Case("t5", 13)
2819            .Case("t6", 14)
2820            .Case("t7", 15)
2821            .Case("t8", 24)
2822            .Case("t9", 25)
2823            .Default(-1);
2824
2825   if (!(isABI_N32() || isABI_N64()))
2826     return CC;
2827
2828   if (12 <= CC && CC <= 15) {
2829     // Name is one of t4-t7
2830     AsmToken RegTok = getLexer().peekTok();
2831     SMRange RegRange = RegTok.getLocRange();
2832
2833     StringRef FixedName = StringSwitch<StringRef>(Name)
2834                               .Case("t4", "t0")
2835                               .Case("t5", "t1")
2836                               .Case("t6", "t2")
2837                               .Case("t7", "t3")
2838                               .Default("");
2839     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
2840
2841     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
2842                           "Did you mean $" + FixedName + "?", RegRange);
2843   }
2844
2845   // Although SGI documentation just cuts out t0-t3 for n32/n64,
2846   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
2847   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
2848   if (8 <= CC && CC <= 11)
2849     CC += 4;
2850
2851   if (CC == -1)
2852     CC = StringSwitch<unsigned>(Name)
2853              .Case("a4", 8)
2854              .Case("a5", 9)
2855              .Case("a6", 10)
2856              .Case("a7", 11)
2857              .Case("kt0", 26)
2858              .Case("kt1", 27)
2859              .Default(-1);
2860
2861   return CC;
2862 }
2863
2864 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
2865   int CC;
2866
2867   CC = StringSwitch<unsigned>(Name)
2868             .Case("hwr_cpunum", 0)
2869             .Case("hwr_synci_step", 1)
2870             .Case("hwr_cc", 2)
2871             .Case("hwr_ccres", 3)
2872             .Case("hwr_ulr", 29)
2873             .Default(-1);
2874
2875   return CC;
2876 }
2877
2878 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
2879
2880   if (Name[0] == 'f') {
2881     StringRef NumString = Name.substr(1);
2882     unsigned IntVal;
2883     if (NumString.getAsInteger(10, IntVal))
2884       return -1;     // This is not an integer.
2885     if (IntVal > 31) // Maximum index for fpu register.
2886       return -1;
2887     return IntVal;
2888   }
2889   return -1;
2890 }
2891
2892 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
2893
2894   if (Name.startswith("fcc")) {
2895     StringRef NumString = Name.substr(3);
2896     unsigned IntVal;
2897     if (NumString.getAsInteger(10, IntVal))
2898       return -1;    // This is not an integer.
2899     if (IntVal > 7) // There are only 8 fcc registers.
2900       return -1;
2901     return IntVal;
2902   }
2903   return -1;
2904 }
2905
2906 int MipsAsmParser::matchACRegisterName(StringRef Name) {
2907
2908   if (Name.startswith("ac")) {
2909     StringRef NumString = Name.substr(2);
2910     unsigned IntVal;
2911     if (NumString.getAsInteger(10, IntVal))
2912       return -1;    // This is not an integer.
2913     if (IntVal > 3) // There are only 3 acc registers.
2914       return -1;
2915     return IntVal;
2916   }
2917   return -1;
2918 }
2919
2920 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
2921   unsigned IntVal;
2922
2923   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
2924     return -1;
2925
2926   if (IntVal > 31)
2927     return -1;
2928
2929   return IntVal;
2930 }
2931
2932 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
2933   int CC;
2934
2935   CC = StringSwitch<unsigned>(Name)
2936            .Case("msair", 0)
2937            .Case("msacsr", 1)
2938            .Case("msaaccess", 2)
2939            .Case("msasave", 3)
2940            .Case("msamodify", 4)
2941            .Case("msarequest", 5)
2942            .Case("msamap", 6)
2943            .Case("msaunmap", 7)
2944            .Default(-1);
2945
2946   return CC;
2947 }
2948
2949 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
2950   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
2951   if (ATIndex == 0) {
2952     reportParseError(Loc,
2953                      "pseudo-instruction requires $at, which is not available");
2954     return 0;
2955   }
2956   unsigned AT = getReg(
2957       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
2958   return AT;
2959 }
2960
2961 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
2962   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
2963 }
2964
2965 unsigned MipsAsmParser::getGPR(int RegNo) {
2966   return getReg(isGP64bit() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
2967                 RegNo);
2968 }
2969
2970 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
2971   if (RegNum >
2972       getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
2973     return -1;
2974
2975   return getReg(RegClass, RegNum);
2976 }
2977
2978 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2979   MCAsmParser &Parser = getParser();
2980   DEBUG(dbgs() << "parseOperand\n");
2981
2982   // Check if the current operand has a custom associated parser, if so, try to
2983   // custom parse the operand, or fallback to the general approach.
2984   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2985   if (ResTy == MatchOperand_Success)
2986     return false;
2987   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2988   // there was a match, but an error occurred, in which case, just return that
2989   // the operand parsing failed.
2990   if (ResTy == MatchOperand_ParseFail)
2991     return true;
2992
2993   DEBUG(dbgs() << ".. Generic Parser\n");
2994
2995   switch (getLexer().getKind()) {
2996   default:
2997     Error(Parser.getTok().getLoc(), "unexpected token in operand");
2998     return true;
2999   case AsmToken::Dollar: {
3000     // Parse the register.
3001     SMLoc S = Parser.getTok().getLoc();
3002
3003     // Almost all registers have been parsed by custom parsers. There is only
3004     // one exception to this. $zero (and it's alias $0) will reach this point
3005     // for div, divu, and similar instructions because it is not an operand
3006     // to the instruction definition but an explicit register. Special case
3007     // this situation for now.
3008     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
3009       return false;
3010
3011     // Maybe it is a symbol reference.
3012     StringRef Identifier;
3013     if (Parser.parseIdentifier(Identifier))
3014       return true;
3015
3016     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3017     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
3018     // Otherwise create a symbol reference.
3019     const MCExpr *Res =
3020         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3021
3022     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
3023     return false;
3024   }
3025   // Else drop to expression parsing.
3026   case AsmToken::LParen:
3027   case AsmToken::Minus:
3028   case AsmToken::Plus:
3029   case AsmToken::Integer:
3030   case AsmToken::Tilde:
3031   case AsmToken::String: {
3032     DEBUG(dbgs() << ".. generic integer\n");
3033     OperandMatchResultTy ResTy = parseImm(Operands);
3034     return ResTy != MatchOperand_Success;
3035   }
3036   case AsmToken::Percent: {
3037     // It is a symbol reference or constant expression.
3038     const MCExpr *IdVal;
3039     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
3040     if (parseRelocOperand(IdVal))
3041       return true;
3042
3043     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3044
3045     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
3046     return false;
3047   } // case AsmToken::Percent
3048   } // switch(getLexer().getKind())
3049   return true;
3050 }
3051
3052 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
3053                                                StringRef RelocStr) {
3054   const MCExpr *Res;
3055   // Check the type of the expression.
3056   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
3057     // It's a constant, evaluate reloc value.
3058     int16_t Val;
3059     switch (getVariantKind(RelocStr)) {
3060     case MCSymbolRefExpr::VK_Mips_ABS_LO:
3061       // Get the 1st 16-bits.
3062       Val = MCE->getValue() & 0xffff;
3063       break;
3064     case MCSymbolRefExpr::VK_Mips_ABS_HI:
3065       // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
3066       // 16 bits being negative.
3067       Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
3068       break;
3069     case MCSymbolRefExpr::VK_Mips_HIGHER:
3070       // Get the 3rd 16-bits.
3071       Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
3072       break;
3073     case MCSymbolRefExpr::VK_Mips_HIGHEST:
3074       // Get the 4th 16-bits.
3075       Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
3076       break;
3077     default:
3078       report_fatal_error("unsupported reloc value");
3079     }
3080     return MCConstantExpr::create(Val, getContext());
3081   }
3082
3083   if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
3084     // It's a symbol, create a symbolic expression from the symbol.
3085     const MCSymbol *Symbol = &MSRE->getSymbol();
3086     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
3087     Res = MCSymbolRefExpr::create(Symbol, VK, getContext());
3088     return Res;
3089   }
3090
3091   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
3092     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
3093
3094     // Try to create target expression.
3095     if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
3096       return MipsMCExpr::create(VK, Expr, getContext());
3097
3098     const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
3099     const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
3100     Res = MCBinaryExpr::create(BE->getOpcode(), LExp, RExp, getContext());
3101     return Res;
3102   }
3103
3104   if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
3105     const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
3106     Res = MCUnaryExpr::create(UN->getOpcode(), UnExp, getContext());
3107     return Res;
3108   }
3109   // Just return the original expression.
3110   return Expr;
3111 }
3112
3113 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
3114
3115   switch (Expr->getKind()) {
3116   case MCExpr::Constant:
3117     return true;
3118   case MCExpr::SymbolRef:
3119     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
3120   case MCExpr::Binary:
3121     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
3122       if (!isEvaluated(BE->getLHS()))
3123         return false;
3124       return isEvaluated(BE->getRHS());
3125     }
3126   case MCExpr::Unary:
3127     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
3128   case MCExpr::Target:
3129     return true;
3130   }
3131   return false;
3132 }
3133
3134 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
3135   MCAsmParser &Parser = getParser();
3136   Parser.Lex();                          // Eat the % token.
3137   const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
3138   if (Tok.isNot(AsmToken::Identifier))
3139     return true;
3140
3141   std::string Str = Tok.getIdentifier();
3142
3143   Parser.Lex(); // Eat the identifier.
3144   // Now make an expression from the rest of the operand.
3145   const MCExpr *IdVal;
3146   SMLoc EndLoc;
3147
3148   if (getLexer().getKind() == AsmToken::LParen) {
3149     while (1) {
3150       Parser.Lex(); // Eat the '(' token.
3151       if (getLexer().getKind() == AsmToken::Percent) {
3152         Parser.Lex(); // Eat the % token.
3153         const AsmToken &nextTok = Parser.getTok();
3154         if (nextTok.isNot(AsmToken::Identifier))
3155           return true;
3156         Str += "(%";
3157         Str += nextTok.getIdentifier();
3158         Parser.Lex(); // Eat the identifier.
3159         if (getLexer().getKind() != AsmToken::LParen)
3160           return true;
3161       } else
3162         break;
3163     }
3164     if (getParser().parseParenExpression(IdVal, EndLoc))
3165       return true;
3166
3167     while (getLexer().getKind() == AsmToken::RParen)
3168       Parser.Lex(); // Eat the ')' token.
3169
3170   } else
3171     return true; // Parenthesis must follow the relocation operand.
3172
3173   Res = evaluateRelocExpr(IdVal, Str);
3174   return false;
3175 }
3176
3177 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
3178                                   SMLoc &EndLoc) {
3179   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
3180   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
3181   if (ResTy == MatchOperand_Success) {
3182     assert(Operands.size() == 1);
3183     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
3184     StartLoc = Operand.getStartLoc();
3185     EndLoc = Operand.getEndLoc();
3186
3187     // AFAIK, we only support numeric registers and named GPR's in CFI
3188     // directives.
3189     // Don't worry about eating tokens before failing. Using an unrecognised
3190     // register is a parse error.
3191     if (Operand.isGPRAsmReg()) {
3192       // Resolve to GPR32 or GPR64 appropriately.
3193       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
3194     }
3195
3196     return (RegNo == (unsigned)-1);
3197   }
3198
3199   assert(Operands.size() == 0);
3200   return (RegNo == (unsigned)-1);
3201 }
3202
3203 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
3204   MCAsmParser &Parser = getParser();
3205   SMLoc S;
3206   bool Result = true;
3207   unsigned NumOfLParen = 0;
3208
3209   while (getLexer().getKind() == AsmToken::LParen) {
3210     Parser.Lex();
3211     ++NumOfLParen;
3212   }
3213
3214   switch (getLexer().getKind()) {
3215   default:
3216     return true;
3217   case AsmToken::Identifier:
3218   case AsmToken::LParen:
3219   case AsmToken::Integer:
3220   case AsmToken::Minus:
3221   case AsmToken::Plus:
3222     if (isParenExpr)
3223       Result = getParser().parseParenExprOfDepth(NumOfLParen, Res, S);
3224     else
3225       Result = (getParser().parseExpression(Res));
3226     while (getLexer().getKind() == AsmToken::RParen)
3227       Parser.Lex();
3228     break;
3229   case AsmToken::Percent:
3230     Result = parseRelocOperand(Res);
3231   }
3232   return Result;
3233 }
3234
3235 MipsAsmParser::OperandMatchResultTy
3236 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
3237   MCAsmParser &Parser = getParser();
3238   DEBUG(dbgs() << "parseMemOperand\n");
3239   const MCExpr *IdVal = nullptr;
3240   SMLoc S;
3241   bool isParenExpr = false;
3242   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
3243   // First operand is the offset.
3244   S = Parser.getTok().getLoc();
3245
3246   if (getLexer().getKind() == AsmToken::LParen) {
3247     Parser.Lex();
3248     isParenExpr = true;
3249   }
3250
3251   if (getLexer().getKind() != AsmToken::Dollar) {
3252     if (parseMemOffset(IdVal, isParenExpr))
3253       return MatchOperand_ParseFail;
3254
3255     const AsmToken &Tok = Parser.getTok(); // Get the next token.
3256     if (Tok.isNot(AsmToken::LParen)) {
3257       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
3258       if (Mnemonic.getToken() == "la") {
3259         SMLoc E =
3260             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3261         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
3262         return MatchOperand_Success;
3263       }
3264       if (Tok.is(AsmToken::EndOfStatement)) {
3265         SMLoc E =
3266             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3267
3268         // Zero register assumed, add a memory operand with ZERO as its base.
3269         // "Base" will be managed by k_Memory.
3270         auto Base = MipsOperand::createGPRReg(0, getContext().getRegisterInfo(),
3271                                               S, E, *this);
3272         Operands.push_back(
3273             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
3274         return MatchOperand_Success;
3275       }
3276       Error(Parser.getTok().getLoc(), "'(' expected");
3277       return MatchOperand_ParseFail;
3278     }
3279
3280     Parser.Lex(); // Eat the '(' token.
3281   }
3282
3283   Res = parseAnyRegister(Operands);
3284   if (Res != MatchOperand_Success)
3285     return Res;
3286
3287   if (Parser.getTok().isNot(AsmToken::RParen)) {
3288     Error(Parser.getTok().getLoc(), "')' expected");
3289     return MatchOperand_ParseFail;
3290   }
3291
3292   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3293
3294   Parser.Lex(); // Eat the ')' token.
3295
3296   if (!IdVal)
3297     IdVal = MCConstantExpr::create(0, getContext());
3298
3299   // Replace the register operand with the memory operand.
3300   std::unique_ptr<MipsOperand> op(
3301       static_cast<MipsOperand *>(Operands.back().release()));
3302   // Remove the register from the operands.
3303   // "op" will be managed by k_Memory.
3304   Operands.pop_back();
3305   // Add the memory operand.
3306   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
3307     int64_t Imm;
3308     if (IdVal->evaluateAsAbsolute(Imm))
3309       IdVal = MCConstantExpr::create(Imm, getContext());
3310     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
3311       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
3312                                    getContext());
3313   }
3314
3315   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
3316   return MatchOperand_Success;
3317 }
3318
3319 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
3320   MCAsmParser &Parser = getParser();
3321   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
3322   if (Sym) {
3323     SMLoc S = Parser.getTok().getLoc();
3324     const MCExpr *Expr;
3325     if (Sym->isVariable())
3326       Expr = Sym->getVariableValue();
3327     else
3328       return false;
3329     if (Expr->getKind() == MCExpr::SymbolRef) {
3330       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
3331       StringRef DefSymbol = Ref->getSymbol().getName();
3332       if (DefSymbol.startswith("$")) {
3333         OperandMatchResultTy ResTy =
3334             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
3335         if (ResTy == MatchOperand_Success) {
3336           Parser.Lex();
3337           return true;
3338         } else if (ResTy == MatchOperand_ParseFail)
3339           llvm_unreachable("Should never ParseFail");
3340         return false;
3341       }
3342     } else if (Expr->getKind() == MCExpr::Constant) {
3343       Parser.Lex();
3344       const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
3345       Operands.push_back(
3346           MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
3347       return true;
3348     }
3349   }
3350   return false;
3351 }
3352
3353 MipsAsmParser::OperandMatchResultTy
3354 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
3355                                                  StringRef Identifier,
3356                                                  SMLoc S) {
3357   int Index = matchCPURegisterName(Identifier);
3358   if (Index != -1) {
3359     Operands.push_back(MipsOperand::createGPRReg(
3360         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3361     return MatchOperand_Success;
3362   }
3363
3364   Index = matchHWRegsRegisterName(Identifier);
3365   if (Index != -1) {
3366     Operands.push_back(MipsOperand::createHWRegsReg(
3367         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3368     return MatchOperand_Success;
3369   }
3370
3371   Index = matchFPURegisterName(Identifier);
3372   if (Index != -1) {
3373     Operands.push_back(MipsOperand::createFGRReg(
3374         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3375     return MatchOperand_Success;
3376   }
3377
3378   Index = matchFCCRegisterName(Identifier);
3379   if (Index != -1) {
3380     Operands.push_back(MipsOperand::createFCCReg(
3381         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3382     return MatchOperand_Success;
3383   }
3384
3385   Index = matchACRegisterName(Identifier);
3386   if (Index != -1) {
3387     Operands.push_back(MipsOperand::createACCReg(
3388         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3389     return MatchOperand_Success;
3390   }
3391
3392   Index = matchMSA128RegisterName(Identifier);
3393   if (Index != -1) {
3394     Operands.push_back(MipsOperand::createMSA128Reg(
3395         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3396     return MatchOperand_Success;
3397   }
3398
3399   Index = matchMSA128CtrlRegisterName(Identifier);
3400   if (Index != -1) {
3401     Operands.push_back(MipsOperand::createMSACtrlReg(
3402         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
3403     return MatchOperand_Success;
3404   }
3405
3406   return MatchOperand_NoMatch;
3407 }
3408
3409 MipsAsmParser::OperandMatchResultTy
3410 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
3411   MCAsmParser &Parser = getParser();
3412   auto Token = Parser.getLexer().peekTok(false);
3413
3414   if (Token.is(AsmToken::Identifier)) {
3415     DEBUG(dbgs() << ".. identifier\n");
3416     StringRef Identifier = Token.getIdentifier();
3417     OperandMatchResultTy ResTy =
3418         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
3419     return ResTy;
3420   } else if (Token.is(AsmToken::Integer)) {
3421     DEBUG(dbgs() << ".. integer\n");
3422     Operands.push_back(MipsOperand::createNumericReg(
3423         Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
3424         *this));
3425     return MatchOperand_Success;
3426   }
3427
3428   DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
3429
3430   return MatchOperand_NoMatch;
3431 }
3432
3433 MipsAsmParser::OperandMatchResultTy
3434 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
3435   MCAsmParser &Parser = getParser();
3436   DEBUG(dbgs() << "parseAnyRegister\n");
3437
3438   auto Token = Parser.getTok();
3439
3440   SMLoc S = Token.getLoc();
3441
3442   if (Token.isNot(AsmToken::Dollar)) {
3443     DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
3444     if (Token.is(AsmToken::Identifier)) {
3445       if (searchSymbolAlias(Operands))
3446         return MatchOperand_Success;
3447     }
3448     DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
3449     return MatchOperand_NoMatch;
3450   }
3451   DEBUG(dbgs() << ".. $\n");
3452
3453   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
3454   if (ResTy == MatchOperand_Success) {
3455     Parser.Lex(); // $
3456     Parser.Lex(); // identifier
3457   }
3458   return ResTy;
3459 }
3460
3461 MipsAsmParser::OperandMatchResultTy
3462 MipsAsmParser::parseImm(OperandVector &Operands) {
3463   MCAsmParser &Parser = getParser();
3464   switch (getLexer().getKind()) {
3465   default:
3466     return MatchOperand_NoMatch;
3467   case AsmToken::LParen:
3468   case AsmToken::Minus:
3469   case AsmToken::Plus:
3470   case AsmToken::Integer:
3471   case AsmToken::Tilde:
3472   case AsmToken::String:
3473     break;
3474   }
3475
3476   const MCExpr *IdVal;
3477   SMLoc S = Parser.getTok().getLoc();
3478   if (getParser().parseExpression(IdVal))
3479     return MatchOperand_ParseFail;
3480
3481   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3482   Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
3483   return MatchOperand_Success;
3484 }
3485
3486 MipsAsmParser::OperandMatchResultTy
3487 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
3488   MCAsmParser &Parser = getParser();
3489   DEBUG(dbgs() << "parseJumpTarget\n");
3490
3491   SMLoc S = getLexer().getLoc();
3492
3493   // Integers and expressions are acceptable
3494   OperandMatchResultTy ResTy = parseImm(Operands);
3495   if (ResTy != MatchOperand_NoMatch)
3496     return ResTy;
3497
3498   // Registers are a valid target and have priority over symbols.
3499   ResTy = parseAnyRegister(Operands);
3500   if (ResTy != MatchOperand_NoMatch)
3501     return ResTy;
3502
3503   const MCExpr *Expr = nullptr;
3504   if (Parser.parseExpression(Expr)) {
3505     // We have no way of knowing if a symbol was consumed so we must ParseFail
3506     return MatchOperand_ParseFail;
3507   }
3508   Operands.push_back(
3509       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
3510   return MatchOperand_Success;
3511 }
3512
3513 MipsAsmParser::OperandMatchResultTy
3514 MipsAsmParser::parseInvNum(OperandVector &Operands) {
3515   MCAsmParser &Parser = getParser();
3516   const MCExpr *IdVal;
3517   // If the first token is '$' we may have register operand.
3518   if (Parser.getTok().is(AsmToken::Dollar))
3519     return MatchOperand_NoMatch;
3520   SMLoc S = Parser.getTok().getLoc();
3521   if (getParser().parseExpression(IdVal))
3522     return MatchOperand_ParseFail;
3523   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
3524   assert(MCE && "Unexpected MCExpr type.");
3525   int64_t Val = MCE->getValue();
3526   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3527   Operands.push_back(MipsOperand::CreateImm(
3528       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
3529   return MatchOperand_Success;
3530 }
3531
3532 MipsAsmParser::OperandMatchResultTy
3533 MipsAsmParser::parseLSAImm(OperandVector &Operands) {
3534   MCAsmParser &Parser = getParser();
3535   switch (getLexer().getKind()) {
3536   default:
3537     return MatchOperand_NoMatch;
3538   case AsmToken::LParen:
3539   case AsmToken::Plus:
3540   case AsmToken::Minus:
3541   case AsmToken::Integer:
3542     break;
3543   }
3544
3545   const MCExpr *Expr;
3546   SMLoc S = Parser.getTok().getLoc();
3547
3548   if (getParser().parseExpression(Expr))
3549     return MatchOperand_ParseFail;
3550
3551   int64_t Val;
3552   if (!Expr->evaluateAsAbsolute(Val)) {
3553     Error(S, "expected immediate value");
3554     return MatchOperand_ParseFail;
3555   }
3556
3557   // The LSA instruction allows a 2-bit unsigned immediate. For this reason
3558   // and because the CPU always adds one to the immediate field, the allowed
3559   // range becomes 1..4. We'll only check the range here and will deal
3560   // with the addition/subtraction when actually decoding/encoding
3561   // the instruction.
3562   if (Val < 1 || Val > 4) {
3563     Error(S, "immediate not in range (1..4)");
3564     return MatchOperand_ParseFail;
3565   }
3566
3567   Operands.push_back(
3568       MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
3569   return MatchOperand_Success;
3570 }
3571
3572 MipsAsmParser::OperandMatchResultTy
3573 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
3574   MCAsmParser &Parser = getParser();
3575   SmallVector<unsigned, 10> Regs;
3576   unsigned RegNo;
3577   unsigned PrevReg = Mips::NoRegister;
3578   bool RegRange = false;
3579   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
3580
3581   if (Parser.getTok().isNot(AsmToken::Dollar))
3582     return MatchOperand_ParseFail;
3583
3584   SMLoc S = Parser.getTok().getLoc();
3585   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
3586     SMLoc E = getLexer().getLoc();
3587     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
3588     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
3589     if (RegRange) {
3590       // Remove last register operand because registers from register range
3591       // should be inserted first.
3592       if (RegNo == Mips::RA) {
3593         Regs.push_back(RegNo);
3594       } else {
3595         unsigned TmpReg = PrevReg + 1;
3596         while (TmpReg <= RegNo) {
3597           if ((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) {
3598             Error(E, "invalid register operand");
3599             return MatchOperand_ParseFail;
3600           }
3601
3602           PrevReg = TmpReg;
3603           Regs.push_back(TmpReg++);
3604         }
3605       }
3606
3607       RegRange = false;
3608     } else {
3609       if ((PrevReg == Mips::NoRegister) && (RegNo != Mips::S0) &&
3610           (RegNo != Mips::RA)) {
3611         Error(E, "$16 or $31 expected");
3612         return MatchOperand_ParseFail;
3613       } else if (((RegNo < Mips::S0) || (RegNo > Mips::S7)) &&
3614                  (RegNo != Mips::FP) && (RegNo != Mips::RA)) {
3615         Error(E, "invalid register operand");
3616         return MatchOperand_ParseFail;
3617       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
3618                  (RegNo != Mips::FP) && (RegNo != Mips::RA)) {
3619         Error(E, "consecutive register numbers expected");
3620         return MatchOperand_ParseFail;
3621       }
3622
3623       Regs.push_back(RegNo);
3624     }
3625
3626     if (Parser.getTok().is(AsmToken::Minus))
3627       RegRange = true;
3628
3629     if (!Parser.getTok().isNot(AsmToken::Minus) &&
3630         !Parser.getTok().isNot(AsmToken::Comma)) {
3631       Error(E, "',' or '-' expected");
3632       return MatchOperand_ParseFail;
3633     }
3634
3635     Lex(); // Consume comma or minus
3636     if (Parser.getTok().isNot(AsmToken::Dollar))
3637       break;
3638
3639     PrevReg = RegNo;
3640   }
3641
3642   SMLoc E = Parser.getTok().getLoc();
3643   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
3644   parseMemOperand(Operands);
3645   return MatchOperand_Success;
3646 }
3647
3648 MipsAsmParser::OperandMatchResultTy
3649 MipsAsmParser::parseRegisterPair(OperandVector &Operands) {
3650   MCAsmParser &Parser = getParser();
3651
3652   SMLoc S = Parser.getTok().getLoc();
3653   if (parseAnyRegister(Operands) != MatchOperand_Success)
3654     return MatchOperand_ParseFail;
3655
3656   SMLoc E = Parser.getTok().getLoc();
3657   MipsOperand &Op = static_cast<MipsOperand &>(*Operands.back());
3658   unsigned Reg = Op.getGPR32Reg();
3659   Operands.pop_back();
3660   Operands.push_back(MipsOperand::CreateRegPair(Reg, S, E, *this));
3661   return MatchOperand_Success;
3662 }
3663
3664 MipsAsmParser::OperandMatchResultTy
3665 MipsAsmParser::parseMovePRegPair(OperandVector &Operands) {
3666   MCAsmParser &Parser = getParser();
3667   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
3668   SmallVector<unsigned, 10> Regs;
3669
3670   if (Parser.getTok().isNot(AsmToken::Dollar))
3671     return MatchOperand_ParseFail;
3672
3673   SMLoc S = Parser.getTok().getLoc();
3674
3675   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
3676     return MatchOperand_ParseFail;
3677
3678   MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
3679   unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
3680   Regs.push_back(RegNo);
3681
3682   SMLoc E = Parser.getTok().getLoc();
3683   if (Parser.getTok().isNot(AsmToken::Comma)) {
3684     Error(E, "',' expected");
3685     return MatchOperand_ParseFail;
3686   }
3687
3688   // Remove comma.
3689   Parser.Lex();
3690
3691   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
3692     return MatchOperand_ParseFail;
3693
3694   Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
3695   RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
3696   Regs.push_back(RegNo);
3697
3698   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
3699
3700   return MatchOperand_Success;
3701 }
3702
3703 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
3704
3705   MCSymbolRefExpr::VariantKind VK =
3706       StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
3707           .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
3708           .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
3709           .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
3710           .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
3711           .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
3712           .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
3713           .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
3714           .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
3715           .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
3716           .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
3717           .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
3718           .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
3719           .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
3720           .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
3721           .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
3722           .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
3723           .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
3724           .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
3725           .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
3726           .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
3727           .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
3728           .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
3729           .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
3730           .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
3731           .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
3732           .Default(MCSymbolRefExpr::VK_None);
3733
3734   assert(VK != MCSymbolRefExpr::VK_None);
3735
3736   return VK;
3737 }
3738
3739 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
3740 /// either this.
3741 /// ::= '(', register, ')'
3742 /// handle it before we iterate so we don't get tripped up by the lack of
3743 /// a comma.
3744 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
3745   MCAsmParser &Parser = getParser();
3746   if (getLexer().is(AsmToken::LParen)) {
3747     Operands.push_back(
3748         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
3749     Parser.Lex();
3750     if (parseOperand(Operands, Name)) {
3751       SMLoc Loc = getLexer().getLoc();
3752       Parser.eatToEndOfStatement();
3753       return Error(Loc, "unexpected token in argument list");
3754     }
3755     if (Parser.getTok().isNot(AsmToken::RParen)) {
3756       SMLoc Loc = getLexer().getLoc();
3757       Parser.eatToEndOfStatement();
3758       return Error(Loc, "unexpected token, expected ')'");
3759     }
3760     Operands.push_back(
3761         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
3762     Parser.Lex();
3763   }
3764   return false;
3765 }
3766
3767 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
3768 /// either one of these.
3769 /// ::= '[', register, ']'
3770 /// ::= '[', integer, ']'
3771 /// handle it before we iterate so we don't get tripped up by the lack of
3772 /// a comma.
3773 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
3774                                        OperandVector &Operands) {
3775   MCAsmParser &Parser = getParser();
3776   if (getLexer().is(AsmToken::LBrac)) {
3777     Operands.push_back(
3778         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
3779     Parser.Lex();
3780     if (parseOperand(Operands, Name)) {
3781       SMLoc Loc = getLexer().getLoc();
3782       Parser.eatToEndOfStatement();
3783       return Error(Loc, "unexpected token in argument list");
3784     }
3785     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3786       SMLoc Loc = getLexer().getLoc();
3787       Parser.eatToEndOfStatement();
3788       return Error(Loc, "unexpected token, expected ']'");
3789     }
3790     Operands.push_back(
3791         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
3792     Parser.Lex();
3793   }
3794   return false;
3795 }
3796
3797 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
3798                                      SMLoc NameLoc, OperandVector &Operands) {
3799   MCAsmParser &Parser = getParser();
3800   DEBUG(dbgs() << "ParseInstruction\n");
3801
3802   // We have reached first instruction, module directive are now forbidden.
3803   getTargetStreamer().forbidModuleDirective();
3804
3805   // Check if we have valid mnemonic
3806   if (!mnemonicIsValid(Name, 0)) {
3807     Parser.eatToEndOfStatement();
3808     return Error(NameLoc, "unknown instruction");
3809   }
3810   // First operand in MCInst is instruction mnemonic.
3811   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
3812
3813   // Read the remaining operands.
3814   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3815     // Read the first operand.
3816     if (parseOperand(Operands, Name)) {
3817       SMLoc Loc = getLexer().getLoc();
3818       Parser.eatToEndOfStatement();
3819       return Error(Loc, "unexpected token in argument list");
3820     }
3821     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
3822       return true;
3823     // AFAIK, parenthesis suffixes are never on the first operand
3824
3825     while (getLexer().is(AsmToken::Comma)) {
3826       Parser.Lex(); // Eat the comma.
3827       // Parse and remember the operand.
3828       if (parseOperand(Operands, Name)) {
3829         SMLoc Loc = getLexer().getLoc();
3830         Parser.eatToEndOfStatement();
3831         return Error(Loc, "unexpected token in argument list");
3832       }
3833       // Parse bracket and parenthesis suffixes before we iterate
3834       if (getLexer().is(AsmToken::LBrac)) {
3835         if (parseBracketSuffix(Name, Operands))
3836           return true;
3837       } else if (getLexer().is(AsmToken::LParen) &&
3838                  parseParenSuffix(Name, Operands))
3839         return true;
3840     }
3841   }
3842   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3843     SMLoc Loc = getLexer().getLoc();
3844     Parser.eatToEndOfStatement();
3845     return Error(Loc, "unexpected token in argument list");
3846   }
3847   Parser.Lex(); // Consume the EndOfStatement.
3848   return false;
3849 }
3850
3851 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
3852   MCAsmParser &Parser = getParser();
3853   SMLoc Loc = getLexer().getLoc();
3854   Parser.eatToEndOfStatement();
3855   return Error(Loc, ErrorMsg);
3856 }
3857
3858 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
3859   return Error(Loc, ErrorMsg);
3860 }
3861
3862 bool MipsAsmParser::parseSetNoAtDirective() {
3863   MCAsmParser &Parser = getParser();
3864   // Line should look like: ".set noat".
3865
3866   // Set the $at register to $0.
3867   AssemblerOptions.back()->setATRegIndex(0);
3868
3869   Parser.Lex(); // Eat "noat".
3870
3871   // If this is not the end of the statement, report an error.
3872   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3873     reportParseError("unexpected token, expected end of statement");
3874     return false;
3875   }
3876
3877   getTargetStreamer().emitDirectiveSetNoAt();
3878   Parser.Lex(); // Consume the EndOfStatement.
3879   return false;
3880 }
3881
3882 bool MipsAsmParser::parseSetAtDirective() {
3883   // Line can be: ".set at", which sets $at to $1
3884   //          or  ".set at=$reg", which sets $at to $reg.
3885   MCAsmParser &Parser = getParser();
3886   Parser.Lex(); // Eat "at".
3887
3888   if (getLexer().is(AsmToken::EndOfStatement)) {
3889     // No register was specified, so we set $at to $1.
3890     AssemblerOptions.back()->setATRegIndex(1);
3891
3892     getTargetStreamer().emitDirectiveSetAt();
3893     Parser.Lex(); // Consume the EndOfStatement.
3894     return false;
3895   }
3896
3897   if (getLexer().isNot(AsmToken::Equal)) {
3898     reportParseError("unexpected token, expected equals sign");
3899     return false;
3900   }
3901   Parser.Lex(); // Eat "=".
3902
3903   if (getLexer().isNot(AsmToken::Dollar)) {
3904     if (getLexer().is(AsmToken::EndOfStatement)) {
3905       reportParseError("no register specified");
3906       return false;
3907     } else {
3908       reportParseError("unexpected token, expected dollar sign '$'");
3909       return false;
3910     }
3911   }
3912   Parser.Lex(); // Eat "$".
3913
3914   // Find out what "reg" is.
3915   unsigned AtRegNo;
3916   const AsmToken &Reg = Parser.getTok();
3917   if (Reg.is(AsmToken::Identifier)) {
3918     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
3919   } else if (Reg.is(AsmToken::Integer)) {
3920     AtRegNo = Reg.getIntVal();
3921   } else {
3922     reportParseError("unexpected token, expected identifier or integer");
3923     return false;
3924   }
3925
3926   // Check if $reg is a valid register. If it is, set $at to $reg.
3927   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
3928     reportParseError("invalid register");
3929     return false;
3930   }
3931   Parser.Lex(); // Eat "reg".
3932
3933   // If this is not the end of the statement, report an error.
3934   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3935     reportParseError("unexpected token, expected end of statement");
3936     return false;
3937   }
3938
3939   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
3940
3941   Parser.Lex(); // Consume the EndOfStatement.
3942   return false;
3943 }
3944
3945 bool MipsAsmParser::parseSetReorderDirective() {
3946   MCAsmParser &Parser = getParser();
3947   Parser.Lex();
3948   // If this is not the end of the statement, report an error.
3949   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3950     reportParseError("unexpected token, expected end of statement");
3951     return false;
3952   }
3953   AssemblerOptions.back()->setReorder();
3954   getTargetStreamer().emitDirectiveSetReorder();
3955   Parser.Lex(); // Consume the EndOfStatement.
3956   return false;
3957 }
3958
3959 bool MipsAsmParser::parseSetNoReorderDirective() {
3960   MCAsmParser &Parser = getParser();
3961   Parser.Lex();
3962   // If this is not the end of the statement, report an error.
3963   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3964     reportParseError("unexpected token, expected end of statement");
3965     return false;
3966   }
3967   AssemblerOptions.back()->setNoReorder();
3968   getTargetStreamer().emitDirectiveSetNoReorder();
3969   Parser.Lex(); // Consume the EndOfStatement.
3970   return false;
3971 }
3972
3973 bool MipsAsmParser::parseSetMacroDirective() {
3974   MCAsmParser &Parser = getParser();
3975   Parser.Lex();
3976   // If this is not the end of the statement, report an error.
3977   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3978     reportParseError("unexpected token, expected end of statement");
3979     return false;
3980   }
3981   AssemblerOptions.back()->setMacro();
3982   getTargetStreamer().emitDirectiveSetMacro();
3983   Parser.Lex(); // Consume the EndOfStatement.
3984   return false;
3985 }
3986
3987 bool MipsAsmParser::parseSetNoMacroDirective() {
3988   MCAsmParser &Parser = getParser();
3989   Parser.Lex();
3990   // If this is not the end of the statement, report an error.
3991   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3992     reportParseError("unexpected token, expected end of statement");
3993     return false;
3994   }
3995   if (AssemblerOptions.back()->isReorder()) {
3996     reportParseError("`noreorder' must be set before `nomacro'");
3997     return false;
3998   }
3999   AssemblerOptions.back()->setNoMacro();
4000   getTargetStreamer().emitDirectiveSetNoMacro();
4001   Parser.Lex(); // Consume the EndOfStatement.
4002   return false;
4003 }
4004
4005 bool MipsAsmParser::parseSetMsaDirective() {
4006   MCAsmParser &Parser = getParser();
4007   Parser.Lex();
4008
4009   // If this is not the end of the statement, report an error.
4010   if (getLexer().isNot(AsmToken::EndOfStatement))
4011     return reportParseError("unexpected token, expected end of statement");
4012
4013   setFeatureBits(Mips::FeatureMSA, "msa");
4014   getTargetStreamer().emitDirectiveSetMsa();
4015   return false;
4016 }
4017
4018 bool MipsAsmParser::parseSetNoMsaDirective() {
4019   MCAsmParser &Parser = getParser();
4020   Parser.Lex();
4021
4022   // If this is not the end of the statement, report an error.
4023   if (getLexer().isNot(AsmToken::EndOfStatement))
4024     return reportParseError("unexpected token, expected end of statement");
4025
4026   clearFeatureBits(Mips::FeatureMSA, "msa");
4027   getTargetStreamer().emitDirectiveSetNoMsa();
4028   return false;
4029 }
4030
4031 bool MipsAsmParser::parseSetNoDspDirective() {
4032   MCAsmParser &Parser = getParser();
4033   Parser.Lex(); // Eat "nodsp".
4034
4035   // If this is not the end of the statement, report an error.
4036   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4037     reportParseError("unexpected token, expected end of statement");
4038     return false;
4039   }
4040
4041   clearFeatureBits(Mips::FeatureDSP, "dsp");
4042   getTargetStreamer().emitDirectiveSetNoDsp();
4043   return false;
4044 }
4045
4046 bool MipsAsmParser::parseSetMips16Directive() {
4047   MCAsmParser &Parser = getParser();
4048   Parser.Lex(); // Eat "mips16".
4049
4050   // If this is not the end of the statement, report an error.
4051   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4052     reportParseError("unexpected token, expected end of statement");
4053     return false;
4054   }
4055
4056   setFeatureBits(Mips::FeatureMips16, "mips16");
4057   getTargetStreamer().emitDirectiveSetMips16();
4058   Parser.Lex(); // Consume the EndOfStatement.
4059   return false;
4060 }
4061
4062 bool MipsAsmParser::parseSetNoMips16Directive() {
4063   MCAsmParser &Parser = getParser();
4064   Parser.Lex(); // Eat "nomips16".
4065
4066   // If this is not the end of the statement, report an error.
4067   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4068     reportParseError("unexpected token, expected end of statement");
4069     return false;
4070   }
4071
4072   clearFeatureBits(Mips::FeatureMips16, "mips16");
4073   getTargetStreamer().emitDirectiveSetNoMips16();
4074   Parser.Lex(); // Consume the EndOfStatement.
4075   return false;
4076 }
4077
4078 bool MipsAsmParser::parseSetFpDirective() {
4079   MCAsmParser &Parser = getParser();
4080   MipsABIFlagsSection::FpABIKind FpAbiVal;
4081   // Line can be: .set fp=32
4082   //              .set fp=xx
4083   //              .set fp=64
4084   Parser.Lex(); // Eat fp token
4085   AsmToken Tok = Parser.getTok();
4086   if (Tok.isNot(AsmToken::Equal)) {
4087     reportParseError("unexpected token, expected equals sign '='");
4088     return false;
4089   }
4090   Parser.Lex(); // Eat '=' token.
4091   Tok = Parser.getTok();
4092
4093   if (!parseFpABIValue(FpAbiVal, ".set"))
4094     return false;
4095
4096   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4097     reportParseError("unexpected token, expected end of statement");
4098     return false;
4099   }
4100   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
4101   Parser.Lex(); // Consume the EndOfStatement.
4102   return false;
4103 }
4104
4105 bool MipsAsmParser::parseSetOddSPRegDirective() {
4106   MCAsmParser &Parser = getParser();
4107
4108   Parser.Lex(); // Eat "oddspreg".
4109   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4110     reportParseError("unexpected token, expected end of statement");
4111     return false;
4112   }
4113
4114   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
4115   getTargetStreamer().emitDirectiveSetOddSPReg();
4116   return false;
4117 }
4118
4119 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
4120   MCAsmParser &Parser = getParser();
4121
4122   Parser.Lex(); // Eat "nooddspreg".
4123   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4124     reportParseError("unexpected token, expected end of statement");
4125     return false;
4126   }
4127
4128   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
4129   getTargetStreamer().emitDirectiveSetNoOddSPReg();
4130   return false;
4131 }
4132
4133 bool MipsAsmParser::parseSetPopDirective() {
4134   MCAsmParser &Parser = getParser();
4135   SMLoc Loc = getLexer().getLoc();
4136
4137   Parser.Lex();
4138   if (getLexer().isNot(AsmToken::EndOfStatement))
4139     return reportParseError("unexpected token, expected end of statement");
4140
4141   // Always keep an element on the options "stack" to prevent the user
4142   // from changing the initial options. This is how we remember them.
4143   if (AssemblerOptions.size() == 2)
4144     return reportParseError(Loc, ".set pop with no .set push");
4145
4146   AssemblerOptions.pop_back();
4147   setAvailableFeatures(
4148       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
4149   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
4150
4151   getTargetStreamer().emitDirectiveSetPop();
4152   return false;
4153 }
4154
4155 bool MipsAsmParser::parseSetPushDirective() {
4156   MCAsmParser &Parser = getParser();
4157   Parser.Lex();
4158   if (getLexer().isNot(AsmToken::EndOfStatement))
4159     return reportParseError("unexpected token, expected end of statement");
4160
4161   // Create a copy of the current assembler options environment and push it.
4162   AssemblerOptions.push_back(
4163               make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
4164
4165   getTargetStreamer().emitDirectiveSetPush();
4166   return false;
4167 }
4168
4169 bool MipsAsmParser::parseSetSoftFloatDirective() {
4170   MCAsmParser &Parser = getParser();
4171   Parser.Lex();
4172   if (getLexer().isNot(AsmToken::EndOfStatement))
4173     return reportParseError("unexpected token, expected end of statement");
4174
4175   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
4176   getTargetStreamer().emitDirectiveSetSoftFloat();
4177   return false;
4178 }
4179
4180 bool MipsAsmParser::parseSetHardFloatDirective() {
4181   MCAsmParser &Parser = getParser();
4182   Parser.Lex();
4183   if (getLexer().isNot(AsmToken::EndOfStatement))
4184     return reportParseError("unexpected token, expected end of statement");
4185
4186   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
4187   getTargetStreamer().emitDirectiveSetHardFloat();
4188   return false;
4189 }
4190
4191 bool MipsAsmParser::parseSetAssignment() {
4192   StringRef Name;
4193   const MCExpr *Value;
4194   MCAsmParser &Parser = getParser();
4195
4196   if (Parser.parseIdentifier(Name))
4197     reportParseError("expected identifier after .set");
4198
4199   if (getLexer().isNot(AsmToken::Comma))
4200     return reportParseError("unexpected token, expected comma");
4201   Lex(); // Eat comma
4202
4203   if (Parser.parseExpression(Value))
4204     return reportParseError("expected valid expression after comma");
4205
4206   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4207   Sym->setVariableValue(Value);
4208
4209   return false;
4210 }
4211
4212 bool MipsAsmParser::parseSetMips0Directive() {
4213   MCAsmParser &Parser = getParser();
4214   Parser.Lex();
4215   if (getLexer().isNot(AsmToken::EndOfStatement))
4216     return reportParseError("unexpected token, expected end of statement");
4217
4218   // Reset assembler options to their initial values.
4219   setAvailableFeatures(
4220       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
4221   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
4222   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
4223
4224   getTargetStreamer().emitDirectiveSetMips0();
4225   return false;
4226 }
4227
4228 bool MipsAsmParser::parseSetArchDirective() {
4229   MCAsmParser &Parser = getParser();
4230   Parser.Lex();
4231   if (getLexer().isNot(AsmToken::Equal))
4232     return reportParseError("unexpected token, expected equals sign");
4233
4234   Parser.Lex();
4235   StringRef Arch;
4236   if (Parser.parseIdentifier(Arch))
4237     return reportParseError("expected arch identifier");
4238
4239   StringRef ArchFeatureName =
4240       StringSwitch<StringRef>(Arch)
4241           .Case("mips1", "mips1")
4242           .Case("mips2", "mips2")
4243           .Case("mips3", "mips3")
4244           .Case("mips4", "mips4")
4245           .Case("mips5", "mips5")
4246           .Case("mips32", "mips32")
4247           .Case("mips32r2", "mips32r2")
4248           .Case("mips32r3", "mips32r3")
4249           .Case("mips32r5", "mips32r5")
4250           .Case("mips32r6", "mips32r6")
4251           .Case("mips64", "mips64")
4252           .Case("mips64r2", "mips64r2")
4253           .Case("mips64r3", "mips64r3")
4254           .Case("mips64r5", "mips64r5")
4255           .Case("mips64r6", "mips64r6")
4256           .Case("cnmips", "cnmips")
4257           .Case("r4000", "mips3") // This is an implementation of Mips3.
4258           .Default("");
4259
4260   if (ArchFeatureName.empty())
4261     return reportParseError("unsupported architecture");
4262
4263   selectArch(ArchFeatureName);
4264   getTargetStreamer().emitDirectiveSetArch(Arch);
4265   return false;
4266 }
4267
4268 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
4269   MCAsmParser &Parser = getParser();
4270   Parser.Lex();
4271   if (getLexer().isNot(AsmToken::EndOfStatement))
4272     return reportParseError("unexpected token, expected end of statement");
4273
4274   switch (Feature) {
4275   default:
4276     llvm_unreachable("Unimplemented feature");
4277   case Mips::FeatureDSP:
4278     setFeatureBits(Mips::FeatureDSP, "dsp");
4279     getTargetStreamer().emitDirectiveSetDsp();
4280     break;
4281   case Mips::FeatureMicroMips:
4282     getTargetStreamer().emitDirectiveSetMicroMips();
4283     break;
4284   case Mips::FeatureMips1:
4285     selectArch("mips1");
4286     getTargetStreamer().emitDirectiveSetMips1();
4287     break;
4288   case Mips::FeatureMips2:
4289     selectArch("mips2");
4290     getTargetStreamer().emitDirectiveSetMips2();
4291     break;
4292   case Mips::FeatureMips3:
4293     selectArch("mips3");
4294     getTargetStreamer().emitDirectiveSetMips3();
4295     break;
4296   case Mips::FeatureMips4:
4297     selectArch("mips4");
4298     getTargetStreamer().emitDirectiveSetMips4();
4299     break;
4300   case Mips::FeatureMips5:
4301     selectArch("mips5");
4302     getTargetStreamer().emitDirectiveSetMips5();
4303     break;
4304   case Mips::FeatureMips32:
4305     selectArch("mips32");
4306     getTargetStreamer().emitDirectiveSetMips32();
4307     break;
4308   case Mips::FeatureMips32r2:
4309     selectArch("mips32r2");
4310     getTargetStreamer().emitDirectiveSetMips32R2();
4311     break;
4312   case Mips::FeatureMips32r3:
4313     selectArch("mips32r3");
4314     getTargetStreamer().emitDirectiveSetMips32R3();
4315     break;
4316   case Mips::FeatureMips32r5:
4317     selectArch("mips32r5");
4318     getTargetStreamer().emitDirectiveSetMips32R5();
4319     break;
4320   case Mips::FeatureMips32r6:
4321     selectArch("mips32r6");
4322     getTargetStreamer().emitDirectiveSetMips32R6();
4323     break;
4324   case Mips::FeatureMips64:
4325     selectArch("mips64");
4326     getTargetStreamer().emitDirectiveSetMips64();
4327     break;
4328   case Mips::FeatureMips64r2:
4329     selectArch("mips64r2");
4330     getTargetStreamer().emitDirectiveSetMips64R2();
4331     break;
4332   case Mips::FeatureMips64r3:
4333     selectArch("mips64r3");
4334     getTargetStreamer().emitDirectiveSetMips64R3();
4335     break;
4336   case Mips::FeatureMips64r5:
4337     selectArch("mips64r5");
4338     getTargetStreamer().emitDirectiveSetMips64R5();
4339     break;
4340   case Mips::FeatureMips64r6:
4341     selectArch("mips64r6");
4342     getTargetStreamer().emitDirectiveSetMips64R6();
4343     break;
4344   }
4345   return false;
4346 }
4347
4348 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
4349   MCAsmParser &Parser = getParser();
4350   if (getLexer().isNot(AsmToken::Comma)) {
4351     SMLoc Loc = getLexer().getLoc();
4352     Parser.eatToEndOfStatement();
4353     return Error(Loc, ErrorStr);
4354   }
4355
4356   Parser.Lex(); // Eat the comma.
4357   return true;
4358 }
4359
4360 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
4361   if (AssemblerOptions.back()->isReorder())
4362     Warning(Loc, ".cpload should be inside a noreorder section");
4363
4364   if (inMips16Mode()) {
4365     reportParseError(".cpload is not supported in Mips16 mode");
4366     return false;
4367   }
4368
4369   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
4370   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
4371   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
4372     reportParseError("expected register containing function address");
4373     return false;
4374   }
4375
4376   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
4377   if (!RegOpnd.isGPRAsmReg()) {
4378     reportParseError(RegOpnd.getStartLoc(), "invalid register");
4379     return false;
4380   }
4381
4382   // If this is not the end of the statement, report an error.
4383   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4384     reportParseError("unexpected token, expected end of statement");
4385     return false;
4386   }
4387
4388   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
4389   return false;
4390 }
4391
4392 bool MipsAsmParser::parseDirectiveCPSetup() {
4393   MCAsmParser &Parser = getParser();
4394   unsigned FuncReg;
4395   unsigned Save;
4396   bool SaveIsReg = true;
4397
4398   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
4399   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
4400   if (ResTy == MatchOperand_NoMatch) {
4401     reportParseError("expected register containing function address");
4402     Parser.eatToEndOfStatement();
4403     return false;
4404   }
4405
4406   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
4407   if (!FuncRegOpnd.isGPRAsmReg()) {
4408     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
4409     Parser.eatToEndOfStatement();
4410     return false;
4411   }
4412
4413   FuncReg = FuncRegOpnd.getGPR32Reg();
4414   TmpReg.clear();
4415
4416   if (!eatComma("unexpected token, expected comma"))
4417     return true;
4418
4419   ResTy = parseAnyRegister(TmpReg);
4420   if (ResTy == MatchOperand_NoMatch) {
4421     const AsmToken &Tok = Parser.getTok();
4422     if (Tok.is(AsmToken::Integer)) {
4423       Save = Tok.getIntVal();
4424       SaveIsReg = false;
4425       Parser.Lex();
4426     } else {
4427       reportParseError("expected save register or stack offset");
4428       Parser.eatToEndOfStatement();
4429       return false;
4430     }
4431   } else {
4432     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
4433     if (!SaveOpnd.isGPRAsmReg()) {
4434       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
4435       Parser.eatToEndOfStatement();
4436       return false;
4437     }
4438     Save = SaveOpnd.getGPR32Reg();
4439   }
4440
4441   if (!eatComma("unexpected token, expected comma"))
4442     return true;
4443
4444   const MCExpr *Expr;
4445   if (Parser.parseExpression(Expr)) {
4446     reportParseError("expected expression");
4447     return false;
4448   }
4449
4450   if (Expr->getKind() != MCExpr::SymbolRef) {
4451     reportParseError("expected symbol");
4452     return false;
4453   }
4454   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
4455
4456   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
4457                                            SaveIsReg);
4458   return false;
4459 }
4460
4461 bool MipsAsmParser::parseDirectiveNaN() {
4462   MCAsmParser &Parser = getParser();
4463   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4464     const AsmToken &Tok = Parser.getTok();
4465
4466     if (Tok.getString() == "2008") {
4467       Parser.Lex();
4468       getTargetStreamer().emitDirectiveNaN2008();
4469       return false;
4470     } else if (Tok.getString() == "legacy") {
4471       Parser.Lex();
4472       getTargetStreamer().emitDirectiveNaNLegacy();
4473       return false;
4474     }
4475   }
4476   // If we don't recognize the option passed to the .nan
4477   // directive (e.g. no option or unknown option), emit an error.
4478   reportParseError("invalid option in .nan directive");
4479   return false;
4480 }
4481
4482 bool MipsAsmParser::parseDirectiveSet() {
4483   MCAsmParser &Parser = getParser();
4484   // Get the next token.
4485   const AsmToken &Tok = Parser.getTok();
4486
4487   if (Tok.getString() == "noat") {
4488     return parseSetNoAtDirective();
4489   } else if (Tok.getString() == "at") {
4490     return parseSetAtDirective();
4491   } else if (Tok.getString() == "arch") {
4492     return parseSetArchDirective();
4493   } else if (Tok.getString() == "fp") {
4494     return parseSetFpDirective();
4495   } else if (Tok.getString() == "oddspreg") {
4496     return parseSetOddSPRegDirective();
4497   } else if (Tok.getString() == "nooddspreg") {
4498     return parseSetNoOddSPRegDirective();
4499   } else if (Tok.getString() == "pop") {
4500     return parseSetPopDirective();
4501   } else if (Tok.getString() == "push") {
4502     return parseSetPushDirective();
4503   } else if (Tok.getString() == "reorder") {
4504     return parseSetReorderDirective();
4505   } else if (Tok.getString() == "noreorder") {
4506     return parseSetNoReorderDirective();
4507   } else if (Tok.getString() == "macro") {
4508     return parseSetMacroDirective();
4509   } else if (Tok.getString() == "nomacro") {
4510     return parseSetNoMacroDirective();
4511   } else if (Tok.getString() == "mips16") {
4512     return parseSetMips16Directive();
4513   } else if (Tok.getString() == "nomips16") {
4514     return parseSetNoMips16Directive();
4515   } else if (Tok.getString() == "nomicromips") {
4516     getTargetStreamer().emitDirectiveSetNoMicroMips();
4517     Parser.eatToEndOfStatement();
4518     return false;
4519   } else if (Tok.getString() == "micromips") {
4520     return parseSetFeature(Mips::FeatureMicroMips);
4521   } else if (Tok.getString() == "mips0") {
4522     return parseSetMips0Directive();
4523   } else if (Tok.getString() == "mips1") {
4524     return parseSetFeature(Mips::FeatureMips1);
4525   } else if (Tok.getString() == "mips2") {
4526     return parseSetFeature(Mips::FeatureMips2);
4527   } else if (Tok.getString() == "mips3") {
4528     return parseSetFeature(Mips::FeatureMips3);
4529   } else if (Tok.getString() == "mips4") {
4530     return parseSetFeature(Mips::FeatureMips4);
4531   } else if (Tok.getString() == "mips5") {
4532     return parseSetFeature(Mips::FeatureMips5);
4533   } else if (Tok.getString() == "mips32") {
4534     return parseSetFeature(Mips::FeatureMips32);
4535   } else if (Tok.getString() == "mips32r2") {
4536     return parseSetFeature(Mips::FeatureMips32r2);
4537   } else if (Tok.getString() == "mips32r3") {
4538     return parseSetFeature(Mips::FeatureMips32r3);
4539   } else if (Tok.getString() == "mips32r5") {
4540     return parseSetFeature(Mips::FeatureMips32r5);
4541   } else if (Tok.getString() == "mips32r6") {
4542     return parseSetFeature(Mips::FeatureMips32r6);
4543   } else if (Tok.getString() == "mips64") {
4544     return parseSetFeature(Mips::FeatureMips64);
4545   } else if (Tok.getString() == "mips64r2") {
4546     return parseSetFeature(Mips::FeatureMips64r2);
4547   } else if (Tok.getString() == "mips64r3") {
4548     return parseSetFeature(Mips::FeatureMips64r3);
4549   } else if (Tok.getString() == "mips64r5") {
4550     return parseSetFeature(Mips::FeatureMips64r5);
4551   } else if (Tok.getString() == "mips64r6") {
4552     return parseSetFeature(Mips::FeatureMips64r6);
4553   } else if (Tok.getString() == "dsp") {
4554     return parseSetFeature(Mips::FeatureDSP);
4555   } else if (Tok.getString() == "nodsp") {
4556     return parseSetNoDspDirective();
4557   } else if (Tok.getString() == "msa") {
4558     return parseSetMsaDirective();
4559   } else if (Tok.getString() == "nomsa") {
4560     return parseSetNoMsaDirective();
4561   } else if (Tok.getString() == "softfloat") {
4562     return parseSetSoftFloatDirective();
4563   } else if (Tok.getString() == "hardfloat") {
4564     return parseSetHardFloatDirective();
4565   } else {
4566     // It is just an identifier, look for an assignment.
4567     parseSetAssignment();
4568     return false;
4569   }
4570
4571   return true;
4572 }
4573
4574 /// parseDataDirective
4575 ///  ::= .word [ expression (, expression)* ]
4576 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
4577   MCAsmParser &Parser = getParser();
4578   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4579     for (;;) {
4580       const MCExpr *Value;
4581       if (getParser().parseExpression(Value))
4582         return true;
4583
4584       getParser().getStreamer().EmitValue(Value, Size);
4585
4586       if (getLexer().is(AsmToken::EndOfStatement))
4587         break;
4588
4589       if (getLexer().isNot(AsmToken::Comma))
4590         return Error(L, "unexpected token, expected comma");
4591       Parser.Lex();
4592     }
4593   }
4594
4595   Parser.Lex();
4596   return false;
4597 }
4598
4599 /// parseDirectiveGpWord
4600 ///  ::= .gpword local_sym
4601 bool MipsAsmParser::parseDirectiveGpWord() {
4602   MCAsmParser &Parser = getParser();
4603   const MCExpr *Value;
4604   // EmitGPRel32Value requires an expression, so we are using base class
4605   // method to evaluate the expression.
4606   if (getParser().parseExpression(Value))
4607     return true;
4608   getParser().getStreamer().EmitGPRel32Value(Value);
4609
4610   if (getLexer().isNot(AsmToken::EndOfStatement))
4611     return Error(getLexer().getLoc(), 
4612                 "unexpected token, expected end of statement");
4613   Parser.Lex(); // Eat EndOfStatement token.
4614   return false;
4615 }
4616
4617 /// parseDirectiveGpDWord
4618 ///  ::= .gpdword local_sym
4619 bool MipsAsmParser::parseDirectiveGpDWord() {
4620   MCAsmParser &Parser = getParser();
4621   const MCExpr *Value;
4622   // EmitGPRel64Value requires an expression, so we are using base class
4623   // method to evaluate the expression.
4624   if (getParser().parseExpression(Value))
4625     return true;
4626   getParser().getStreamer().EmitGPRel64Value(Value);
4627
4628   if (getLexer().isNot(AsmToken::EndOfStatement))
4629     return Error(getLexer().getLoc(), 
4630                 "unexpected token, expected end of statement");
4631   Parser.Lex(); // Eat EndOfStatement token.
4632   return false;
4633 }
4634
4635 bool MipsAsmParser::parseDirectiveOption() {
4636   MCAsmParser &Parser = getParser();
4637   // Get the option token.
4638   AsmToken Tok = Parser.getTok();
4639   // At the moment only identifiers are supported.
4640   if (Tok.isNot(AsmToken::Identifier)) {
4641     Error(Parser.getTok().getLoc(), "unexpected token, expected identifier");
4642     Parser.eatToEndOfStatement();
4643     return false;
4644   }
4645
4646   StringRef Option = Tok.getIdentifier();
4647
4648   if (Option == "pic0") {
4649     getTargetStreamer().emitDirectiveOptionPic0();
4650     Parser.Lex();
4651     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
4652       Error(Parser.getTok().getLoc(),
4653             "unexpected token, expected end of statement");
4654       Parser.eatToEndOfStatement();
4655     }
4656     return false;
4657   }
4658
4659   if (Option == "pic2") {
4660     getTargetStreamer().emitDirectiveOptionPic2();
4661     Parser.Lex();
4662     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
4663       Error(Parser.getTok().getLoc(),
4664             "unexpected token, expected end of statement");
4665       Parser.eatToEndOfStatement();
4666     }
4667     return false;
4668   }
4669
4670   // Unknown option.
4671   Warning(Parser.getTok().getLoc(), 
4672           "unknown option, expected 'pic0' or 'pic2'");
4673   Parser.eatToEndOfStatement();
4674   return false;
4675 }
4676
4677 /// parseInsnDirective
4678 ///  ::= .insn
4679 bool MipsAsmParser::parseInsnDirective() {
4680   // If this is not the end of the statement, report an error.
4681   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4682     reportParseError("unexpected token, expected end of statement");
4683     return false;
4684   }
4685
4686   // The actual label marking happens in
4687   // MipsELFStreamer::createPendingLabelRelocs().
4688   getTargetStreamer().emitDirectiveInsn();
4689
4690   getParser().Lex(); // Eat EndOfStatement token.
4691   return false;
4692 }
4693
4694 /// parseDirectiveModule
4695 ///  ::= .module oddspreg
4696 ///  ::= .module nooddspreg
4697 ///  ::= .module fp=value
4698 bool MipsAsmParser::parseDirectiveModule() {
4699   MCAsmParser &Parser = getParser();
4700   MCAsmLexer &Lexer = getLexer();
4701   SMLoc L = Lexer.getLoc();
4702
4703   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
4704     // TODO : get a better message.
4705     reportParseError(".module directive must appear before any code");
4706     return false;
4707   }
4708
4709   StringRef Option;
4710   if (Parser.parseIdentifier(Option)) {
4711     reportParseError("expected .module option identifier");
4712     return false;
4713   }
4714
4715   if (Option == "oddspreg") {
4716     clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
4717
4718     // Synchronize the abiflags information with the FeatureBits information we
4719     // changed above.
4720     getTargetStreamer().updateABIInfo(*this);
4721
4722     // If printing assembly, use the recently updated abiflags information.
4723     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
4724     // emitted at the end).
4725     getTargetStreamer().emitDirectiveModuleOddSPReg();
4726
4727     // If this is not the end of the statement, report an error.
4728     if (getLexer().isNot(AsmToken::EndOfStatement)) {
4729       reportParseError("unexpected token, expected end of statement");
4730       return false;
4731     }
4732
4733     return false; // parseDirectiveModule has finished successfully.
4734   } else if (Option == "nooddspreg") {
4735     if (!isABI_O32()) {
4736       Error(L, "'.module nooddspreg' requires the O32 ABI");
4737       return false;
4738     }
4739
4740     setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
4741
4742     // Synchronize the abiflags information with the FeatureBits information we
4743     // changed above.
4744     getTargetStreamer().updateABIInfo(*this);
4745
4746     // If printing assembly, use the recently updated abiflags information.
4747     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
4748     // emitted at the end).
4749     getTargetStreamer().emitDirectiveModuleOddSPReg();
4750
4751     // If this is not the end of the statement, report an error.
4752     if (getLexer().isNot(AsmToken::EndOfStatement)) {
4753       reportParseError("unexpected token, expected end of statement");
4754       return false;
4755     }
4756
4757     return false; // parseDirectiveModule has finished successfully.
4758   } else if (Option == "fp") {
4759     return parseDirectiveModuleFP();
4760   } else {
4761     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
4762   }
4763 }
4764
4765 /// parseDirectiveModuleFP
4766 ///  ::= =32
4767 ///  ::= =xx
4768 ///  ::= =64
4769 bool MipsAsmParser::parseDirectiveModuleFP() {
4770   MCAsmParser &Parser = getParser();
4771   MCAsmLexer &Lexer = getLexer();
4772
4773   if (Lexer.isNot(AsmToken::Equal)) {
4774     reportParseError("unexpected token, expected equals sign '='");
4775     return false;
4776   }
4777   Parser.Lex(); // Eat '=' token.
4778
4779   MipsABIFlagsSection::FpABIKind FpABI;
4780   if (!parseFpABIValue(FpABI, ".module"))
4781     return false;
4782
4783   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4784     reportParseError("unexpected token, expected end of statement");
4785     return false;
4786   }
4787
4788   // Synchronize the abiflags information with the FeatureBits information we
4789   // changed above.
4790   getTargetStreamer().updateABIInfo(*this);
4791
4792   // If printing assembly, use the recently updated abiflags information.
4793   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
4794   // emitted at the end).
4795   getTargetStreamer().emitDirectiveModuleFP();
4796
4797   Parser.Lex(); // Consume the EndOfStatement.
4798   return false;
4799 }
4800
4801 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
4802                                     StringRef Directive) {
4803   MCAsmParser &Parser = getParser();
4804   MCAsmLexer &Lexer = getLexer();
4805
4806   if (Lexer.is(AsmToken::Identifier)) {
4807     StringRef Value = Parser.getTok().getString();
4808     Parser.Lex();
4809
4810     if (Value != "xx") {
4811       reportParseError("unsupported value, expected 'xx', '32' or '64'");
4812       return false;
4813     }
4814
4815     if (!isABI_O32()) {
4816       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
4817       return false;
4818     }
4819
4820     FpABI = MipsABIFlagsSection::FpABIKind::XX;
4821     setFeatureBits(Mips::FeatureFPXX, "fpxx");
4822     clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
4823     return true;
4824   }
4825
4826   if (Lexer.is(AsmToken::Integer)) {
4827     unsigned Value = Parser.getTok().getIntVal();
4828     Parser.Lex();
4829
4830     if (Value != 32 && Value != 64) {
4831       reportParseError("unsupported value, expected 'xx', '32' or '64'");
4832       return false;
4833     }
4834
4835     if (Value == 32) {
4836       if (!isABI_O32()) {
4837         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
4838         return false;
4839       }
4840
4841       FpABI = MipsABIFlagsSection::FpABIKind::S32;
4842       clearFeatureBits(Mips::FeatureFPXX, "fpxx");
4843       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
4844     } else {
4845       FpABI = MipsABIFlagsSection::FpABIKind::S64;
4846       clearFeatureBits(Mips::FeatureFPXX, "fpxx");
4847       setFeatureBits(Mips::FeatureFP64Bit, "fp64");
4848     }
4849
4850     return true;
4851   }
4852
4853   return false;
4854 }
4855
4856 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
4857   MCAsmParser &Parser = getParser();
4858   StringRef IDVal = DirectiveID.getString();
4859
4860   if (IDVal == ".cpload")
4861     return parseDirectiveCpLoad(DirectiveID.getLoc());
4862   if (IDVal == ".dword") {
4863     parseDataDirective(8, DirectiveID.getLoc());
4864     return false;
4865   }
4866   if (IDVal == ".ent") {
4867     StringRef SymbolName;
4868
4869     if (Parser.parseIdentifier(SymbolName)) {
4870       reportParseError("expected identifier after .ent");
4871       return false;
4872     }
4873
4874     // There's an undocumented extension that allows an integer to
4875     // follow the name of the procedure which AFAICS is ignored by GAS.
4876     // Example: .ent foo,2
4877     if (getLexer().isNot(AsmToken::EndOfStatement)) {
4878       if (getLexer().isNot(AsmToken::Comma)) {
4879         // Even though we accept this undocumented extension for compatibility
4880         // reasons, the additional integer argument does not actually change
4881         // the behaviour of the '.ent' directive, so we would like to discourage
4882         // its use. We do this by not referring to the extended version in
4883         // error messages which are not directly related to its use.
4884         reportParseError("unexpected token, expected end of statement");
4885         return false;
4886       }
4887       Parser.Lex(); // Eat the comma.
4888       const MCExpr *DummyNumber;
4889       int64_t DummyNumberVal;
4890       // If the user was explicitly trying to use the extended version,
4891       // we still give helpful extension-related error messages.
4892       if (Parser.parseExpression(DummyNumber)) {
4893         reportParseError("expected number after comma");
4894         return false;
4895       }
4896       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
4897         reportParseError("expected an absolute expression after comma");
4898         return false;
4899       }
4900     }
4901
4902     // If this is not the end of the statement, report an error.
4903     if (getLexer().isNot(AsmToken::EndOfStatement)) {
4904       reportParseError("unexpected token, expected end of statement");
4905       return false;
4906     }
4907
4908     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
4909
4910     getTargetStreamer().emitDirectiveEnt(*Sym);
4911     CurrentFn = Sym;
4912     return false;
4913   }
4914
4915   if (IDVal == ".end") {
4916     StringRef SymbolName;
4917
4918     if (Parser.parseIdentifier(SymbolName)) {
4919       reportParseError("expected identifier after .end");
4920       return false;
4921     }
4922
4923     if (getLexer().isNot(AsmToken::EndOfStatement)) {
4924       reportParseError("unexpected token, expected end of statement");
4925       return false;
4926     }
4927
4928     if (CurrentFn == nullptr) {
4929       reportParseError(".end used without .ent");
4930       return false;
4931     }
4932
4933     if ((SymbolName != CurrentFn->getName())) {
4934       reportParseError(".end symbol does not match .ent symbol");
4935       return false;
4936     }
4937
4938     getTargetStreamer().emitDirectiveEnd(SymbolName);
4939     CurrentFn = nullptr;
4940     return false;
4941   }
4942
4943   if (IDVal == ".frame") {
4944     // .frame $stack_reg, frame_size_in_bytes, $return_reg
4945     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
4946     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
4947     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
4948       reportParseError("expected stack register");
4949       return false;
4950     }
4951
4952     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
4953     if (!StackRegOpnd.isGPRAsmReg()) {
4954       reportParseError(StackRegOpnd.getStartLoc(),
4955                        "expected general purpose register");
4956       return false;
4957     }
4958     unsigned StackReg = StackRegOpnd.getGPR32Reg();
4959
4960     if (Parser.getTok().is(AsmToken::Comma))
4961       Parser.Lex();
4962     else {
4963       reportParseError("unexpected token, expected comma");
4964       return false;
4965     }
4966
4967     // Parse the frame size.
4968     const MCExpr *FrameSize;
4969     int64_t FrameSizeVal;
4970
4971     if (Parser.parseExpression(FrameSize)) {
4972       reportParseError("expected frame size value");
4973       return false;
4974     }
4975
4976     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
4977       reportParseError("frame size not an absolute expression");
4978       return false;
4979     }
4980
4981     if (Parser.getTok().is(AsmToken::Comma))
4982       Parser.Lex();
4983     else {
4984       reportParseError("unexpected token, expected comma");
4985       return false;
4986     }
4987
4988     // Parse the return register.
4989     TmpReg.clear();
4990     ResTy = parseAnyRegister(TmpReg);
4991     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
4992       reportParseError("expected return register");
4993       return false;
4994     }
4995
4996     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
4997     if (!ReturnRegOpnd.isGPRAsmReg()) {
4998       reportParseError(ReturnRegOpnd.getStartLoc(),
4999                        "expected general purpose register");
5000       return false;
5001     }
5002
5003     // If this is not the end of the statement, report an error.
5004     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5005       reportParseError("unexpected token, expected end of statement");
5006       return false;
5007     }
5008
5009     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
5010                                   ReturnRegOpnd.getGPR32Reg());
5011     return false;
5012   }
5013
5014   if (IDVal == ".set") {
5015     return parseDirectiveSet();
5016   }
5017
5018   if (IDVal == ".mask" || IDVal == ".fmask") {
5019     // .mask bitmask, frame_offset
5020     // bitmask: One bit for each register used.
5021     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
5022     //               first register is expected to be saved.
5023     // Examples:
5024     //   .mask 0x80000000, -4
5025     //   .fmask 0x80000000, -4
5026     //
5027
5028     // Parse the bitmask
5029     const MCExpr *BitMask;
5030     int64_t BitMaskVal;
5031
5032     if (Parser.parseExpression(BitMask)) {
5033       reportParseError("expected bitmask value");
5034       return false;
5035     }
5036
5037     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
5038       reportParseError("bitmask not an absolute expression");
5039       return false;
5040     }
5041
5042     if (Parser.getTok().is(AsmToken::Comma))
5043       Parser.Lex();
5044     else {
5045       reportParseError("unexpected token, expected comma");
5046       return false;
5047     }
5048
5049     // Parse the frame_offset
5050     const MCExpr *FrameOffset;
5051     int64_t FrameOffsetVal;
5052
5053     if (Parser.parseExpression(FrameOffset)) {
5054       reportParseError("expected frame offset value");
5055       return false;
5056     }
5057
5058     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
5059       reportParseError("frame offset not an absolute expression");
5060       return false;
5061     }
5062
5063     // If this is not the end of the statement, report an error.
5064     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5065       reportParseError("unexpected token, expected end of statement");
5066       return false;
5067     }
5068
5069     if (IDVal == ".mask")
5070       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
5071     else
5072       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
5073     return false;
5074   }
5075
5076   if (IDVal == ".nan")
5077     return parseDirectiveNaN();
5078
5079   if (IDVal == ".gpword") {
5080     parseDirectiveGpWord();
5081     return false;
5082   }
5083
5084   if (IDVal == ".gpdword") {
5085     parseDirectiveGpDWord();
5086     return false;
5087   }
5088
5089   if (IDVal == ".word") {
5090     parseDataDirective(4, DirectiveID.getLoc());
5091     return false;
5092   }
5093
5094   if (IDVal == ".option")
5095     return parseDirectiveOption();
5096
5097   if (IDVal == ".abicalls") {
5098     getTargetStreamer().emitDirectiveAbiCalls();
5099     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5100       Error(Parser.getTok().getLoc(), 
5101             "unexpected token, expected end of statement");
5102       // Clear line
5103       Parser.eatToEndOfStatement();
5104     }
5105     return false;
5106   }
5107
5108   if (IDVal == ".cpsetup")
5109     return parseDirectiveCPSetup();
5110
5111   if (IDVal == ".module")
5112     return parseDirectiveModule();
5113
5114   if (IDVal == ".llvm_internal_mips_reallow_module_directive")
5115     return parseInternalDirectiveReallowModule();
5116
5117   if (IDVal == ".insn")
5118     return parseInsnDirective();
5119
5120   return true;
5121 }
5122
5123 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
5124   // If this is not the end of the statement, report an error.
5125   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5126     reportParseError("unexpected token, expected end of statement");
5127     return false;
5128   }
5129
5130   getTargetStreamer().reallowModuleDirective();
5131
5132   getParser().Lex(); // Eat EndOfStatement token.
5133   return false;
5134 }
5135
5136 extern "C" void LLVMInitializeMipsAsmParser() {
5137   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
5138   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
5139   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
5140   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
5141 }
5142
5143 #define GET_REGISTER_MATCHER
5144 #define GET_MATCHER_IMPLEMENTATION
5145 #include "MipsGenAsmMatcher.inc"