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 "MipsTargetObjectFile.h"
15 #include "MipsTargetStreamer.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/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <memory>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "mips-asm-parser"
40 
41 namespace llvm {
42 class MCInstrInfo;
43 }
44 
45 namespace {
46 class MipsAssemblerOptions {
47 public:
48   MipsAssemblerOptions(const FeatureBitset &Features_) :
49     ATReg(1), Reorder(true), Macro(true), Features(Features_) {}
50 
51   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
52     ATReg = Opts->getATRegIndex();
53     Reorder = Opts->isReorder();
54     Macro = Opts->isMacro();
55     Features = Opts->getFeatures();
56   }
57 
58   unsigned getATRegIndex() const { return ATReg; }
59   bool setATRegIndex(unsigned Reg) {
60     if (Reg > 31)
61       return false;
62 
63     ATReg = Reg;
64     return true;
65   }
66 
67   bool isReorder() const { return Reorder; }
68   void setReorder() { Reorder = true; }
69   void setNoReorder() { Reorder = false; }
70 
71   bool isMacro() const { return Macro; }
72   void setMacro() { Macro = true; }
73   void setNoMacro() { Macro = false; }
74 
75   const FeatureBitset &getFeatures() const { return Features; }
76   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
77 
78   // Set of features that are either architecture features or referenced
79   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
80   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
81   // The reason we need this mask is explained in the selectArch function.
82   // FIXME: Ideally we would like TableGen to generate this information.
83   static const FeatureBitset AllArchRelatedMask;
84 
85 private:
86   unsigned ATReg;
87   bool Reorder;
88   bool Macro;
89   FeatureBitset Features;
90 };
91 }
92 
93 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
94     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
95     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
96     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
97     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
98     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
99     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
100     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
101     Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008
102 };
103 
104 namespace {
105 class MipsAsmParser : public MCTargetAsmParser {
106   MipsTargetStreamer &getTargetStreamer() {
107     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
108     return static_cast<MipsTargetStreamer &>(TS);
109   }
110 
111   MipsABIInfo ABI;
112   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
113   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
114                        // nullptr, which indicates that no function is currently
115                        // selected. This usually happens after an '.end func'
116                        // directive.
117   bool IsLittleEndian;
118   bool IsPicEnabled;
119   bool IsCpRestoreSet;
120   int CpRestoreOffset;
121   unsigned CpSaveLocation;
122   /// If true, then CpSaveLocation is a register, otherwise it's an offset.
123   bool     CpSaveLocationIsRegister;
124 
125   // Print a warning along with its fix-it message at the given range.
126   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
127                              SMRange Range, bool ShowColors = true);
128 
129 #define GET_ASSEMBLER_HEADER
130 #include "MipsGenAsmMatcher.inc"
131 
132   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
133 
134   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
135                                OperandVector &Operands, MCStreamer &Out,
136                                uint64_t &ErrorInfo,
137                                bool MatchingInlineAsm) override;
138 
139   /// Parse a register as used in CFI directives
140   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
141 
142   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
143 
144   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
145 
146   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
147                         SMLoc NameLoc, OperandVector &Operands) override;
148 
149   bool ParseDirective(AsmToken DirectiveID) override;
150 
151   OperandMatchResultTy parseMemOperand(OperandVector &Operands);
152   OperandMatchResultTy
153   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
154                                     StringRef Identifier, SMLoc S);
155   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
156                                                      SMLoc S);
157   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
158   OperandMatchResultTy parseImm(OperandVector &Operands);
159   OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
160   OperandMatchResultTy parseInvNum(OperandVector &Operands);
161   OperandMatchResultTy parseLSAImm(OperandVector &Operands);
162   OperandMatchResultTy parseRegisterPair(OperandVector &Operands);
163   OperandMatchResultTy parseMovePRegPair(OperandVector &Operands);
164   OperandMatchResultTy parseRegisterList(OperandVector &Operands);
165 
166   bool searchSymbolAlias(OperandVector &Operands);
167 
168   bool parseOperand(OperandVector &, StringRef Mnemonic);
169 
170   enum MacroExpanderResultTy {
171     MER_NotAMacro,
172     MER_Success,
173     MER_Fail,
174   };
175 
176   // Expands assembly pseudo instructions.
177   MacroExpanderResultTy tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
178                                              MCStreamer &Out,
179                                              const MCSubtargetInfo *STI);
180 
181   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
182                          const MCSubtargetInfo *STI);
183 
184   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
185                      bool Is32BitImm, bool IsAddress, SMLoc IDLoc,
186                      MCStreamer &Out, const MCSubtargetInfo *STI);
187 
188   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
189                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
190                                MCStreamer &Out, const MCSubtargetInfo *STI);
191 
192   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
193                      MCStreamer &Out, const MCSubtargetInfo *STI);
194 
195   bool expandLoadAddress(unsigned DstReg, unsigned BaseReg,
196                          const MCOperand &Offset, bool Is32BitAddress,
197                          SMLoc IDLoc, MCStreamer &Out,
198                          const MCSubtargetInfo *STI);
199 
200   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
201                                   const MCSubtargetInfo *STI);
202 
203   void expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
204                      const MCSubtargetInfo *STI, bool isLoad, bool isImmOpnd);
205 
206   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
207                                const MCSubtargetInfo *STI);
208 
209   bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
210                             const MCSubtargetInfo *STI);
211 
212   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
213                        const MCSubtargetInfo *STI);
214 
215   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
216                           const MCSubtargetInfo *STI);
217 
218   bool expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
219                  const MCSubtargetInfo *STI, const bool IsMips64,
220                  const bool Signed);
221 
222   bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc,
223                    MCStreamer &Out, const MCSubtargetInfo *STI);
224 
225   bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out,
226                  const MCSubtargetInfo *STI);
227 
228   bool expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
229                  const MCSubtargetInfo *STI);
230 
231   bool expandRotation(MCInst &Inst, SMLoc IDLoc,
232                       MCStreamer &Out, const MCSubtargetInfo *STI);
233   bool expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
234                          const MCSubtargetInfo *STI);
235   bool expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
236                        const MCSubtargetInfo *STI);
237   bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
238                           const MCSubtargetInfo *STI);
239 
240   bool expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
241                  const MCSubtargetInfo *STI);
242 
243   void createNop(bool hasShortDelaySlot, SMLoc IDLoc, MCStreamer &Out,
244                  const MCSubtargetInfo *STI);
245 
246   void createAddu(unsigned DstReg, unsigned SrcReg, unsigned TrgReg,
247                   bool Is64Bit, MCStreamer &Out, const MCSubtargetInfo *STI);
248 
249   void createCpRestoreMemOp(bool IsLoad, int StackOffset, SMLoc IDLoc,
250                             MCStreamer &Out, const MCSubtargetInfo *STI);
251 
252   bool reportParseError(Twine ErrorMsg);
253   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
254 
255   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
256   bool parseRelocOperand(const MCExpr *&Res);
257 
258   const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
259 
260   bool isEvaluated(const MCExpr *Expr);
261   bool parseSetMips0Directive();
262   bool parseSetArchDirective();
263   bool parseSetFeature(uint64_t Feature);
264   bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup.
265   bool parseDirectiveCpLoad(SMLoc Loc);
266   bool parseDirectiveCpRestore(SMLoc Loc);
267   bool parseDirectiveCPSetup();
268   bool parseDirectiveCPReturn();
269   bool parseDirectiveNaN();
270   bool parseDirectiveSet();
271   bool parseDirectiveOption();
272   bool parseInsnDirective();
273   bool parseSSectionDirective(StringRef Section, unsigned Type);
274 
275   bool parseSetAtDirective();
276   bool parseSetNoAtDirective();
277   bool parseSetMacroDirective();
278   bool parseSetNoMacroDirective();
279   bool parseSetMsaDirective();
280   bool parseSetNoMsaDirective();
281   bool parseSetNoDspDirective();
282   bool parseSetReorderDirective();
283   bool parseSetNoReorderDirective();
284   bool parseSetMips16Directive();
285   bool parseSetNoMips16Directive();
286   bool parseSetFpDirective();
287   bool parseSetOddSPRegDirective();
288   bool parseSetNoOddSPRegDirective();
289   bool parseSetPopDirective();
290   bool parseSetPushDirective();
291   bool parseSetSoftFloatDirective();
292   bool parseSetHardFloatDirective();
293 
294   bool parseSetAssignment();
295 
296   bool parseDataDirective(unsigned Size, SMLoc L);
297   bool parseDirectiveGpWord();
298   bool parseDirectiveGpDWord();
299   bool parseDirectiveModule();
300   bool parseDirectiveModuleFP();
301   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
302                        StringRef Directive);
303 
304   bool parseInternalDirectiveReallowModule();
305 
306   MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
307 
308   bool eatComma(StringRef ErrorStr);
309 
310   int matchCPURegisterName(StringRef Symbol);
311 
312   int matchHWRegsRegisterName(StringRef Symbol);
313 
314   int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
315 
316   int matchFPURegisterName(StringRef Name);
317 
318   int matchFCCRegisterName(StringRef Name);
319 
320   int matchACRegisterName(StringRef Name);
321 
322   int matchMSA128RegisterName(StringRef Name);
323 
324   int matchMSA128CtrlRegisterName(StringRef Name);
325 
326   unsigned getReg(int RC, int RegNo);
327 
328   unsigned getGPR(int RegNo);
329 
330   /// Returns the internal register number for the current AT. Also checks if
331   /// the current AT is unavailable (set to $0) and gives an error if it is.
332   /// This should be used in pseudo-instruction expansions which need AT.
333   unsigned getATReg(SMLoc Loc);
334 
335   bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
336                           const MCSubtargetInfo *STI);
337 
338   // Helper function that checks if the value of a vector index is within the
339   // boundaries of accepted values for each RegisterKind
340   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
341   bool validateMSAIndex(int Val, int RegKind);
342 
343   // Selects a new architecture by updating the FeatureBits with the necessary
344   // info including implied dependencies.
345   // Internally, it clears all the feature bits related to *any* architecture
346   // and selects the new one using the ToggleFeature functionality of the
347   // MCSubtargetInfo object that handles implied dependencies. The reason we
348   // clear all the arch related bits manually is because ToggleFeature only
349   // clears the features that imply the feature being cleared and not the
350   // features implied by the feature being cleared. This is easier to see
351   // with an example:
352   //  --------------------------------------------------
353   // | Feature         | Implies                        |
354   // | -------------------------------------------------|
355   // | FeatureMips1    | None                           |
356   // | FeatureMips2    | FeatureMips1                   |
357   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
358   // | FeatureMips4    | FeatureMips3                   |
359   // | ...             |                                |
360   //  --------------------------------------------------
361   //
362   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
363   // FeatureMipsGP64 | FeatureMips1)
364   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
365   void selectArch(StringRef ArchFeature) {
366     MCSubtargetInfo &STI = copySTI();
367     FeatureBitset FeatureBits = STI.getFeatureBits();
368     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
369     STI.setFeatureBits(FeatureBits);
370     setAvailableFeatures(
371         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
372     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
373   }
374 
375   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
376     if (!(getSTI().getFeatureBits()[Feature])) {
377       MCSubtargetInfo &STI = copySTI();
378       setAvailableFeatures(
379           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
380       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
381     }
382   }
383 
384   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
385     if (getSTI().getFeatureBits()[Feature]) {
386       MCSubtargetInfo &STI = copySTI();
387       setAvailableFeatures(
388           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
389       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
390     }
391   }
392 
393   void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
394     setFeatureBits(Feature, FeatureString);
395     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
396   }
397 
398   void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
399     clearFeatureBits(Feature, FeatureString);
400     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
401   }
402 
403 public:
404   enum MipsMatchResultTy {
405     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY,
406 #define GET_OPERAND_DIAGNOSTIC_TYPES
407 #include "MipsGenAsmMatcher.inc"
408 #undef GET_OPERAND_DIAGNOSTIC_TYPES
409   };
410 
411   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
412                 const MCInstrInfo &MII, const MCTargetOptions &Options)
413     : MCTargetAsmParser(Options, sti),
414         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
415                                           sti.getCPU(), Options)) {
416     MCAsmParserExtension::Initialize(parser);
417 
418     parser.addAliasForDirective(".asciiz", ".asciz");
419 
420     // Initialize the set of available features.
421     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
422 
423     // Remember the initial assembler options. The user can not modify these.
424     AssemblerOptions.push_back(
425         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
426 
427     // Create an assembler options environment for the user to modify.
428     AssemblerOptions.push_back(
429         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
430 
431     getTargetStreamer().updateABIInfo(*this);
432 
433     if (!isABI_O32() && !useOddSPReg() != 0)
434       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
435 
436     CurrentFn = nullptr;
437 
438     IsPicEnabled =
439         (getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_);
440 
441     IsCpRestoreSet = false;
442     CpRestoreOffset = -1;
443 
444     Triple TheTriple(sti.getTargetTriple());
445     if ((TheTriple.getArch() == Triple::mips) ||
446         (TheTriple.getArch() == Triple::mips64))
447       IsLittleEndian = false;
448     else
449       IsLittleEndian = true;
450   }
451 
452   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
453   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
454 
455   bool isGP64bit() const {
456     return getSTI().getFeatureBits()[Mips::FeatureGP64Bit];
457   }
458   bool isFP64bit() const {
459     return getSTI().getFeatureBits()[Mips::FeatureFP64Bit];
460   }
461   const MipsABIInfo &getABI() const { return ABI; }
462   bool isABI_N32() const { return ABI.IsN32(); }
463   bool isABI_N64() const { return ABI.IsN64(); }
464   bool isABI_O32() const { return ABI.IsO32(); }
465   bool isABI_FPXX() const {
466     return getSTI().getFeatureBits()[Mips::FeatureFPXX];
467   }
468 
469   bool useOddSPReg() const {
470     return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]);
471   }
472 
473   bool inMicroMipsMode() const {
474     return getSTI().getFeatureBits()[Mips::FeatureMicroMips];
475   }
476   bool hasMips1() const {
477     return getSTI().getFeatureBits()[Mips::FeatureMips1];
478   }
479   bool hasMips2() const {
480     return getSTI().getFeatureBits()[Mips::FeatureMips2];
481   }
482   bool hasMips3() const {
483     return getSTI().getFeatureBits()[Mips::FeatureMips3];
484   }
485   bool hasMips4() const {
486     return getSTI().getFeatureBits()[Mips::FeatureMips4];
487   }
488   bool hasMips5() const {
489     return getSTI().getFeatureBits()[Mips::FeatureMips5];
490   }
491   bool hasMips32() const {
492     return getSTI().getFeatureBits()[Mips::FeatureMips32];
493   }
494   bool hasMips64() const {
495     return getSTI().getFeatureBits()[Mips::FeatureMips64];
496   }
497   bool hasMips32r2() const {
498     return getSTI().getFeatureBits()[Mips::FeatureMips32r2];
499   }
500   bool hasMips64r2() const {
501     return getSTI().getFeatureBits()[Mips::FeatureMips64r2];
502   }
503   bool hasMips32r3() const {
504     return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]);
505   }
506   bool hasMips64r3() const {
507     return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]);
508   }
509   bool hasMips32r5() const {
510     return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]);
511   }
512   bool hasMips64r5() const {
513     return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]);
514   }
515   bool hasMips32r6() const {
516     return getSTI().getFeatureBits()[Mips::FeatureMips32r6];
517   }
518   bool hasMips64r6() const {
519     return getSTI().getFeatureBits()[Mips::FeatureMips64r6];
520   }
521 
522   bool hasDSP() const {
523     return getSTI().getFeatureBits()[Mips::FeatureDSP];
524   }
525   bool hasDSPR2() const {
526     return getSTI().getFeatureBits()[Mips::FeatureDSPR2];
527   }
528   bool hasDSPR3() const {
529     return getSTI().getFeatureBits()[Mips::FeatureDSPR3];
530   }
531   bool hasMSA() const {
532     return getSTI().getFeatureBits()[Mips::FeatureMSA];
533   }
534   bool hasCnMips() const {
535     return (getSTI().getFeatureBits()[Mips::FeatureCnMips]);
536   }
537 
538   bool inPicMode() {
539     return IsPicEnabled;
540   }
541 
542   bool inMips16Mode() const {
543     return getSTI().getFeatureBits()[Mips::FeatureMips16];
544   }
545 
546   bool useTraps() const {
547     return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV];
548   }
549 
550   bool useSoftFloat() const {
551     return getSTI().getFeatureBits()[Mips::FeatureSoftFloat];
552   }
553 
554   /// Warn if RegIndex is the same as the current AT.
555   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
556 
557   void warnIfNoMacro(SMLoc Loc);
558 
559   bool isLittle() const { return IsLittleEndian; }
560 };
561 }
562 
563 namespace {
564 
565 /// MipsOperand - Instances of this class represent a parsed Mips machine
566 /// instruction.
567 class MipsOperand : public MCParsedAsmOperand {
568 public:
569   /// Broad categories of register classes
570   /// The exact class is finalized by the render method.
571   enum RegKind {
572     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
573     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
574                           /// isFP64bit())
575     RegKind_FCC = 4,      /// FCC
576     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
577     RegKind_MSACtrl = 16, /// MSA control registers
578     RegKind_COP2 = 32,    /// COP2
579     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
580                           /// context).
581     RegKind_CCR = 128,    /// CCR
582     RegKind_HWRegs = 256, /// HWRegs
583     RegKind_COP3 = 512,   /// COP3
584     RegKind_COP0 = 1024,  /// COP0
585     /// Potentially any (e.g. $1)
586     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
587                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
588                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
589   };
590 
591 private:
592   enum KindTy {
593     k_Immediate,     /// An immediate (possibly involving symbol references)
594     k_Memory,        /// Base + Offset Memory Address
595     k_PhysRegister,  /// A physical register from the Mips namespace
596     k_RegisterIndex, /// A register index in one or more RegKind.
597     k_Token,         /// A simple token
598     k_RegList,       /// A physical register list
599     k_RegPair        /// A pair of physical register
600   } Kind;
601 
602 public:
603   MipsOperand(KindTy K, MipsAsmParser &Parser)
604       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
605 
606 private:
607   /// For diagnostics, and checking the assembler temporary
608   MipsAsmParser &AsmParser;
609 
610   struct Token {
611     const char *Data;
612     unsigned Length;
613   };
614 
615   struct PhysRegOp {
616     unsigned Num; /// Register Number
617   };
618 
619   struct RegIdxOp {
620     unsigned Index; /// Index into the register class
621     RegKind Kind;   /// Bitfield of the kinds it could possibly be
622     const MCRegisterInfo *RegInfo;
623   };
624 
625   struct ImmOp {
626     const MCExpr *Val;
627   };
628 
629   struct MemOp {
630     MipsOperand *Base;
631     const MCExpr *Off;
632   };
633 
634   struct RegListOp {
635     SmallVector<unsigned, 10> *List;
636   };
637 
638   union {
639     struct Token Tok;
640     struct PhysRegOp PhysReg;
641     struct RegIdxOp RegIdx;
642     struct ImmOp Imm;
643     struct MemOp Mem;
644     struct RegListOp RegList;
645   };
646 
647   SMLoc StartLoc, EndLoc;
648 
649   /// Internal constructor for register kinds
650   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
651                                                 const MCRegisterInfo *RegInfo,
652                                                 SMLoc S, SMLoc E,
653                                                 MipsAsmParser &Parser) {
654     auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
655     Op->RegIdx.Index = Index;
656     Op->RegIdx.RegInfo = RegInfo;
657     Op->RegIdx.Kind = RegKind;
658     Op->StartLoc = S;
659     Op->EndLoc = E;
660     return Op;
661   }
662 
663 public:
664   /// Coerce the register to GPR32 and return the real register for the current
665   /// target.
666   unsigned getGPR32Reg() const {
667     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
668     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
669     unsigned ClassID = Mips::GPR32RegClassID;
670     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
671   }
672 
673   /// Coerce the register to GPR32 and return the real register for the current
674   /// target.
675   unsigned getGPRMM16Reg() const {
676     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
677     unsigned ClassID = Mips::GPR32RegClassID;
678     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
679   }
680 
681   /// Coerce the register to GPR64 and return the real register for the current
682   /// target.
683   unsigned getGPR64Reg() const {
684     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
685     unsigned ClassID = Mips::GPR64RegClassID;
686     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
687   }
688 
689 private:
690   /// Coerce the register to AFGR64 and return the real register for the current
691   /// target.
692   unsigned getAFGR64Reg() const {
693     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
694     if (RegIdx.Index % 2 != 0)
695       AsmParser.Warning(StartLoc, "Float register should be even.");
696     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
697         .getRegister(RegIdx.Index / 2);
698   }
699 
700   /// Coerce the register to FGR64 and return the real register for the current
701   /// target.
702   unsigned getFGR64Reg() const {
703     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
704     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
705         .getRegister(RegIdx.Index);
706   }
707 
708   /// Coerce the register to FGR32 and return the real register for the current
709   /// target.
710   unsigned getFGR32Reg() const {
711     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
712     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
713         .getRegister(RegIdx.Index);
714   }
715 
716   /// Coerce the register to FGRH32 and return the real register for the current
717   /// target.
718   unsigned getFGRH32Reg() const {
719     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
720     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
721         .getRegister(RegIdx.Index);
722   }
723 
724   /// Coerce the register to FCC and return the real register for the current
725   /// target.
726   unsigned getFCCReg() const {
727     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
728     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
729         .getRegister(RegIdx.Index);
730   }
731 
732   /// Coerce the register to MSA128 and return the real register for the current
733   /// target.
734   unsigned getMSA128Reg() const {
735     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
736     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
737     // identical
738     unsigned ClassID = Mips::MSA128BRegClassID;
739     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
740   }
741 
742   /// Coerce the register to MSACtrl and return the real register for the
743   /// current target.
744   unsigned getMSACtrlReg() const {
745     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
746     unsigned ClassID = Mips::MSACtrlRegClassID;
747     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
748   }
749 
750   /// Coerce the register to COP0 and return the real register for the
751   /// current target.
752   unsigned getCOP0Reg() const {
753     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
754     unsigned ClassID = Mips::COP0RegClassID;
755     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
756   }
757 
758   /// Coerce the register to COP2 and return the real register for the
759   /// current target.
760   unsigned getCOP2Reg() const {
761     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
762     unsigned ClassID = Mips::COP2RegClassID;
763     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
764   }
765 
766   /// Coerce the register to COP3 and return the real register for the
767   /// current target.
768   unsigned getCOP3Reg() const {
769     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
770     unsigned ClassID = Mips::COP3RegClassID;
771     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
772   }
773 
774   /// Coerce the register to ACC64DSP and return the real register for the
775   /// current target.
776   unsigned getACC64DSPReg() const {
777     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
778     unsigned ClassID = Mips::ACC64DSPRegClassID;
779     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
780   }
781 
782   /// Coerce the register to HI32DSP and return the real register for the
783   /// current target.
784   unsigned getHI32DSPReg() const {
785     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
786     unsigned ClassID = Mips::HI32DSPRegClassID;
787     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
788   }
789 
790   /// Coerce the register to LO32DSP and return the real register for the
791   /// current target.
792   unsigned getLO32DSPReg() const {
793     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
794     unsigned ClassID = Mips::LO32DSPRegClassID;
795     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
796   }
797 
798   /// Coerce the register to CCR and return the real register for the
799   /// current target.
800   unsigned getCCRReg() const {
801     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
802     unsigned ClassID = Mips::CCRRegClassID;
803     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
804   }
805 
806   /// Coerce the register to HWRegs and return the real register for the
807   /// current target.
808   unsigned getHWRegsReg() const {
809     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
810     unsigned ClassID = Mips::HWRegsRegClassID;
811     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
812   }
813 
814 public:
815   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
816     // Add as immediate when possible.  Null MCExpr = 0.
817     if (!Expr)
818       Inst.addOperand(MCOperand::createImm(0));
819     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
820       Inst.addOperand(MCOperand::createImm(CE->getValue()));
821     else
822       Inst.addOperand(MCOperand::createExpr(Expr));
823   }
824 
825   void addRegOperands(MCInst &Inst, unsigned N) const {
826     llvm_unreachable("Use a custom parser instead");
827   }
828 
829   /// Render the operand to an MCInst as a GPR32
830   /// Asserts if the wrong number of operands are requested, or the operand
831   /// is not a k_RegisterIndex compatible with RegKind_GPR
832   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
833     assert(N == 1 && "Invalid number of operands!");
834     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
835   }
836 
837   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
838     assert(N == 1 && "Invalid number of operands!");
839     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
840   }
841 
842   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
843     assert(N == 1 && "Invalid number of operands!");
844     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
845   }
846 
847   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
848     assert(N == 1 && "Invalid number of operands!");
849     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
850   }
851 
852   /// Render the operand to an MCInst as a GPR64
853   /// Asserts if the wrong number of operands are requested, or the operand
854   /// is not a k_RegisterIndex compatible with RegKind_GPR
855   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
856     assert(N == 1 && "Invalid number of operands!");
857     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
858   }
859 
860   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
861     assert(N == 1 && "Invalid number of operands!");
862     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
863   }
864 
865   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
866     assert(N == 1 && "Invalid number of operands!");
867     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
868   }
869 
870   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
871     assert(N == 1 && "Invalid number of operands!");
872     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
873     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
874     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
875       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
876                                 "registers");
877   }
878 
879   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
880     assert(N == 1 && "Invalid number of operands!");
881     Inst.addOperand(MCOperand::createReg(getFGRH32Reg()));
882   }
883 
884   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
885     assert(N == 1 && "Invalid number of operands!");
886     Inst.addOperand(MCOperand::createReg(getFCCReg()));
887   }
888 
889   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
890     assert(N == 1 && "Invalid number of operands!");
891     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
892   }
893 
894   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
895     assert(N == 1 && "Invalid number of operands!");
896     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
897   }
898 
899   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
900     assert(N == 1 && "Invalid number of operands!");
901     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
902   }
903 
904   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
905     assert(N == 1 && "Invalid number of operands!");
906     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
907   }
908 
909   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
910     assert(N == 1 && "Invalid number of operands!");
911     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
912   }
913 
914   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
915     assert(N == 1 && "Invalid number of operands!");
916     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
917   }
918 
919   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
920     assert(N == 1 && "Invalid number of operands!");
921     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
922   }
923 
924   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
925     assert(N == 1 && "Invalid number of operands!");
926     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
927   }
928 
929   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
930     assert(N == 1 && "Invalid number of operands!");
931     Inst.addOperand(MCOperand::createReg(getCCRReg()));
932   }
933 
934   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
935     assert(N == 1 && "Invalid number of operands!");
936     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
937   }
938 
939   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
940   void addConstantUImmOperands(MCInst &Inst, unsigned N) const {
941     assert(N == 1 && "Invalid number of operands!");
942     uint64_t Imm = getConstantImm() - Offset;
943     Imm &= (1 << Bits) - 1;
944     Imm += Offset;
945     Imm += AdjustOffset;
946     Inst.addOperand(MCOperand::createImm(Imm));
947   }
948 
949   template <unsigned Bits>
950   void addSImmOperands(MCInst &Inst, unsigned N) const {
951     if (isImm() && !isConstantImm()) {
952       addExpr(Inst, getImm());
953       return;
954     }
955     addConstantSImmOperands<Bits, 0, 0>(Inst, N);
956   }
957 
958   template <unsigned Bits>
959   void addUImmOperands(MCInst &Inst, unsigned N) const {
960     if (isImm() && !isConstantImm()) {
961       addExpr(Inst, getImm());
962       return;
963     }
964     addConstantUImmOperands<Bits, 0, 0>(Inst, N);
965   }
966 
967   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
968   void addConstantSImmOperands(MCInst &Inst, unsigned N) const {
969     assert(N == 1 && "Invalid number of operands!");
970     int64_t Imm = getConstantImm() - Offset;
971     Imm = SignExtend64<Bits>(Imm);
972     Imm += Offset;
973     Imm += AdjustOffset;
974     Inst.addOperand(MCOperand::createImm(Imm));
975   }
976 
977   void addImmOperands(MCInst &Inst, unsigned N) const {
978     assert(N == 1 && "Invalid number of operands!");
979     const MCExpr *Expr = getImm();
980     addExpr(Inst, Expr);
981   }
982 
983   void addMemOperands(MCInst &Inst, unsigned N) const {
984     assert(N == 2 && "Invalid number of operands!");
985 
986     Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit()
987                                              ? getMemBase()->getGPR64Reg()
988                                              : getMemBase()->getGPR32Reg()));
989 
990     const MCExpr *Expr = getMemOff();
991     addExpr(Inst, Expr);
992   }
993 
994   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
995     assert(N == 2 && "Invalid number of operands!");
996 
997     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
998 
999     const MCExpr *Expr = getMemOff();
1000     addExpr(Inst, Expr);
1001   }
1002 
1003   void addRegListOperands(MCInst &Inst, unsigned N) const {
1004     assert(N == 1 && "Invalid number of operands!");
1005 
1006     for (auto RegNo : getRegList())
1007       Inst.addOperand(MCOperand::createReg(RegNo));
1008   }
1009 
1010   void addRegPairOperands(MCInst &Inst, unsigned N) const {
1011     assert(N == 2 && "Invalid number of operands!");
1012     unsigned RegNo = getRegPair();
1013     Inst.addOperand(MCOperand::createReg(RegNo++));
1014     Inst.addOperand(MCOperand::createReg(RegNo));
1015   }
1016 
1017   void addMovePRegPairOperands(MCInst &Inst, unsigned N) const {
1018     assert(N == 2 && "Invalid number of operands!");
1019     for (auto RegNo : getRegList())
1020       Inst.addOperand(MCOperand::createReg(RegNo));
1021   }
1022 
1023   bool isReg() const override {
1024     // As a special case until we sort out the definition of div/divu, pretend
1025     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
1026     if (isGPRAsmReg() && RegIdx.Index == 0)
1027       return true;
1028 
1029     return Kind == k_PhysRegister;
1030   }
1031   bool isRegIdx() const { return Kind == k_RegisterIndex; }
1032   bool isImm() const override { return Kind == k_Immediate; }
1033   bool isConstantImm() const {
1034     return isImm() && isa<MCConstantExpr>(getImm());
1035   }
1036   bool isConstantImmz() const {
1037     return isConstantImm() && getConstantImm() == 0;
1038   }
1039   template <unsigned Bits, int Offset = 0> bool isConstantUImm() const {
1040     return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset);
1041   }
1042   template <unsigned Bits> bool isSImm() const {
1043     return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm();
1044   }
1045   template <unsigned Bits> bool isUImm() const {
1046     return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm();
1047   }
1048   template <unsigned Bits> bool isAnyImm() const {
1049     return isConstantImm() ? (isInt<Bits>(getConstantImm()) ||
1050                               isUInt<Bits>(getConstantImm()))
1051                            : isImm();
1052   }
1053   template <unsigned Bits, int Offset = 0> bool isConstantSImm() const {
1054     return isConstantImm() && isInt<Bits>(getConstantImm() - Offset);
1055   }
1056   template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const {
1057     return isConstantImm() && getConstantImm() >= Bottom &&
1058            getConstantImm() <= Top;
1059   }
1060   bool isToken() const override {
1061     // Note: It's not possible to pretend that other operand kinds are tokens.
1062     // The matcher emitter checks tokens first.
1063     return Kind == k_Token;
1064   }
1065   bool isMem() const override { return Kind == k_Memory; }
1066   bool isConstantMemOff() const {
1067     return isMem() && isa<MCConstantExpr>(getMemOff());
1068   }
1069   template <unsigned Bits, unsigned ShiftAmount = 0>
1070   bool isMemWithSimmOffset() const {
1071     return isMem() && isConstantMemOff() &&
1072            isShiftedInt<Bits, ShiftAmount>(getConstantMemOff()) &&
1073            getMemBase()->isGPRAsmReg();
1074   }
1075   template <unsigned Bits> bool isMemWithSimmOffsetGPR() const {
1076     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff()) &&
1077            getMemBase()->isGPRAsmReg();
1078   }
1079   bool isMemWithGRPMM16Base() const {
1080     return isMem() && getMemBase()->isMM16AsmReg();
1081   }
1082   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
1083     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1084       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
1085   }
1086   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
1087     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1088       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1089       && (getMemBase()->getGPR32Reg() == Mips::SP);
1090   }
1091   template <unsigned Bits, unsigned ShiftLeftAmount>
1092   bool isScaledUImm() const {
1093     return isConstantImm() &&
1094            isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm());
1095   }
1096   template <unsigned Bits, unsigned ShiftLeftAmount>
1097   bool isScaledSImm() const {
1098     return isConstantImm() &&
1099            isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm());
1100   }
1101   bool isRegList16() const {
1102     if (!isRegList())
1103       return false;
1104 
1105     int Size = RegList.List->size();
1106     if (Size < 2 || Size > 5)
1107       return false;
1108 
1109     unsigned R0 = RegList.List->front();
1110     unsigned R1 = RegList.List->back();
1111     if (!((R0 == Mips::S0 && R1 == Mips::RA) ||
1112           (R0 == Mips::S0_64 && R1 == Mips::RA_64)))
1113       return false;
1114 
1115     int PrevReg = *RegList.List->begin();
1116     for (int i = 1; i < Size - 1; i++) {
1117       int Reg = (*(RegList.List))[i];
1118       if ( Reg != PrevReg + 1)
1119         return false;
1120       PrevReg = Reg;
1121     }
1122 
1123     return true;
1124   }
1125   bool isInvNum() const { return Kind == k_Immediate; }
1126   bool isLSAImm() const {
1127     if (!isConstantImm())
1128       return false;
1129     int64_t Val = getConstantImm();
1130     return 1 <= Val && Val <= 4;
1131   }
1132   bool isRegList() const { return Kind == k_RegList; }
1133   bool isMovePRegPair() const {
1134     if (Kind != k_RegList || RegList.List->size() != 2)
1135       return false;
1136 
1137     unsigned R0 = RegList.List->front();
1138     unsigned R1 = RegList.List->back();
1139 
1140     if ((R0 == Mips::A1 && R1 == Mips::A2) ||
1141         (R0 == Mips::A1 && R1 == Mips::A3) ||
1142         (R0 == Mips::A2 && R1 == Mips::A3) ||
1143         (R0 == Mips::A0 && R1 == Mips::S5) ||
1144         (R0 == Mips::A0 && R1 == Mips::S6) ||
1145         (R0 == Mips::A0 && R1 == Mips::A1) ||
1146         (R0 == Mips::A0 && R1 == Mips::A2) ||
1147         (R0 == Mips::A0 && R1 == Mips::A3))
1148       return true;
1149 
1150     return false;
1151   }
1152 
1153   StringRef getToken() const {
1154     assert(Kind == k_Token && "Invalid access!");
1155     return StringRef(Tok.Data, Tok.Length);
1156   }
1157   bool isRegPair() const { return Kind == k_RegPair; }
1158 
1159   unsigned getReg() const override {
1160     // As a special case until we sort out the definition of div/divu, pretend
1161     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
1162     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1163         RegIdx.Kind & RegKind_GPR)
1164       return getGPR32Reg(); // FIXME: GPR64 too
1165 
1166     assert(Kind == k_PhysRegister && "Invalid access!");
1167     return PhysReg.Num;
1168   }
1169 
1170   const MCExpr *getImm() const {
1171     assert((Kind == k_Immediate) && "Invalid access!");
1172     return Imm.Val;
1173   }
1174 
1175   int64_t getConstantImm() const {
1176     const MCExpr *Val = getImm();
1177     return static_cast<const MCConstantExpr *>(Val)->getValue();
1178   }
1179 
1180   MipsOperand *getMemBase() const {
1181     assert((Kind == k_Memory) && "Invalid access!");
1182     return Mem.Base;
1183   }
1184 
1185   const MCExpr *getMemOff() const {
1186     assert((Kind == k_Memory) && "Invalid access!");
1187     return Mem.Off;
1188   }
1189 
1190   int64_t getConstantMemOff() const {
1191     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1192   }
1193 
1194   const SmallVectorImpl<unsigned> &getRegList() const {
1195     assert((Kind == k_RegList) && "Invalid access!");
1196     return *(RegList.List);
1197   }
1198 
1199   unsigned getRegPair() const {
1200     assert((Kind == k_RegPair) && "Invalid access!");
1201     return RegIdx.Index;
1202   }
1203 
1204   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1205                                                   MipsAsmParser &Parser) {
1206     auto Op = make_unique<MipsOperand>(k_Token, Parser);
1207     Op->Tok.Data = Str.data();
1208     Op->Tok.Length = Str.size();
1209     Op->StartLoc = S;
1210     Op->EndLoc = S;
1211     return Op;
1212   }
1213 
1214   /// Create a numeric register (e.g. $1). The exact register remains
1215   /// unresolved until an instruction successfully matches
1216   static std::unique_ptr<MipsOperand>
1217   createNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1218                    SMLoc E, MipsAsmParser &Parser) {
1219     DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1220     return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
1221   }
1222 
1223   /// Create a register that is definitely a GPR.
1224   /// This is typically only used for named registers such as $gp.
1225   static std::unique_ptr<MipsOperand>
1226   createGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1227                MipsAsmParser &Parser) {
1228     return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
1229   }
1230 
1231   /// Create a register that is definitely a FGR.
1232   /// This is typically only used for named registers such as $f0.
1233   static std::unique_ptr<MipsOperand>
1234   createFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1235                MipsAsmParser &Parser) {
1236     return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
1237   }
1238 
1239   /// Create a register that is definitely a HWReg.
1240   /// This is typically only used for named registers such as $hwr_cpunum.
1241   static std::unique_ptr<MipsOperand>
1242   createHWRegsReg(unsigned Index, const MCRegisterInfo *RegInfo,
1243                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1244     return CreateReg(Index, RegKind_HWRegs, RegInfo, S, E, Parser);
1245   }
1246 
1247   /// Create a register that is definitely an FCC.
1248   /// This is typically only used for named registers such as $fcc0.
1249   static std::unique_ptr<MipsOperand>
1250   createFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1251                MipsAsmParser &Parser) {
1252     return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
1253   }
1254 
1255   /// Create a register that is definitely an ACC.
1256   /// This is typically only used for named registers such as $ac0.
1257   static std::unique_ptr<MipsOperand>
1258   createACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1259                MipsAsmParser &Parser) {
1260     return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
1261   }
1262 
1263   /// Create a register that is definitely an MSA128.
1264   /// This is typically only used for named registers such as $w0.
1265   static std::unique_ptr<MipsOperand>
1266   createMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1267                   SMLoc E, MipsAsmParser &Parser) {
1268     return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
1269   }
1270 
1271   /// Create a register that is definitely an MSACtrl.
1272   /// This is typically only used for named registers such as $msaaccess.
1273   static std::unique_ptr<MipsOperand>
1274   createMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1275                    SMLoc E, MipsAsmParser &Parser) {
1276     return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
1277   }
1278 
1279   static std::unique_ptr<MipsOperand>
1280   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1281     auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
1282     Op->Imm.Val = Val;
1283     Op->StartLoc = S;
1284     Op->EndLoc = E;
1285     return Op;
1286   }
1287 
1288   static std::unique_ptr<MipsOperand>
1289   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1290             SMLoc E, MipsAsmParser &Parser) {
1291     auto Op = make_unique<MipsOperand>(k_Memory, Parser);
1292     Op->Mem.Base = Base.release();
1293     Op->Mem.Off = Off;
1294     Op->StartLoc = S;
1295     Op->EndLoc = E;
1296     return Op;
1297   }
1298 
1299   static std::unique_ptr<MipsOperand>
1300   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1301                 MipsAsmParser &Parser) {
1302     assert (Regs.size() > 0 && "Empty list not allowed");
1303 
1304     auto Op = make_unique<MipsOperand>(k_RegList, Parser);
1305     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1306     Op->StartLoc = StartLoc;
1307     Op->EndLoc = EndLoc;
1308     return Op;
1309   }
1310 
1311   static std::unique_ptr<MipsOperand>
1312   CreateRegPair(unsigned RegNo, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1313     auto Op = make_unique<MipsOperand>(k_RegPair, Parser);
1314     Op->RegIdx.Index = RegNo;
1315     Op->StartLoc = S;
1316     Op->EndLoc = E;
1317     return Op;
1318   }
1319 
1320   bool isGPRAsmReg() const {
1321     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1322   }
1323   bool isMM16AsmReg() const {
1324     if (!(isRegIdx() && RegIdx.Kind))
1325       return false;
1326     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1327             || RegIdx.Index == 16 || RegIdx.Index == 17);
1328   }
1329   bool isMM16AsmRegZero() const {
1330     if (!(isRegIdx() && RegIdx.Kind))
1331       return false;
1332     return (RegIdx.Index == 0 ||
1333             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1334             RegIdx.Index == 17);
1335   }
1336   bool isMM16AsmRegMoveP() const {
1337     if (!(isRegIdx() && RegIdx.Kind))
1338       return false;
1339     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1340       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1341   }
1342   bool isFGRAsmReg() const {
1343     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1344     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1345   }
1346   bool isHWRegsAsmReg() const {
1347     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1348   }
1349   bool isCCRAsmReg() const {
1350     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1351   }
1352   bool isFCCAsmReg() const {
1353     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1354       return false;
1355     if (!AsmParser.hasEightFccRegisters())
1356       return RegIdx.Index == 0;
1357     return RegIdx.Index <= 7;
1358   }
1359   bool isACCAsmReg() const {
1360     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1361   }
1362   bool isCOP0AsmReg() const {
1363     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1364   }
1365   bool isCOP2AsmReg() const {
1366     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1367   }
1368   bool isCOP3AsmReg() const {
1369     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1370   }
1371   bool isMSA128AsmReg() const {
1372     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1373   }
1374   bool isMSACtrlAsmReg() const {
1375     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1376   }
1377 
1378   /// getStartLoc - Get the location of the first token of this operand.
1379   SMLoc getStartLoc() const override { return StartLoc; }
1380   /// getEndLoc - Get the location of the last token of this operand.
1381   SMLoc getEndLoc() const override { return EndLoc; }
1382 
1383   virtual ~MipsOperand() {
1384     switch (Kind) {
1385     case k_Immediate:
1386       break;
1387     case k_Memory:
1388       delete Mem.Base;
1389       break;
1390     case k_RegList:
1391       delete RegList.List;
1392     case k_PhysRegister:
1393     case k_RegisterIndex:
1394     case k_Token:
1395     case k_RegPair:
1396       break;
1397     }
1398   }
1399 
1400   void print(raw_ostream &OS) const override {
1401     switch (Kind) {
1402     case k_Immediate:
1403       OS << "Imm<";
1404       OS << *Imm.Val;
1405       OS << ">";
1406       break;
1407     case k_Memory:
1408       OS << "Mem<";
1409       Mem.Base->print(OS);
1410       OS << ", ";
1411       OS << *Mem.Off;
1412       OS << ">";
1413       break;
1414     case k_PhysRegister:
1415       OS << "PhysReg<" << PhysReg.Num << ">";
1416       break;
1417     case k_RegisterIndex:
1418       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
1419       break;
1420     case k_Token:
1421       OS << Tok.Data;
1422       break;
1423     case k_RegList:
1424       OS << "RegList< ";
1425       for (auto Reg : (*RegList.List))
1426         OS << Reg << " ";
1427       OS <<  ">";
1428       break;
1429     case k_RegPair:
1430       OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">";
1431       break;
1432     }
1433   }
1434 }; // class MipsOperand
1435 } // namespace
1436 
1437 namespace llvm {
1438 extern const MCInstrDesc MipsInsts[];
1439 }
1440 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1441   return MipsInsts[Opcode];
1442 }
1443 
1444 static bool hasShortDelaySlot(unsigned Opcode) {
1445   switch (Opcode) {
1446     case Mips::JALS_MM:
1447     case Mips::JALRS_MM:
1448     case Mips::JALRS16_MM:
1449     case Mips::BGEZALS_MM:
1450     case Mips::BLTZALS_MM:
1451       return true;
1452     default:
1453       return false;
1454   }
1455 }
1456 
1457 static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) {
1458   if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) {
1459     return &SRExpr->getSymbol();
1460   }
1461 
1462   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) {
1463     const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS());
1464     const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS());
1465 
1466     if (LHSSym)
1467       return LHSSym;
1468 
1469     if (RHSSym)
1470       return RHSSym;
1471 
1472     return nullptr;
1473   }
1474 
1475   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1476     return getSingleMCSymbol(UExpr->getSubExpr());
1477 
1478   return nullptr;
1479 }
1480 
1481 static unsigned countMCSymbolRefExpr(const MCExpr *Expr) {
1482   if (isa<MCSymbolRefExpr>(Expr))
1483     return 1;
1484 
1485   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr))
1486     return countMCSymbolRefExpr(BExpr->getLHS()) +
1487            countMCSymbolRefExpr(BExpr->getRHS());
1488 
1489   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1490     return countMCSymbolRefExpr(UExpr->getSubExpr());
1491 
1492   return 0;
1493 }
1494 
1495 namespace {
1496 void emitRX(unsigned Opcode, unsigned Reg0, MCOperand Op1, SMLoc IDLoc,
1497             MCStreamer &Out, const MCSubtargetInfo *STI) {
1498   MCInst tmpInst;
1499   tmpInst.setOpcode(Opcode);
1500   tmpInst.addOperand(MCOperand::createReg(Reg0));
1501   tmpInst.addOperand(Op1);
1502   tmpInst.setLoc(IDLoc);
1503   Out.EmitInstruction(tmpInst, *STI);
1504 }
1505 
1506 void emitRI(unsigned Opcode, unsigned Reg0, int32_t Imm, SMLoc IDLoc,
1507             MCStreamer &Out, const MCSubtargetInfo *STI) {
1508   emitRX(Opcode, Reg0, MCOperand::createImm(Imm), IDLoc, Out, STI);
1509 }
1510 
1511 void emitRR(unsigned Opcode, unsigned Reg0, unsigned Reg1, SMLoc IDLoc,
1512             MCStreamer &Out, const MCSubtargetInfo *STI) {
1513   emitRX(Opcode, Reg0, MCOperand::createReg(Reg1), IDLoc, Out, STI);
1514 }
1515 
1516 void emitII(unsigned Opcode, int16_t Imm1, int16_t Imm2, SMLoc IDLoc,
1517             MCStreamer &Out, const MCSubtargetInfo *STI) {
1518   MCInst tmpInst;
1519   tmpInst.setOpcode(Opcode);
1520   tmpInst.addOperand(MCOperand::createImm(Imm1));
1521   tmpInst.addOperand(MCOperand::createImm(Imm2));
1522   tmpInst.setLoc(IDLoc);
1523   Out.EmitInstruction(tmpInst, *STI);
1524 }
1525 
1526 void emitR(unsigned Opcode, unsigned Reg0, SMLoc IDLoc,
1527            MCStreamer &Out, const MCSubtargetInfo *STI) {
1528   MCInst tmpInst;
1529   tmpInst.setOpcode(Opcode);
1530   tmpInst.addOperand(MCOperand::createReg(Reg0));
1531   tmpInst.setLoc(IDLoc);
1532   Out.EmitInstruction(tmpInst, *STI);
1533 }
1534 
1535 void emitRRX(unsigned Opcode, unsigned Reg0, unsigned Reg1, MCOperand Op2,
1536              SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) {
1537   MCInst tmpInst;
1538   tmpInst.setOpcode(Opcode);
1539   tmpInst.addOperand(MCOperand::createReg(Reg0));
1540   tmpInst.addOperand(MCOperand::createReg(Reg1));
1541   tmpInst.addOperand(Op2);
1542   tmpInst.setLoc(IDLoc);
1543   Out.EmitInstruction(tmpInst, *STI);
1544 }
1545 
1546 void emitRRR(unsigned Opcode, unsigned Reg0, unsigned Reg1, unsigned Reg2,
1547              SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) {
1548   emitRRX(Opcode, Reg0, Reg1, MCOperand::createReg(Reg2), IDLoc, Out, STI);
1549 }
1550 
1551 void emitRRI(unsigned Opcode, unsigned Reg0, unsigned Reg1, int16_t Imm,
1552              SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) {
1553   emitRRX(Opcode, Reg0, Reg1, MCOperand::createImm(Imm), IDLoc, Out, STI);
1554 }
1555 
1556 void emitAppropriateDSLL(unsigned DstReg, unsigned SrcReg, int16_t ShiftAmount,
1557                          SMLoc IDLoc, MCStreamer &Out,
1558                          const MCSubtargetInfo *STI) {
1559   if (ShiftAmount >= 32) {
1560     emitRRI(Mips::DSLL32, DstReg, SrcReg, ShiftAmount - 32, IDLoc, Out, STI);
1561     return;
1562   }
1563 
1564   emitRRI(Mips::DSLL, DstReg, SrcReg, ShiftAmount, IDLoc, Out, STI);
1565 }
1566 } // end anonymous namespace.
1567 
1568 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1569                                        MCStreamer &Out,
1570                                        const MCSubtargetInfo *STI) {
1571   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1572   bool ExpandedJalSym = false;
1573 
1574   Inst.setLoc(IDLoc);
1575 
1576   if (MCID.isBranch() || MCID.isCall()) {
1577     const unsigned Opcode = Inst.getOpcode();
1578     MCOperand Offset;
1579 
1580     switch (Opcode) {
1581     default:
1582       break;
1583     case Mips::BBIT0:
1584     case Mips::BBIT032:
1585     case Mips::BBIT1:
1586     case Mips::BBIT132:
1587       assert(hasCnMips() && "instruction only valid for octeon cpus");
1588       // Fall through
1589 
1590     case Mips::BEQ:
1591     case Mips::BNE:
1592     case Mips::BEQ_MM:
1593     case Mips::BNE_MM:
1594       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1595       Offset = Inst.getOperand(2);
1596       if (!Offset.isImm())
1597         break; // We'll deal with this situation later on when applying fixups.
1598       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1599         return Error(IDLoc, "branch target out of range");
1600       if (OffsetToAlignment(Offset.getImm(),
1601                             1LL << (inMicroMipsMode() ? 1 : 2)))
1602         return Error(IDLoc, "branch to misaligned address");
1603       break;
1604     case Mips::BGEZ:
1605     case Mips::BGTZ:
1606     case Mips::BLEZ:
1607     case Mips::BLTZ:
1608     case Mips::BGEZAL:
1609     case Mips::BLTZAL:
1610     case Mips::BC1F:
1611     case Mips::BC1T:
1612     case Mips::BGEZ_MM:
1613     case Mips::BGTZ_MM:
1614     case Mips::BLEZ_MM:
1615     case Mips::BLTZ_MM:
1616     case Mips::BGEZAL_MM:
1617     case Mips::BLTZAL_MM:
1618     case Mips::BC1F_MM:
1619     case Mips::BC1T_MM:
1620       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1621       Offset = Inst.getOperand(1);
1622       if (!Offset.isImm())
1623         break; // We'll deal with this situation later on when applying fixups.
1624       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1625         return Error(IDLoc, "branch target out of range");
1626       if (OffsetToAlignment(Offset.getImm(),
1627                             1LL << (inMicroMipsMode() ? 1 : 2)))
1628         return Error(IDLoc, "branch to misaligned address");
1629       break;
1630     case Mips::BEQZ16_MM:
1631     case Mips::BEQZC16_MMR6:
1632     case Mips::BNEZ16_MM:
1633     case Mips::BNEZC16_MMR6:
1634       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1635       Offset = Inst.getOperand(1);
1636       if (!Offset.isImm())
1637         break; // We'll deal with this situation later on when applying fixups.
1638       if (!isInt<8>(Offset.getImm()))
1639         return Error(IDLoc, "branch target out of range");
1640       if (OffsetToAlignment(Offset.getImm(), 2LL))
1641         return Error(IDLoc, "branch to misaligned address");
1642       break;
1643     }
1644   }
1645 
1646   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1647   // We still accept it but it is a normal nop.
1648   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1649     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1650     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1651                                                       "nop instruction");
1652   }
1653 
1654   if (hasCnMips()) {
1655     const unsigned Opcode = Inst.getOpcode();
1656     MCOperand Opnd;
1657     int Imm;
1658 
1659     switch (Opcode) {
1660       default:
1661         break;
1662 
1663       case Mips::BBIT0:
1664       case Mips::BBIT032:
1665       case Mips::BBIT1:
1666       case Mips::BBIT132:
1667         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1668         // The offset is handled above
1669         Opnd = Inst.getOperand(1);
1670         if (!Opnd.isImm())
1671           return Error(IDLoc, "expected immediate operand kind");
1672         Imm = Opnd.getImm();
1673         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1674                               Opcode == Mips::BBIT1 ? 63 : 31))
1675           return Error(IDLoc, "immediate operand value out of range");
1676         if (Imm > 31) {
1677           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1678                                                : Mips::BBIT132);
1679           Inst.getOperand(1).setImm(Imm - 32);
1680         }
1681         break;
1682 
1683       case Mips::SEQi:
1684       case Mips::SNEi:
1685         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1686         Opnd = Inst.getOperand(2);
1687         if (!Opnd.isImm())
1688           return Error(IDLoc, "expected immediate operand kind");
1689         Imm = Opnd.getImm();
1690         if (!isInt<10>(Imm))
1691           return Error(IDLoc, "immediate operand value out of range");
1692         break;
1693     }
1694   }
1695 
1696   // This expansion is not in a function called by tryExpandInstruction()
1697   // because the pseudo-instruction doesn't have a distinct opcode.
1698   if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) &&
1699       inPicMode()) {
1700     warnIfNoMacro(IDLoc);
1701 
1702     const MCExpr *JalExpr = Inst.getOperand(0).getExpr();
1703 
1704     // We can do this expansion if there's only 1 symbol in the argument
1705     // expression.
1706     if (countMCSymbolRefExpr(JalExpr) > 1)
1707       return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode");
1708 
1709     // FIXME: This is checking the expression can be handled by the later stages
1710     //        of the assembler. We ought to leave it to those later stages but
1711     //        we can't do that until we stop evaluateRelocExpr() rewriting the
1712     //        expressions into non-equivalent forms.
1713     const MCSymbol *JalSym = getSingleMCSymbol(JalExpr);
1714 
1715     // FIXME: Add support for label+offset operands (currently causes an error).
1716     // FIXME: Add support for forward-declared local symbols.
1717     // FIXME: Add expansion for when the LargeGOT option is enabled.
1718     if (JalSym->isInSection() || JalSym->isTemporary()) {
1719       if (isABI_O32()) {
1720         // If it's a local symbol and the O32 ABI is being used, we expand to:
1721         //  lw $25, 0($gp)
1722         //    R_(MICRO)MIPS_GOT16  label
1723         //  addiu $25, $25, 0
1724         //    R_(MICRO)MIPS_LO16   label
1725         //  jalr  $25
1726         const MCExpr *Got16RelocExpr = evaluateRelocExpr(JalExpr, "got");
1727         const MCExpr *Lo16RelocExpr = evaluateRelocExpr(JalExpr, "lo");
1728 
1729         emitRRX(Mips::LW, Mips::T9, Mips::GP,
1730                 MCOperand::createExpr(Got16RelocExpr), IDLoc, Out, STI);
1731         emitRRX(Mips::ADDiu, Mips::T9, Mips::T9,
1732                 MCOperand::createExpr(Lo16RelocExpr), IDLoc, Out, STI);
1733       } else if (isABI_N32() || isABI_N64()) {
1734         // If it's a local symbol and the N32/N64 ABIs are being used,
1735         // we expand to:
1736         //  lw/ld $25, 0($gp)
1737         //    R_(MICRO)MIPS_GOT_DISP  label
1738         //  jalr  $25
1739         const MCExpr *GotDispRelocExpr = evaluateRelocExpr(JalExpr, "got_disp");
1740 
1741         emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
1742                 MCOperand::createExpr(GotDispRelocExpr), IDLoc, Out, STI);
1743       }
1744     } else {
1745       // If it's an external/weak symbol, we expand to:
1746       //  lw/ld    $25, 0($gp)
1747       //    R_(MICRO)MIPS_CALL16  label
1748       //  jalr  $25
1749       const MCExpr *Call16RelocExpr = evaluateRelocExpr(JalExpr, "call16");
1750 
1751       emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
1752               MCOperand::createExpr(Call16RelocExpr), IDLoc, Out, STI);
1753     }
1754 
1755     MCInst JalrInst;
1756     if (IsCpRestoreSet && inMicroMipsMode())
1757       JalrInst.setOpcode(Mips::JALRS_MM);
1758     else
1759       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
1760     JalrInst.addOperand(MCOperand::createReg(Mips::RA));
1761     JalrInst.addOperand(MCOperand::createReg(Mips::T9));
1762 
1763     // FIXME: Add an R_(MICRO)MIPS_JALR relocation after the JALR.
1764     // This relocation is supposed to be an optimization hint for the linker
1765     // and is not necessary for correctness.
1766 
1767     Inst = JalrInst;
1768     ExpandedJalSym = true;
1769   }
1770 
1771   if (MCID.mayLoad() || MCID.mayStore()) {
1772     // Check the offset of memory operand, if it is a symbol
1773     // reference or immediate we may have to expand instructions.
1774     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1775       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1776       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1777           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1778         MCOperand &Op = Inst.getOperand(i);
1779         if (Op.isImm()) {
1780           int MemOffset = Op.getImm();
1781           if (MemOffset < -32768 || MemOffset > 32767) {
1782             // Offset can't exceed 16bit value.
1783             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), true);
1784             return false;
1785           }
1786         } else if (Op.isExpr()) {
1787           const MCExpr *Expr = Op.getExpr();
1788           if (Expr->getKind() == MCExpr::SymbolRef) {
1789             const MCSymbolRefExpr *SR =
1790                 static_cast<const MCSymbolRefExpr *>(Expr);
1791             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
1792               // Expand symbol.
1793               expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false);
1794               return false;
1795             }
1796           } else if (!isEvaluated(Expr)) {
1797             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false);
1798             return false;
1799           }
1800         }
1801       }
1802     } // for
1803   }   // if load/store
1804 
1805   if (inMicroMipsMode()) {
1806     if (MCID.mayLoad()) {
1807       // Try to create 16-bit GP relative load instruction.
1808       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1809         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1810         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1811             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1812           MCOperand &Op = Inst.getOperand(i);
1813           if (Op.isImm()) {
1814             int MemOffset = Op.getImm();
1815             MCOperand &DstReg = Inst.getOperand(0);
1816             MCOperand &BaseReg = Inst.getOperand(1);
1817             if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) &&
1818                 getContext().getRegisterInfo()->getRegClass(
1819                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
1820                 (BaseReg.getReg() == Mips::GP ||
1821                 BaseReg.getReg() == Mips::GP_64)) {
1822 
1823               emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset,
1824                       IDLoc, Out, STI);
1825               return false;
1826             }
1827           }
1828         }
1829       } // for
1830     }   // if load
1831 
1832     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
1833 
1834     MCOperand Opnd;
1835     int Imm;
1836 
1837     switch (Inst.getOpcode()) {
1838       default:
1839         break;
1840       case Mips::ADDIUSP_MM:
1841         Opnd = Inst.getOperand(0);
1842         if (!Opnd.isImm())
1843           return Error(IDLoc, "expected immediate operand kind");
1844         Imm = Opnd.getImm();
1845         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
1846             Imm % 4 != 0)
1847           return Error(IDLoc, "immediate operand value out of range");
1848         break;
1849       case Mips::SLL16_MM:
1850       case Mips::SRL16_MM:
1851         Opnd = Inst.getOperand(2);
1852         if (!Opnd.isImm())
1853           return Error(IDLoc, "expected immediate operand kind");
1854         Imm = Opnd.getImm();
1855         if (Imm < 1 || Imm > 8)
1856           return Error(IDLoc, "immediate operand value out of range");
1857         break;
1858       case Mips::LI16_MM:
1859         Opnd = Inst.getOperand(1);
1860         if (!Opnd.isImm())
1861           return Error(IDLoc, "expected immediate operand kind");
1862         Imm = Opnd.getImm();
1863         if (Imm < -1 || Imm > 126)
1864           return Error(IDLoc, "immediate operand value out of range");
1865         break;
1866       case Mips::ADDIUR2_MM:
1867         Opnd = Inst.getOperand(2);
1868         if (!Opnd.isImm())
1869           return Error(IDLoc, "expected immediate operand kind");
1870         Imm = Opnd.getImm();
1871         if (!(Imm == 1 || Imm == -1 ||
1872               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
1873           return Error(IDLoc, "immediate operand value out of range");
1874         break;
1875       case Mips::ANDI16_MM:
1876         Opnd = Inst.getOperand(2);
1877         if (!Opnd.isImm())
1878           return Error(IDLoc, "expected immediate operand kind");
1879         Imm = Opnd.getImm();
1880         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
1881               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
1882               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
1883           return Error(IDLoc, "immediate operand value out of range");
1884         break;
1885       case Mips::LBU16_MM:
1886         Opnd = Inst.getOperand(2);
1887         if (!Opnd.isImm())
1888           return Error(IDLoc, "expected immediate operand kind");
1889         Imm = Opnd.getImm();
1890         if (Imm < -1 || Imm > 14)
1891           return Error(IDLoc, "immediate operand value out of range");
1892         break;
1893       case Mips::SB16_MM:
1894       case Mips::SB16_MMR6:
1895         Opnd = Inst.getOperand(2);
1896         if (!Opnd.isImm())
1897           return Error(IDLoc, "expected immediate operand kind");
1898         Imm = Opnd.getImm();
1899         if (Imm < 0 || Imm > 15)
1900           return Error(IDLoc, "immediate operand value out of range");
1901         break;
1902       case Mips::LHU16_MM:
1903       case Mips::SH16_MM:
1904       case Mips::SH16_MMR6:
1905         Opnd = Inst.getOperand(2);
1906         if (!Opnd.isImm())
1907           return Error(IDLoc, "expected immediate operand kind");
1908         Imm = Opnd.getImm();
1909         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
1910           return Error(IDLoc, "immediate operand value out of range");
1911         break;
1912       case Mips::LW16_MM:
1913       case Mips::SW16_MM:
1914       case Mips::SW16_MMR6:
1915         Opnd = Inst.getOperand(2);
1916         if (!Opnd.isImm())
1917           return Error(IDLoc, "expected immediate operand kind");
1918         Imm = Opnd.getImm();
1919         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
1920           return Error(IDLoc, "immediate operand value out of range");
1921         break;
1922       case Mips::ADDIUPC_MM:
1923         MCOperand Opnd = Inst.getOperand(1);
1924         if (!Opnd.isImm())
1925           return Error(IDLoc, "expected immediate operand kind");
1926         int Imm = Opnd.getImm();
1927         if ((Imm % 4 != 0) || !isInt<25>(Imm))
1928           return Error(IDLoc, "immediate operand value out of range");
1929         break;
1930     }
1931   }
1932 
1933   bool FillDelaySlot =
1934       MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder();
1935   if (FillDelaySlot)
1936     getTargetStreamer().emitDirectiveSetNoReorder();
1937 
1938   MacroExpanderResultTy ExpandResult =
1939       tryExpandInstruction(Inst, IDLoc, Out, STI);
1940   switch (ExpandResult) {
1941   case MER_NotAMacro:
1942     Out.EmitInstruction(Inst, *STI);
1943     break;
1944   case MER_Success:
1945     break;
1946   case MER_Fail:
1947     return true;
1948   }
1949 
1950   // If this instruction has a delay slot and .set reorder is active,
1951   // emit a NOP after it.
1952   if (FillDelaySlot) {
1953     createNop(hasShortDelaySlot(Inst.getOpcode()), IDLoc, Out, STI);
1954     getTargetStreamer().emitDirectiveSetReorder();
1955   }
1956 
1957   if ((Inst.getOpcode() == Mips::JalOneReg ||
1958        Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) &&
1959       isPicAndNotNxxAbi()) {
1960     if (IsCpRestoreSet) {
1961       // We need a NOP between the JALR and the LW:
1962       // If .set reorder has been used, we've already emitted a NOP.
1963       // If .set noreorder has been used, we need to emit a NOP at this point.
1964       if (!AssemblerOptions.back()->isReorder())
1965         createNop(hasShortDelaySlot(Inst.getOpcode()), IDLoc, Out, STI);
1966 
1967       // Load the $gp from the stack.
1968       createCpRestoreMemOp(true /*IsLoad*/, CpRestoreOffset /*StackOffset*/,
1969                            IDLoc, Out, STI);
1970     } else
1971       Warning(IDLoc, "no .cprestore used in PIC mode");
1972   }
1973 
1974   return false;
1975 }
1976 
1977 MipsAsmParser::MacroExpanderResultTy
1978 MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
1979                                     const MCSubtargetInfo *STI) {
1980   switch (Inst.getOpcode()) {
1981   default:
1982     return MER_NotAMacro;
1983   case Mips::LoadImm32:
1984     return expandLoadImm(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
1985   case Mips::LoadImm64:
1986     return expandLoadImm(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
1987   case Mips::LoadAddrImm32:
1988   case Mips::LoadAddrImm64:
1989     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1990     assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) &&
1991            "expected immediate operand kind");
1992 
1993     return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister,
1994                              Inst.getOperand(1),
1995                              Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc,
1996                              Out, STI)
1997                ? MER_Fail
1998                : MER_Success;
1999   case Mips::LoadAddrReg32:
2000   case Mips::LoadAddrReg64:
2001     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2002     assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2003     assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) &&
2004            "expected immediate operand kind");
2005 
2006     return expandLoadAddress(Inst.getOperand(0).getReg(),
2007                              Inst.getOperand(1).getReg(), Inst.getOperand(2),
2008                              Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc,
2009                              Out, STI)
2010                ? MER_Fail
2011                : MER_Success;
2012   case Mips::B_MM_Pseudo:
2013   case Mips::B_MMR6_Pseudo:
2014     return expandUncondBranchMMPseudo(Inst, IDLoc, Out, STI) ? MER_Fail
2015                                                              : MER_Success;
2016   case Mips::SWM_MM:
2017   case Mips::LWM_MM:
2018     return expandLoadStoreMultiple(Inst, IDLoc, Out, STI) ? MER_Fail
2019                                                           : MER_Success;
2020   case Mips::JalOneReg:
2021   case Mips::JalTwoReg:
2022     return expandJalWithRegs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2023   case Mips::BneImm:
2024   case Mips::BeqImm:
2025     return expandBranchImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2026   case Mips::BLT:
2027   case Mips::BLE:
2028   case Mips::BGE:
2029   case Mips::BGT:
2030   case Mips::BLTU:
2031   case Mips::BLEU:
2032   case Mips::BGEU:
2033   case Mips::BGTU:
2034   case Mips::BLTL:
2035   case Mips::BLEL:
2036   case Mips::BGEL:
2037   case Mips::BGTL:
2038   case Mips::BLTUL:
2039   case Mips::BLEUL:
2040   case Mips::BGEUL:
2041   case Mips::BGTUL:
2042   case Mips::BLTImmMacro:
2043   case Mips::BLEImmMacro:
2044   case Mips::BGEImmMacro:
2045   case Mips::BGTImmMacro:
2046   case Mips::BLTUImmMacro:
2047   case Mips::BLEUImmMacro:
2048   case Mips::BGEUImmMacro:
2049   case Mips::BGTUImmMacro:
2050   case Mips::BLTLImmMacro:
2051   case Mips::BLELImmMacro:
2052   case Mips::BGELImmMacro:
2053   case Mips::BGTLImmMacro:
2054   case Mips::BLTULImmMacro:
2055   case Mips::BLEULImmMacro:
2056   case Mips::BGEULImmMacro:
2057   case Mips::BGTULImmMacro:
2058     return expandCondBranches(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2059   case Mips::SDivMacro:
2060     return expandDiv(Inst, IDLoc, Out, STI, false, true) ? MER_Fail
2061                                                          : MER_Success;
2062   case Mips::DSDivMacro:
2063     return expandDiv(Inst, IDLoc, Out, STI, true, true) ? MER_Fail
2064                                                         : MER_Success;
2065   case Mips::UDivMacro:
2066     return expandDiv(Inst, IDLoc, Out, STI, false, false) ? MER_Fail
2067                                                           : MER_Success;
2068   case Mips::DUDivMacro:
2069     return expandDiv(Inst, IDLoc, Out, STI, true, false) ? MER_Fail
2070                                                          : MER_Success;
2071   case Mips::PseudoTRUNC_W_S:
2072     return expandTrunc(Inst, false, false, IDLoc, Out, STI) ? MER_Fail
2073                                                             : MER_Success;
2074   case Mips::PseudoTRUNC_W_D32:
2075     return expandTrunc(Inst, true, false, IDLoc, Out, STI) ? MER_Fail
2076                                                            : MER_Success;
2077   case Mips::PseudoTRUNC_W_D:
2078     return expandTrunc(Inst, true, true, IDLoc, Out, STI) ? MER_Fail
2079                                                           : MER_Success;
2080   case Mips::Ulh:
2081     return expandUlh(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2082   case Mips::Ulhu:
2083     return expandUlh(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2084   case Mips::Ulw:
2085     return expandUlw(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2086   case Mips::NORImm:
2087     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2088   case Mips::ADDi:
2089   case Mips::ADDiu:
2090   case Mips::SLTi:
2091   case Mips::SLTiu:
2092     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2093         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2094       int64_t ImmValue = Inst.getOperand(2).getImm();
2095       if (isInt<16>(ImmValue))
2096         return MER_NotAMacro;
2097       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2098                                                          : MER_Success;
2099     }
2100     return MER_NotAMacro;
2101   case Mips::ANDi:
2102   case Mips::ORi:
2103   case Mips::XORi:
2104     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2105         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2106       int64_t ImmValue = Inst.getOperand(2).getImm();
2107       if (isUInt<16>(ImmValue))
2108         return MER_NotAMacro;
2109       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2110                                                          : MER_Success;
2111     }
2112     return MER_NotAMacro;
2113   case Mips::ROL:
2114   case Mips::ROR:
2115     return expandRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2116   case Mips::ROLImm:
2117   case Mips::RORImm:
2118     return expandRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2119   case Mips::DROL:
2120   case Mips::DROR:
2121     return expandDRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2122   case Mips::DROLImm:
2123   case Mips::DRORImm:
2124     return expandDRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2125   case Mips::ABSMacro:
2126     return expandAbs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2127   }
2128 }
2129 
2130 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
2131                                       MCStreamer &Out,
2132                                       const MCSubtargetInfo *STI) {
2133   // Create a JALR instruction which is going to replace the pseudo-JAL.
2134   MCInst JalrInst;
2135   JalrInst.setLoc(IDLoc);
2136   const MCOperand FirstRegOp = Inst.getOperand(0);
2137   const unsigned Opcode = Inst.getOpcode();
2138 
2139   if (Opcode == Mips::JalOneReg) {
2140     // jal $rs => jalr $rs
2141     if (IsCpRestoreSet && inMicroMipsMode()) {
2142       JalrInst.setOpcode(Mips::JALRS16_MM);
2143       JalrInst.addOperand(FirstRegOp);
2144     } else if (inMicroMipsMode()) {
2145       JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM);
2146       JalrInst.addOperand(FirstRegOp);
2147     } else {
2148       JalrInst.setOpcode(Mips::JALR);
2149       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2150       JalrInst.addOperand(FirstRegOp);
2151     }
2152   } else if (Opcode == Mips::JalTwoReg) {
2153     // jal $rd, $rs => jalr $rd, $rs
2154     if (IsCpRestoreSet && inMicroMipsMode())
2155       JalrInst.setOpcode(Mips::JALRS_MM);
2156     else
2157       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2158     JalrInst.addOperand(FirstRegOp);
2159     const MCOperand SecondRegOp = Inst.getOperand(1);
2160     JalrInst.addOperand(SecondRegOp);
2161   }
2162   Out.EmitInstruction(JalrInst, *STI);
2163 
2164   // If .set reorder is active and branch instruction has a delay slot,
2165   // emit a NOP after it.
2166   const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode());
2167   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder()) {
2168     createNop(hasShortDelaySlot(JalrInst.getOpcode()), IDLoc, Out, STI);
2169   }
2170 
2171   return false;
2172 }
2173 
2174 /// Can the value be represented by a unsigned N-bit value and a shift left?
2175 template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) {
2176   unsigned BitNum = findFirstSet(x);
2177 
2178   return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum);
2179 }
2180 
2181 /// Load (or add) an immediate into a register.
2182 ///
2183 /// @param ImmValue     The immediate to load.
2184 /// @param DstReg       The register that will hold the immediate.
2185 /// @param SrcReg       A register to add to the immediate or Mips::NoRegister
2186 ///                     for a simple initialization.
2187 /// @param Is32BitImm   Is ImmValue 32-bit or 64-bit?
2188 /// @param IsAddress    True if the immediate represents an address. False if it
2189 ///                     is an integer.
2190 /// @param IDLoc        Location of the immediate in the source file.
2191 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
2192                                   unsigned SrcReg, bool Is32BitImm,
2193                                   bool IsAddress, SMLoc IDLoc, MCStreamer &Out,
2194                                   const MCSubtargetInfo *STI) {
2195   if (!Is32BitImm && !isGP64bit()) {
2196     Error(IDLoc, "instruction requires a 64-bit architecture");
2197     return true;
2198   }
2199 
2200   if (Is32BitImm) {
2201     if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2202       // Sign extend up to 64-bit so that the predicates match the hardware
2203       // behaviour. In particular, isInt<16>(0xffff8000) and similar should be
2204       // true.
2205       ImmValue = SignExtend64<32>(ImmValue);
2206     } else {
2207       Error(IDLoc, "instruction requires a 32-bit immediate");
2208       return true;
2209     }
2210   }
2211 
2212   unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg();
2213   unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu;
2214 
2215   bool UseSrcReg = false;
2216   if (SrcReg != Mips::NoRegister)
2217     UseSrcReg = true;
2218 
2219   unsigned TmpReg = DstReg;
2220   if (UseSrcReg &&
2221       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2222     // At this point we need AT to perform the expansions and we exit if it is
2223     // not available.
2224     unsigned ATReg = getATReg(IDLoc);
2225     if (!ATReg)
2226       return true;
2227     TmpReg = ATReg;
2228   }
2229 
2230   if (isInt<16>(ImmValue)) {
2231     if (!UseSrcReg)
2232       SrcReg = ZeroReg;
2233 
2234     // This doesn't quite follow the usual ABI expectations for N32 but matches
2235     // traditional assembler behaviour. N32 would normally use addiu for both
2236     // integers and addresses.
2237     if (IsAddress && !Is32BitImm) {
2238       emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, Out, STI);
2239       return false;
2240     }
2241 
2242     emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, Out, STI);
2243     return false;
2244   }
2245 
2246   if (isUInt<16>(ImmValue)) {
2247     unsigned TmpReg = DstReg;
2248     if (SrcReg == DstReg) {
2249       TmpReg = getATReg(IDLoc);
2250       if (!TmpReg)
2251         return true;
2252     }
2253 
2254     emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, Out, STI);
2255     if (UseSrcReg)
2256       emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2257     return false;
2258   }
2259 
2260   if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2261     warnIfNoMacro(IDLoc);
2262 
2263     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
2264     uint16_t Bits15To0 = ImmValue & 0xffff;
2265 
2266     if (!Is32BitImm && !isInt<32>(ImmValue)) {
2267       // Traditional behaviour seems to special case this particular value. It's
2268       // not clear why other masks are handled differently.
2269       if (ImmValue == 0xffffffff) {
2270         emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, Out, STI);
2271         emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, Out, STI);
2272         if (UseSrcReg)
2273           emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2274         return false;
2275       }
2276 
2277       // Expand to an ORi instead of a LUi to avoid sign-extending into the
2278       // upper 32 bits.
2279       emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, Out, STI);
2280       emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, Out, STI);
2281       if (Bits15To0)
2282         emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, Out, STI);
2283       if (UseSrcReg)
2284         emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2285       return false;
2286     }
2287 
2288     emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, Out, STI);
2289     if (Bits15To0)
2290       emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, Out, STI);
2291     if (UseSrcReg)
2292       emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2293     return false;
2294   }
2295 
2296   if (isShiftedUIntAtAnyPosition<16>(ImmValue)) {
2297     if (Is32BitImm) {
2298       Error(IDLoc, "instruction requires a 32-bit immediate");
2299       return true;
2300     }
2301 
2302     // Traditionally, these immediates are shifted as little as possible and as
2303     // such we align the most significant bit to bit 15 of our temporary.
2304     unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
2305     unsigned LastSet = findLastSet((uint64_t)ImmValue);
2306     unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
2307     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
2308     emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, Out, STI);
2309     emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, Out, STI);
2310 
2311     if (UseSrcReg)
2312       emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2313 
2314     return false;
2315   }
2316 
2317   warnIfNoMacro(IDLoc);
2318 
2319   // The remaining case is packed with a sequence of dsll and ori with zeros
2320   // being omitted and any neighbouring dsll's being coalesced.
2321   // The highest 32-bit's are equivalent to a 32-bit immediate load.
2322 
2323   // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register.
2324   if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false,
2325                     IDLoc, Out, STI))
2326     return false;
2327 
2328   // Shift and accumulate into the register. If a 16-bit chunk is zero, then
2329   // skip it and defer the shift to the next chunk.
2330   unsigned ShiftCarriedForwards = 16;
2331   for (int BitNum = 16; BitNum >= 0; BitNum -= 16) {
2332     uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff;
2333 
2334     if (ImmChunk != 0) {
2335       emitAppropriateDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc,
2336                           Out, STI);
2337       emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, Out, STI);
2338       ShiftCarriedForwards = 0;
2339     }
2340 
2341     ShiftCarriedForwards += 16;
2342   }
2343   ShiftCarriedForwards -= 16;
2344 
2345   // Finish any remaining shifts left by trailing zeros.
2346   if (ShiftCarriedForwards)
2347     emitAppropriateDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc,
2348                         Out, STI);
2349 
2350   if (UseSrcReg)
2351     emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2352 
2353   return false;
2354 }
2355 
2356 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2357                                   MCStreamer &Out, const MCSubtargetInfo *STI) {
2358   const MCOperand &ImmOp = Inst.getOperand(1);
2359   assert(ImmOp.isImm() && "expected immediate operand kind");
2360   const MCOperand &DstRegOp = Inst.getOperand(0);
2361   assert(DstRegOp.isReg() && "expected register operand kind");
2362 
2363   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2364                     Is32BitImm, false, IDLoc, Out, STI))
2365     return true;
2366 
2367   return false;
2368 }
2369 
2370 bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg,
2371                                       const MCOperand &Offset,
2372                                       bool Is32BitAddress, SMLoc IDLoc,
2373                                       MCStreamer &Out,
2374                                       const MCSubtargetInfo *STI) {
2375   // la can't produce a usable address when addresses are 64-bit.
2376   if (Is32BitAddress && ABI.ArePtrs64bit()) {
2377     // FIXME: Demote this to a warning and continue as if we had 'dla' instead.
2378     //        We currently can't do this because we depend on the equality
2379     //        operator and N64 can end up with a GPR32/GPR64 mismatch.
2380     Error(IDLoc, "la used to load 64-bit address");
2381     // Continue as if we had 'dla' instead.
2382     Is32BitAddress = false;
2383   }
2384 
2385   // dla requires 64-bit addresses.
2386   if (!Is32BitAddress && !hasMips3()) {
2387     Error(IDLoc, "instruction requires a 64-bit architecture");
2388     return true;
2389   }
2390 
2391   if (!Offset.isImm())
2392     return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg,
2393                                    Is32BitAddress, IDLoc, Out, STI);
2394 
2395   if (!ABI.ArePtrs64bit()) {
2396     // Continue as if we had 'la' whether we had 'la' or 'dla'.
2397     Is32BitAddress = true;
2398   }
2399 
2400   return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true,
2401                        IDLoc, Out, STI);
2402 }
2403 
2404 bool MipsAsmParser::loadAndAddSymbolAddress(const MCExpr *SymExpr,
2405                                             unsigned DstReg, unsigned SrcReg,
2406                                             bool Is32BitSym, SMLoc IDLoc,
2407                                             MCStreamer &Out,
2408                                             const MCSubtargetInfo *STI) {
2409   warnIfNoMacro(IDLoc);
2410 
2411   const MCExpr *Symbol = cast<MCExpr>(SymExpr);
2412   const MipsMCExpr *HiExpr = MipsMCExpr::create(
2413       MCSymbolRefExpr::VK_Mips_ABS_HI, Symbol, getContext());
2414   const MipsMCExpr *LoExpr = MipsMCExpr::create(
2415       MCSymbolRefExpr::VK_Mips_ABS_LO, Symbol, getContext());
2416 
2417   bool UseSrcReg = SrcReg != Mips::NoRegister;
2418 
2419   // This is the 64-bit symbol address expansion.
2420   if (ABI.ArePtrs64bit() && isGP64bit()) {
2421     // We always need AT for the 64-bit expansion.
2422     // If it is not available we exit.
2423     unsigned ATReg = getATReg(IDLoc);
2424     if (!ATReg)
2425       return true;
2426 
2427     const MipsMCExpr *HighestExpr = MipsMCExpr::create(
2428         MCSymbolRefExpr::VK_Mips_HIGHEST, Symbol, getContext());
2429     const MipsMCExpr *HigherExpr = MipsMCExpr::create(
2430         MCSymbolRefExpr::VK_Mips_HIGHER, Symbol, getContext());
2431 
2432     if (UseSrcReg &&
2433         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2434                                                                SrcReg)) {
2435       // If $rs is the same as $rd:
2436       // (d)la $rd, sym($rd) => lui    $at, %highest(sym)
2437       //                        daddiu $at, $at, %higher(sym)
2438       //                        dsll   $at, $at, 16
2439       //                        daddiu $at, $at, %hi(sym)
2440       //                        dsll   $at, $at, 16
2441       //                        daddiu $at, $at, %lo(sym)
2442       //                        daddu  $rd, $at, $rd
2443       emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc, Out,
2444              STI);
2445       emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HigherExpr),
2446               IDLoc, Out, STI);
2447       emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, Out, STI);
2448       emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr), IDLoc,
2449               Out, STI);
2450       emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, Out, STI);
2451       emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr), IDLoc,
2452               Out, STI);
2453       emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, Out, STI);
2454 
2455       return false;
2456     }
2457 
2458     // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2459     // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
2460     //                            lui    $at, %hi(sym)
2461     //                            daddiu $rd, $rd, %higher(sym)
2462     //                            daddiu $at, $at, %lo(sym)
2463     //                            dsll32 $rd, $rd, 0
2464     //                            daddu  $rd, $rd, $at
2465     //                            (daddu  $rd, $rd, $rs)
2466     emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc, Out,
2467            STI);
2468     emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, Out, STI);
2469     emitRRX(Mips::DADDiu, DstReg, DstReg, MCOperand::createExpr(HigherExpr),
2470             IDLoc, Out, STI);
2471     emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr), IDLoc,
2472             Out, STI);
2473     emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, Out, STI);
2474     emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, Out, STI);
2475     if (UseSrcReg)
2476       emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, Out, STI);
2477 
2478     return false;
2479   }
2480 
2481   // And now, the 32-bit symbol address expansion:
2482   // If $rs is the same as $rd:
2483   // (d)la $rd, sym($rd)     => lui   $at, %hi(sym)
2484   //                            ori   $at, $at, %lo(sym)
2485   //                            addu  $rd, $at, $rd
2486   // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2487   // (d)la $rd, sym/sym($rs) => lui   $rd, %hi(sym)
2488   //                            ori   $rd, $rd, %lo(sym)
2489   //                            (addu $rd, $rd, $rs)
2490   unsigned TmpReg = DstReg;
2491   if (UseSrcReg &&
2492       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2493     // If $rs is the same as $rd, we need to use AT.
2494     // If it is not available we exit.
2495     unsigned ATReg = getATReg(IDLoc);
2496     if (!ATReg)
2497       return true;
2498     TmpReg = ATReg;
2499   }
2500 
2501   emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, Out, STI);
2502   emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr), IDLoc,
2503           Out, STI);
2504 
2505   if (UseSrcReg)
2506     emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, Out, STI);
2507   else
2508     assert(
2509         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg));
2510 
2511   return false;
2512 }
2513 
2514 bool MipsAsmParser::expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
2515                                                MCStreamer &Out,
2516                                                const MCSubtargetInfo *STI) {
2517   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
2518          "unexpected number of operands");
2519 
2520   MCOperand Offset = Inst.getOperand(0);
2521   if (Offset.isExpr()) {
2522     Inst.clear();
2523     Inst.setOpcode(Mips::BEQ_MM);
2524     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2525     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2526     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
2527   } else {
2528     assert(Offset.isImm() && "expected immediate operand kind");
2529     if (isInt<11>(Offset.getImm())) {
2530       // If offset fits into 11 bits then this instruction becomes microMIPS
2531       // 16-bit unconditional branch instruction.
2532       if (inMicroMipsMode())
2533         Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM);
2534     } else {
2535       if (!isInt<17>(Offset.getImm()))
2536         Error(IDLoc, "branch target out of range");
2537       if (OffsetToAlignment(Offset.getImm(), 1LL << 1))
2538         Error(IDLoc, "branch to misaligned address");
2539       Inst.clear();
2540       Inst.setOpcode(Mips::BEQ_MM);
2541       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2542       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2543       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
2544     }
2545   }
2546   Out.EmitInstruction(Inst, *STI);
2547 
2548   // If .set reorder is active and branch instruction has a delay slot,
2549   // emit a NOP after it.
2550   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
2551   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2552     createNop(true, IDLoc, Out, STI);
2553 
2554   return false;
2555 }
2556 
2557 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2558                                     const MCSubtargetInfo *STI) {
2559   const MCOperand &DstRegOp = Inst.getOperand(0);
2560   assert(DstRegOp.isReg() && "expected register operand kind");
2561 
2562   const MCOperand &ImmOp = Inst.getOperand(1);
2563   assert(ImmOp.isImm() && "expected immediate operand kind");
2564 
2565   const MCOperand &MemOffsetOp = Inst.getOperand(2);
2566   assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) &&
2567          "expected immediate or expression operand");
2568 
2569   unsigned OpCode = 0;
2570   switch(Inst.getOpcode()) {
2571     case Mips::BneImm:
2572       OpCode = Mips::BNE;
2573       break;
2574     case Mips::BeqImm:
2575       OpCode = Mips::BEQ;
2576       break;
2577     default:
2578       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
2579       break;
2580   }
2581 
2582   int64_t ImmValue = ImmOp.getImm();
2583   if (ImmValue == 0)
2584     emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc, Out,
2585             STI);
2586   else {
2587     warnIfNoMacro(IDLoc);
2588 
2589     unsigned ATReg = getATReg(IDLoc);
2590     if (!ATReg)
2591       return true;
2592 
2593     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true,
2594                       IDLoc, Out, STI))
2595       return true;
2596 
2597     emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, Out, STI);
2598   }
2599   return false;
2600 }
2601 
2602 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2603                                   const MCSubtargetInfo *STI, bool isLoad,
2604                                   bool isImmOpnd) {
2605   MCOperand HiOperand, LoOperand;
2606   unsigned TmpRegNum;
2607   // 1st operand is either the source or destination register.
2608   assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2609   unsigned RegOpNum = Inst.getOperand(0).getReg();
2610   // 2nd operand is the base register.
2611   assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2612   unsigned BaseRegNum = Inst.getOperand(1).getReg();
2613   // 3rd operand is either an immediate or expression.
2614   if (isImmOpnd) {
2615     assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
2616     unsigned ImmOffset = Inst.getOperand(2).getImm();
2617     unsigned LoOffset = ImmOffset & 0x0000ffff;
2618     unsigned HiOffset = (ImmOffset & 0xffff0000) >> 16;
2619     // If msb of LoOffset is 1(negative number) we must increment HiOffset.
2620     if (LoOffset & 0x8000)
2621       HiOffset++;
2622     LoOperand = MCOperand::createImm(LoOffset);
2623     HiOperand = MCOperand::createImm(HiOffset);
2624   } else {
2625     const MCExpr *ExprOffset = Inst.getOperand(2).getExpr();
2626     LoOperand = MCOperand::createExpr(evaluateRelocExpr(ExprOffset, "lo"));
2627     HiOperand = MCOperand::createExpr(evaluateRelocExpr(ExprOffset, "hi"));
2628   }
2629   // These are some of the types of expansions we perform here:
2630   // 1) lw $8, sym        => lui $8, %hi(sym)
2631   //                         lw $8, %lo(sym)($8)
2632   // 2) lw $8, offset($9) => lui $8, %hi(offset)
2633   //                         add $8, $8, $9
2634   //                         lw $8, %lo(offset)($9)
2635   // 3) lw $8, offset($8) => lui $at, %hi(offset)
2636   //                         add $at, $at, $8
2637   //                         lw $8, %lo(offset)($at)
2638   // 4) sw $8, sym        => lui $at, %hi(sym)
2639   //                         sw $8, %lo(sym)($at)
2640   // 5) sw $8, offset($8) => lui $at, %hi(offset)
2641   //                         add $at, $at, $8
2642   //                         sw $8, %lo(offset)($at)
2643   // 6) ldc1 $f0, sym     => lui $at, %hi(sym)
2644   //                         ldc1 $f0, %lo(sym)($at)
2645   //
2646   // For load instructions we can use the destination register as a temporary
2647   // if base and dst are different (examples 1 and 2) and if the base register
2648   // is general purpose otherwise we must use $at (example 6) and error if it's
2649   // not available. For stores we must use $at (examples 4 and 5) because we
2650   // must not clobber the source register setting up the offset.
2651   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
2652   int16_t RegClassOp0 = Desc.OpInfo[0].RegClass;
2653   unsigned RegClassIDOp0 =
2654       getContext().getRegisterInfo()->getRegClass(RegClassOp0).getID();
2655   bool IsGPR = (RegClassIDOp0 == Mips::GPR32RegClassID) ||
2656                (RegClassIDOp0 == Mips::GPR64RegClassID);
2657   if (isLoad && IsGPR && (BaseRegNum != RegOpNum))
2658     TmpRegNum = RegOpNum;
2659   else {
2660     // At this point we need AT to perform the expansions and we exit if it is
2661     // not available.
2662     TmpRegNum = getATReg(IDLoc);
2663     if (!TmpRegNum)
2664       return;
2665   }
2666 
2667   emitRX(Mips::LUi, TmpRegNum, HiOperand, IDLoc, Out, STI);
2668   // Add temp register to base.
2669   if (BaseRegNum != Mips::ZERO)
2670     emitRRR(Mips::ADDu, TmpRegNum, TmpRegNum, BaseRegNum, IDLoc, Out, STI);
2671   // And finally, create original instruction with low part
2672   // of offset and new base.
2673   emitRRX(Inst.getOpcode(), RegOpNum, TmpRegNum, LoOperand, IDLoc, Out, STI);
2674 }
2675 
2676 bool MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
2677                                             MCStreamer &Out,
2678                                             const MCSubtargetInfo *STI) {
2679   unsigned OpNum = Inst.getNumOperands();
2680   unsigned Opcode = Inst.getOpcode();
2681   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
2682 
2683   assert (Inst.getOperand(OpNum - 1).isImm() &&
2684           Inst.getOperand(OpNum - 2).isReg() &&
2685           Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
2686 
2687   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
2688       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
2689       (Inst.getOperand(OpNum - 2).getReg() == Mips::SP ||
2690        Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) &&
2691       (Inst.getOperand(OpNum - 3).getReg() == Mips::RA ||
2692        Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) {
2693     // It can be implemented as SWM16 or LWM16 instruction.
2694     if (inMicroMipsMode() && hasMips32r6())
2695       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6;
2696     else
2697       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
2698   }
2699 
2700   Inst.setOpcode(NewOpcode);
2701   Out.EmitInstruction(Inst, *STI);
2702   return false;
2703 }
2704 
2705 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
2706                                        MCStreamer &Out,
2707                                        const MCSubtargetInfo *STI) {
2708   bool EmittedNoMacroWarning = false;
2709   unsigned PseudoOpcode = Inst.getOpcode();
2710   unsigned SrcReg = Inst.getOperand(0).getReg();
2711   const MCOperand &TrgOp = Inst.getOperand(1);
2712   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
2713 
2714   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
2715   bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality;
2716 
2717   unsigned TrgReg;
2718   if (TrgOp.isReg())
2719     TrgReg = TrgOp.getReg();
2720   else if (TrgOp.isImm()) {
2721     warnIfNoMacro(IDLoc);
2722     EmittedNoMacroWarning = true;
2723 
2724     TrgReg = getATReg(IDLoc);
2725     if (!TrgReg)
2726       return true;
2727 
2728     switch(PseudoOpcode) {
2729     default:
2730       llvm_unreachable("unknown opcode for branch pseudo-instruction");
2731     case Mips::BLTImmMacro:
2732       PseudoOpcode = Mips::BLT;
2733       break;
2734     case Mips::BLEImmMacro:
2735       PseudoOpcode = Mips::BLE;
2736       break;
2737     case Mips::BGEImmMacro:
2738       PseudoOpcode = Mips::BGE;
2739       break;
2740     case Mips::BGTImmMacro:
2741       PseudoOpcode = Mips::BGT;
2742       break;
2743     case Mips::BLTUImmMacro:
2744       PseudoOpcode = Mips::BLTU;
2745       break;
2746     case Mips::BLEUImmMacro:
2747       PseudoOpcode = Mips::BLEU;
2748       break;
2749     case Mips::BGEUImmMacro:
2750       PseudoOpcode = Mips::BGEU;
2751       break;
2752     case Mips::BGTUImmMacro:
2753       PseudoOpcode = Mips::BGTU;
2754       break;
2755     case Mips::BLTLImmMacro:
2756       PseudoOpcode = Mips::BLTL;
2757       break;
2758     case Mips::BLELImmMacro:
2759       PseudoOpcode = Mips::BLEL;
2760       break;
2761     case Mips::BGELImmMacro:
2762       PseudoOpcode = Mips::BGEL;
2763       break;
2764     case Mips::BGTLImmMacro:
2765       PseudoOpcode = Mips::BGTL;
2766       break;
2767     case Mips::BLTULImmMacro:
2768       PseudoOpcode = Mips::BLTUL;
2769       break;
2770     case Mips::BLEULImmMacro:
2771       PseudoOpcode = Mips::BLEUL;
2772       break;
2773     case Mips::BGEULImmMacro:
2774       PseudoOpcode = Mips::BGEUL;
2775       break;
2776     case Mips::BGTULImmMacro:
2777       PseudoOpcode = Mips::BGTUL;
2778       break;
2779     }
2780 
2781     if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(),
2782                       false, IDLoc, Out, STI))
2783       return true;
2784   }
2785 
2786   switch (PseudoOpcode) {
2787   case Mips::BLT:
2788   case Mips::BLTU:
2789   case Mips::BLTL:
2790   case Mips::BLTUL:
2791     AcceptsEquality = false;
2792     ReverseOrderSLT = false;
2793     IsUnsigned = ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL));
2794     IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL));
2795     ZeroSrcOpcode = Mips::BGTZ;
2796     ZeroTrgOpcode = Mips::BLTZ;
2797     break;
2798   case Mips::BLE:
2799   case Mips::BLEU:
2800   case Mips::BLEL:
2801   case Mips::BLEUL:
2802     AcceptsEquality = true;
2803     ReverseOrderSLT = true;
2804     IsUnsigned = ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL));
2805     IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL));
2806     ZeroSrcOpcode = Mips::BGEZ;
2807     ZeroTrgOpcode = Mips::BLEZ;
2808     break;
2809   case Mips::BGE:
2810   case Mips::BGEU:
2811   case Mips::BGEL:
2812   case Mips::BGEUL:
2813     AcceptsEquality = true;
2814     ReverseOrderSLT = false;
2815     IsUnsigned = ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL));
2816     IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL));
2817     ZeroSrcOpcode = Mips::BLEZ;
2818     ZeroTrgOpcode = Mips::BGEZ;
2819     break;
2820   case Mips::BGT:
2821   case Mips::BGTU:
2822   case Mips::BGTL:
2823   case Mips::BGTUL:
2824     AcceptsEquality = false;
2825     ReverseOrderSLT = true;
2826     IsUnsigned = ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL));
2827     IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL));
2828     ZeroSrcOpcode = Mips::BLTZ;
2829     ZeroTrgOpcode = Mips::BGTZ;
2830     break;
2831   default:
2832     llvm_unreachable("unknown opcode for branch pseudo-instruction");
2833   }
2834 
2835   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
2836   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
2837   if (IsSrcRegZero && IsTrgRegZero) {
2838     // FIXME: All of these Opcode-specific if's are needed for compatibility
2839     // with GAS' behaviour. However, they may not generate the most efficient
2840     // code in some circumstances.
2841     if (PseudoOpcode == Mips::BLT) {
2842       emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2843              Out, STI);
2844       return false;
2845     }
2846     if (PseudoOpcode == Mips::BLE) {
2847       emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2848              Out, STI);
2849       Warning(IDLoc, "branch is always taken");
2850       return false;
2851     }
2852     if (PseudoOpcode == Mips::BGE) {
2853       emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2854              Out, STI);
2855       Warning(IDLoc, "branch is always taken");
2856       return false;
2857     }
2858     if (PseudoOpcode == Mips::BGT) {
2859       emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2860              Out, STI);
2861       return false;
2862     }
2863     if (PseudoOpcode == Mips::BGTU) {
2864       emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO,
2865               MCOperand::createExpr(OffsetExpr), IDLoc, Out, STI);
2866       return false;
2867     }
2868     if (AcceptsEquality) {
2869       // If both registers are $0 and the pseudo-branch accepts equality, it
2870       // will always be taken, so we emit an unconditional branch.
2871       emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
2872               MCOperand::createExpr(OffsetExpr), IDLoc, Out, STI);
2873       Warning(IDLoc, "branch is always taken");
2874       return false;
2875     }
2876     // If both registers are $0 and the pseudo-branch does not accept
2877     // equality, it will never be taken, so we don't have to emit anything.
2878     return false;
2879   }
2880   if (IsSrcRegZero || IsTrgRegZero) {
2881     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
2882         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
2883       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
2884       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
2885       // the pseudo-branch will never be taken, so we don't emit anything.
2886       // This only applies to unsigned pseudo-branches.
2887       return false;
2888     }
2889     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
2890         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
2891       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
2892       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
2893       // the pseudo-branch will always be taken, so we emit an unconditional
2894       // branch.
2895       // This only applies to unsigned pseudo-branches.
2896       emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
2897               MCOperand::createExpr(OffsetExpr), IDLoc, Out, STI);
2898       Warning(IDLoc, "branch is always taken");
2899       return false;
2900     }
2901     if (IsUnsigned) {
2902       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
2903       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
2904       // the pseudo-branch will be taken only when the non-zero register is
2905       // different from 0, so we emit a BNEZ.
2906       //
2907       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
2908       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
2909       // the pseudo-branch will be taken only when the non-zero register is
2910       // equal to 0, so we emit a BEQZ.
2911       //
2912       // Because only BLEU and BGEU branch on equality, we can use the
2913       // AcceptsEquality variable to decide when to emit the BEQZ.
2914       emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE,
2915               IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO,
2916               MCOperand::createExpr(OffsetExpr), IDLoc, Out, STI);
2917       return false;
2918     }
2919     // If we have a signed pseudo-branch and one of the registers is $0,
2920     // we can use an appropriate compare-to-zero branch. We select which one
2921     // to use in the switch statement above.
2922     emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode,
2923            IsSrcRegZero ? TrgReg : SrcReg, MCOperand::createExpr(OffsetExpr),
2924            IDLoc, Out, STI);
2925     return false;
2926   }
2927 
2928   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
2929   // expansions. If it is not available, we return.
2930   unsigned ATRegNum = getATReg(IDLoc);
2931   if (!ATRegNum)
2932     return true;
2933 
2934   if (!EmittedNoMacroWarning)
2935     warnIfNoMacro(IDLoc);
2936 
2937   // SLT fits well with 2 of our 4 pseudo-branches:
2938   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
2939   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
2940   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
2941   // This is accomplished by using a BNEZ with the result of the SLT.
2942   //
2943   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
2944   // and BLE with BGT), so we change the BNEZ into a a BEQZ.
2945   // Because only BGE and BLE branch on equality, we can use the
2946   // AcceptsEquality variable to decide when to emit the BEQZ.
2947   // Note that the order of the SLT arguments doesn't change between
2948   // opposites.
2949   //
2950   // The same applies to the unsigned variants, except that SLTu is used
2951   // instead of SLT.
2952   emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum,
2953           ReverseOrderSLT ? TrgReg : SrcReg, ReverseOrderSLT ? SrcReg : TrgReg,
2954           IDLoc, Out, STI);
2955 
2956   emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL)
2957                    : (AcceptsEquality ? Mips::BEQ : Mips::BNE),
2958           ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2959           Out, STI);
2960   return false;
2961 }
2962 
2963 bool MipsAsmParser::expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2964                               const MCSubtargetInfo *STI, const bool IsMips64,
2965                               const bool Signed) {
2966   if (hasMips32r6()) {
2967     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
2968     return false;
2969   }
2970 
2971   warnIfNoMacro(IDLoc);
2972 
2973   const MCOperand &RsRegOp = Inst.getOperand(0);
2974   assert(RsRegOp.isReg() && "expected register operand kind");
2975   unsigned RsReg = RsRegOp.getReg();
2976 
2977   const MCOperand &RtRegOp = Inst.getOperand(1);
2978   assert(RtRegOp.isReg() && "expected register operand kind");
2979   unsigned RtReg = RtRegOp.getReg();
2980   unsigned DivOp;
2981   unsigned ZeroReg;
2982 
2983   if (IsMips64) {
2984     DivOp = Signed ? Mips::DSDIV : Mips::DUDIV;
2985     ZeroReg = Mips::ZERO_64;
2986   } else {
2987     DivOp = Signed ? Mips::SDIV : Mips::UDIV;
2988     ZeroReg = Mips::ZERO;
2989   }
2990 
2991   bool UseTraps = useTraps();
2992 
2993   if (RsReg == Mips::ZERO || RsReg == Mips::ZERO_64) {
2994     if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)
2995       Warning(IDLoc, "dividing zero by zero");
2996     if (IsMips64) {
2997       if (Signed && (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) {
2998         if (UseTraps) {
2999           emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, Out, STI);
3000           return false;
3001         }
3002 
3003         emitII(Mips::BREAK, 0x7, 0, IDLoc, Out, STI);
3004         return false;
3005       }
3006     } else {
3007       emitRR(DivOp, RsReg, RtReg, IDLoc, Out, STI);
3008       return false;
3009     }
3010   }
3011 
3012   if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) {
3013     Warning(IDLoc, "division by zero");
3014     if (Signed) {
3015       if (UseTraps) {
3016         emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, Out, STI);
3017         return false;
3018       }
3019 
3020       emitII(Mips::BREAK, 0x7, 0, IDLoc, Out, STI);
3021       return false;
3022     }
3023   }
3024 
3025   // FIXME: The values for these two BranchTarget variables may be different in
3026   // micromips. These magic numbers need to be removed.
3027   unsigned BranchTargetNoTraps;
3028   unsigned BranchTarget;
3029 
3030   if (UseTraps) {
3031     BranchTarget = IsMips64 ? 12 : 8;
3032     emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, Out, STI);
3033   } else {
3034     BranchTarget = IsMips64 ? 20 : 16;
3035     BranchTargetNoTraps = 8;
3036     // Branch to the li instruction.
3037     emitRRI(Mips::BNE, RtReg, ZeroReg, BranchTargetNoTraps, IDLoc, Out, STI);
3038   }
3039 
3040   emitRR(DivOp, RsReg, RtReg, IDLoc, Out, STI);
3041 
3042   if (!UseTraps)
3043     emitII(Mips::BREAK, 0x7, 0, IDLoc, Out, STI);
3044 
3045   if (!Signed) {
3046     emitR(Mips::MFLO, RsReg, IDLoc, Out, STI);
3047     return false;
3048   }
3049 
3050   unsigned ATReg = getATReg(IDLoc);
3051   if (!ATReg)
3052     return true;
3053 
3054   emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, Out, STI);
3055   if (IsMips64) {
3056     // Branch to the mflo instruction.
3057     emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, Out, STI);
3058     emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, Out, STI);
3059     emitRRI(Mips::DSLL32, ATReg, ATReg, 0x1f, IDLoc, Out, STI);
3060   } else {
3061     // Branch to the mflo instruction.
3062     emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, Out, STI);
3063     emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, Out, STI);
3064   }
3065 
3066   if (UseTraps)
3067     emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, Out, STI);
3068   else {
3069     // Branch to the mflo instruction.
3070     emitRRI(Mips::BNE, RsReg, ATReg, BranchTargetNoTraps, IDLoc, Out, STI);
3071     emitRRI(Mips::SLL, ZeroReg, ZeroReg, 0, IDLoc, Out, STI);
3072     emitII(Mips::BREAK, 0x6, 0, IDLoc, Out, STI);
3073   }
3074   emitR(Mips::MFLO, RsReg, IDLoc, Out, STI);
3075   return false;
3076 }
3077 
3078 bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU,
3079                                 SMLoc IDLoc, MCStreamer &Out,
3080                                 const MCSubtargetInfo *STI) {
3081 
3082   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
3083   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() &&
3084          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
3085 
3086   unsigned FirstReg = Inst.getOperand(0).getReg();
3087   unsigned SecondReg = Inst.getOperand(1).getReg();
3088   unsigned ThirdReg = Inst.getOperand(2).getReg();
3089 
3090   if (hasMips1() && !hasMips2()) {
3091     unsigned ATReg = getATReg(IDLoc);
3092     if (!ATReg)
3093       return true;
3094     emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, Out, STI);
3095     emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, Out, STI);
3096     createNop(false, IDLoc, Out, STI);
3097     emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, Out, STI);
3098     emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, Out, STI);
3099     emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, Out, STI);
3100     createNop(false, IDLoc, Out, STI);
3101     emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32)
3102                     : Mips::CVT_W_S,
3103            FirstReg, SecondReg, IDLoc, Out, STI);
3104     emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, Out, STI);
3105     createNop(false, IDLoc, Out, STI);
3106     return false;
3107   }
3108 
3109   emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32)
3110                   : Mips::TRUNC_W_S,
3111          FirstReg, SecondReg, IDLoc, Out, STI);
3112 
3113   return false;
3114 }
3115 
3116 bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
3117                               MCStreamer &Out, const MCSubtargetInfo *STI) {
3118   if (hasMips32r6() || hasMips64r6()) {
3119     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3120     return false;
3121   }
3122 
3123   warnIfNoMacro(IDLoc);
3124 
3125   const MCOperand &DstRegOp = Inst.getOperand(0);
3126   assert(DstRegOp.isReg() && "expected register operand kind");
3127 
3128   const MCOperand &SrcRegOp = Inst.getOperand(1);
3129   assert(SrcRegOp.isReg() && "expected register operand kind");
3130 
3131   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3132   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3133 
3134   unsigned DstReg = DstRegOp.getReg();
3135   unsigned SrcReg = SrcRegOp.getReg();
3136   int64_t OffsetValue = OffsetImmOp.getImm();
3137 
3138   // NOTE: We always need AT for ULHU, as it is always used as the source
3139   // register for one of the LBu's.
3140   unsigned ATReg = getATReg(IDLoc);
3141   if (!ATReg)
3142     return true;
3143 
3144   // When the value of offset+1 does not fit in 16 bits, we have to load the
3145   // offset in AT, (D)ADDu the original source register (if there was one), and
3146   // then use AT as the source register for the 2 generated LBu's.
3147   bool LoadedOffsetInAT = false;
3148   if (!isInt<16>(OffsetValue + 1) || !isInt<16>(OffsetValue)) {
3149     LoadedOffsetInAT = true;
3150 
3151     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3152                       true, IDLoc, Out, STI))
3153       return true;
3154 
3155     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3156     // because it will make our output more similar to GAS'. For example,
3157     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3158     // instead of just an "ori $1, $9, 32768".
3159     // NOTE: If there is no source register specified in the ULHU, the parser
3160     // will interpret it as $0.
3161     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3162       createAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), Out, STI);
3163   }
3164 
3165   unsigned FirstLbuDstReg = LoadedOffsetInAT ? DstReg : ATReg;
3166   unsigned SecondLbuDstReg = LoadedOffsetInAT ? ATReg : DstReg;
3167   unsigned LbuSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3168 
3169   int64_t FirstLbuOffset = 0, SecondLbuOffset = 0;
3170   if (isLittle()) {
3171     FirstLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3172     SecondLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3173   } else {
3174     FirstLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3175     SecondLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3176   }
3177 
3178   unsigned SllReg = LoadedOffsetInAT ? DstReg : ATReg;
3179 
3180   emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg,
3181           FirstLbuOffset, IDLoc, Out, STI);
3182 
3183   emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondLbuOffset, IDLoc, Out,
3184           STI);
3185 
3186   emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, Out, STI);
3187 
3188   emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, Out, STI);
3189 
3190   return false;
3191 }
3192 
3193 bool MipsAsmParser::expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3194                               const MCSubtargetInfo *STI) {
3195   if (hasMips32r6() || hasMips64r6()) {
3196     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3197     return false;
3198   }
3199 
3200   const MCOperand &DstRegOp = Inst.getOperand(0);
3201   assert(DstRegOp.isReg() && "expected register operand kind");
3202 
3203   const MCOperand &SrcRegOp = Inst.getOperand(1);
3204   assert(SrcRegOp.isReg() && "expected register operand kind");
3205 
3206   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3207   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3208 
3209   unsigned SrcReg = SrcRegOp.getReg();
3210   int64_t OffsetValue = OffsetImmOp.getImm();
3211   unsigned ATReg = 0;
3212 
3213   // When the value of offset+3 does not fit in 16 bits, we have to load the
3214   // offset in AT, (D)ADDu the original source register (if there was one), and
3215   // then use AT as the source register for the generated LWL and LWR.
3216   bool LoadedOffsetInAT = false;
3217   if (!isInt<16>(OffsetValue + 3) || !isInt<16>(OffsetValue)) {
3218     ATReg = getATReg(IDLoc);
3219     if (!ATReg)
3220       return true;
3221     LoadedOffsetInAT = true;
3222 
3223     warnIfNoMacro(IDLoc);
3224 
3225     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3226                       true, IDLoc, Out, STI))
3227       return true;
3228 
3229     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3230     // because it will make our output more similar to GAS'. For example,
3231     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3232     // instead of just an "ori $1, $9, 32768".
3233     // NOTE: If there is no source register specified in the ULW, the parser
3234     // will interpret it as $0.
3235     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3236       createAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), Out, STI);
3237   }
3238 
3239   unsigned FinalSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3240   int64_t LeftLoadOffset = 0, RightLoadOffset  = 0;
3241   if (isLittle()) {
3242     LeftLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3243     RightLoadOffset  = LoadedOffsetInAT ? 0 : OffsetValue;
3244   } else {
3245     LeftLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3246     RightLoadOffset  = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3247   }
3248 
3249   emitRRI(Mips::LWL, DstRegOp.getReg(), FinalSrcReg, LeftLoadOffset, IDLoc, Out,
3250           STI);
3251 
3252   emitRRI(Mips::LWR, DstRegOp.getReg(), FinalSrcReg, RightLoadOffset, IDLoc,
3253           Out, STI);
3254 
3255   return false;
3256 }
3257 
3258 bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
3259                                          MCStreamer &Out,
3260                                          const MCSubtargetInfo *STI) {
3261 
3262   assert (Inst.getNumOperands() == 3 && "Invalid operand count");
3263   assert (Inst.getOperand(0).isReg() &&
3264           Inst.getOperand(1).isReg() &&
3265           Inst.getOperand(2).isImm() && "Invalid instruction operand.");
3266 
3267   unsigned ATReg = Mips::NoRegister;
3268   unsigned FinalDstReg = Mips::NoRegister;
3269   unsigned DstReg = Inst.getOperand(0).getReg();
3270   unsigned SrcReg = Inst.getOperand(1).getReg();
3271   int64_t ImmValue = Inst.getOperand(2).getImm();
3272 
3273   bool Is32Bit = isInt<32>(ImmValue) || isUInt<32>(ImmValue);
3274 
3275   unsigned FinalOpcode = Inst.getOpcode();
3276 
3277   if (DstReg == SrcReg) {
3278     ATReg = getATReg(Inst.getLoc());
3279     if (!ATReg)
3280       return true;
3281     FinalDstReg = DstReg;
3282     DstReg = ATReg;
3283   }
3284 
3285   if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false, Inst.getLoc(), Out, STI)) {
3286     switch (FinalOpcode) {
3287     default:
3288       llvm_unreachable("unimplemented expansion");
3289     case (Mips::ADDi):
3290       FinalOpcode = Mips::ADD;
3291       break;
3292     case (Mips::ADDiu):
3293       FinalOpcode = Mips::ADDu;
3294       break;
3295     case (Mips::ANDi):
3296       FinalOpcode = Mips::AND;
3297       break;
3298     case (Mips::NORImm):
3299       FinalOpcode = Mips::NOR;
3300       break;
3301     case (Mips::ORi):
3302       FinalOpcode = Mips::OR;
3303       break;
3304     case (Mips::SLTi):
3305       FinalOpcode = Mips::SLT;
3306       break;
3307     case (Mips::SLTiu):
3308       FinalOpcode = Mips::SLTu;
3309       break;
3310     case (Mips::XORi):
3311       FinalOpcode = Mips::XOR;
3312       break;
3313     }
3314 
3315     if (FinalDstReg == Mips::NoRegister)
3316       emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, Out, STI);
3317     else
3318       emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc, Out, STI);
3319     return false;
3320   }
3321   return true;
3322 }
3323 
3324 bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3325                                    const MCSubtargetInfo *STI) {
3326   unsigned ATReg = Mips::NoRegister;
3327   unsigned DReg = Inst.getOperand(0).getReg();
3328   unsigned SReg = Inst.getOperand(1).getReg();
3329   unsigned TReg = Inst.getOperand(2).getReg();
3330   unsigned TmpReg = DReg;
3331 
3332   unsigned FirstShift = Mips::NOP;
3333   unsigned SecondShift = Mips::NOP;
3334 
3335   if (hasMips32r2()) {
3336 
3337     if (DReg == SReg) {
3338       TmpReg = getATReg(Inst.getLoc());
3339       if (!TmpReg)
3340         return true;
3341     }
3342 
3343     if (Inst.getOpcode() == Mips::ROL) {
3344       emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), Out, STI);
3345       emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), Out, STI);
3346       return false;
3347     }
3348 
3349     if (Inst.getOpcode() == Mips::ROR) {
3350       emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), Out, STI);
3351       return false;
3352     }
3353 
3354     return true;
3355   }
3356 
3357   if (hasMips32()) {
3358 
3359     switch (Inst.getOpcode()) {
3360     default:
3361       llvm_unreachable("unexpected instruction opcode");
3362     case Mips::ROL:
3363       FirstShift = Mips::SRLV;
3364       SecondShift = Mips::SLLV;
3365       break;
3366     case Mips::ROR:
3367       FirstShift = Mips::SLLV;
3368       SecondShift = Mips::SRLV;
3369       break;
3370     }
3371 
3372     ATReg = getATReg(Inst.getLoc());
3373     if (!ATReg)
3374       return true;
3375 
3376     emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), Out, STI);
3377     emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), Out, STI);
3378     emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), Out, STI);
3379     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Out, STI);
3380 
3381     return false;
3382   }
3383 
3384   return true;
3385 }
3386 
3387 bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc,
3388                                       MCStreamer &Out,
3389                                       const MCSubtargetInfo *STI) {
3390 
3391   unsigned ATReg = Mips::NoRegister;
3392   unsigned DReg = Inst.getOperand(0).getReg();
3393   unsigned SReg = Inst.getOperand(1).getReg();
3394   int64_t ImmValue = Inst.getOperand(2).getImm();
3395 
3396   unsigned FirstShift = Mips::NOP;
3397   unsigned SecondShift = Mips::NOP;
3398 
3399   if (hasMips32r2()) {
3400 
3401     if (Inst.getOpcode() == Mips::ROLImm) {
3402       uint64_t MaxShift = 32;
3403       uint64_t ShiftValue = ImmValue;
3404       if (ImmValue != 0)
3405         ShiftValue = MaxShift - ImmValue;
3406       emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), Out, STI);
3407       return false;
3408     }
3409 
3410     if (Inst.getOpcode() == Mips::RORImm) {
3411       emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), Out, STI);
3412       return false;
3413     }
3414 
3415     return true;
3416   }
3417 
3418   if (hasMips32()) {
3419 
3420     if (ImmValue == 0) {
3421       emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), Out, STI);
3422       return false;
3423     }
3424 
3425     switch (Inst.getOpcode()) {
3426     default:
3427       llvm_unreachable("unexpected instruction opcode");
3428     case Mips::ROLImm:
3429       FirstShift = Mips::SLL;
3430       SecondShift = Mips::SRL;
3431       break;
3432     case Mips::RORImm:
3433       FirstShift = Mips::SRL;
3434       SecondShift = Mips::SLL;
3435       break;
3436     }
3437 
3438     ATReg = getATReg(Inst.getLoc());
3439     if (!ATReg)
3440       return true;
3441 
3442     emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), Out, STI);
3443     emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), Out, STI);
3444     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Out, STI);
3445 
3446     return false;
3447   }
3448 
3449   return true;
3450 }
3451 
3452 bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3453                                     const MCSubtargetInfo *STI) {
3454 
3455   unsigned ATReg = Mips::NoRegister;
3456   unsigned DReg = Inst.getOperand(0).getReg();
3457   unsigned SReg = Inst.getOperand(1).getReg();
3458   unsigned TReg = Inst.getOperand(2).getReg();
3459   unsigned TmpReg = DReg;
3460 
3461   unsigned FirstShift = Mips::NOP;
3462   unsigned SecondShift = Mips::NOP;
3463 
3464   if (hasMips64r2()) {
3465 
3466     if (TmpReg == SReg) {
3467       TmpReg = getATReg(Inst.getLoc());
3468       if (!TmpReg)
3469         return true;
3470     }
3471 
3472     if (Inst.getOpcode() == Mips::DROL) {
3473       emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), Out, STI);
3474       emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), Out, STI);
3475       return false;
3476     }
3477 
3478     if (Inst.getOpcode() == Mips::DROR) {
3479       emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), Out, STI);
3480       return false;
3481     }
3482 
3483     return true;
3484   }
3485 
3486   if (hasMips64()) {
3487 
3488     switch (Inst.getOpcode()) {
3489     default:
3490       llvm_unreachable("unexpected instruction opcode");
3491     case Mips::DROL:
3492       FirstShift = Mips::DSRLV;
3493       SecondShift = Mips::DSLLV;
3494       break;
3495     case Mips::DROR:
3496       FirstShift = Mips::DSLLV;
3497       SecondShift = Mips::DSRLV;
3498       break;
3499     }
3500 
3501     ATReg = getATReg(Inst.getLoc());
3502     if (!ATReg)
3503       return true;
3504 
3505     emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), Out, STI);
3506     emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), Out, STI);
3507     emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), Out, STI);
3508     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Out, STI);
3509 
3510     return false;
3511   }
3512 
3513   return true;
3514 }
3515 
3516 bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
3517                                        MCStreamer &Out,
3518                                        const MCSubtargetInfo *STI) {
3519 
3520   unsigned ATReg = Mips::NoRegister;
3521   unsigned DReg = Inst.getOperand(0).getReg();
3522   unsigned SReg = Inst.getOperand(1).getReg();
3523   int64_t ImmValue = Inst.getOperand(2).getImm() % 64;
3524 
3525   unsigned FirstShift = Mips::NOP;
3526   unsigned SecondShift = Mips::NOP;
3527 
3528   MCInst TmpInst;
3529 
3530   if (hasMips64r2()) {
3531 
3532     unsigned FinalOpcode = Mips::NOP;
3533     if (ImmValue == 0)
3534       FinalOpcode = Mips::DROTR;
3535     else if (ImmValue % 32 == 0)
3536       FinalOpcode = Mips::DROTR32;
3537     else if ((ImmValue >= 1) && (ImmValue <= 32)) {
3538       if (Inst.getOpcode() == Mips::DROLImm)
3539         FinalOpcode = Mips::DROTR32;
3540       else
3541         FinalOpcode = Mips::DROTR;
3542     } else if (ImmValue >= 33) {
3543       if (Inst.getOpcode() == Mips::DROLImm)
3544         FinalOpcode = Mips::DROTR;
3545       else
3546         FinalOpcode = Mips::DROTR32;
3547     }
3548 
3549     uint64_t ShiftValue = ImmValue % 32;
3550     if (Inst.getOpcode() == Mips::DROLImm)
3551       ShiftValue = (32 - ImmValue % 32) % 32;
3552 
3553     emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), Out, STI);
3554 
3555     return false;
3556   }
3557 
3558   if (hasMips64()) {
3559 
3560     if (ImmValue == 0) {
3561       emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), Out, STI);
3562       return false;
3563     }
3564 
3565     switch (Inst.getOpcode()) {
3566     default:
3567       llvm_unreachable("unexpected instruction opcode");
3568     case Mips::DROLImm:
3569       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3570         FirstShift = Mips::DSLL;
3571         SecondShift = Mips::DSRL32;
3572       }
3573       if (ImmValue == 32) {
3574         FirstShift = Mips::DSLL32;
3575         SecondShift = Mips::DSRL32;
3576       }
3577       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3578         FirstShift = Mips::DSLL32;
3579         SecondShift = Mips::DSRL;
3580       }
3581       break;
3582     case Mips::DRORImm:
3583       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3584         FirstShift = Mips::DSRL;
3585         SecondShift = Mips::DSLL32;
3586       }
3587       if (ImmValue == 32) {
3588         FirstShift = Mips::DSRL32;
3589         SecondShift = Mips::DSLL32;
3590       }
3591       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3592         FirstShift = Mips::DSRL32;
3593         SecondShift = Mips::DSLL;
3594       }
3595       break;
3596     }
3597 
3598     ATReg = getATReg(Inst.getLoc());
3599     if (!ATReg)
3600       return true;
3601 
3602     emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), Out, STI);
3603     emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32, Inst.getLoc(), Out, STI);
3604     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Out, STI);
3605 
3606     return false;
3607   }
3608 
3609   return true;
3610 }
3611 
3612 bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3613                               const MCSubtargetInfo *STI) {
3614 
3615   unsigned FirstRegOp = Inst.getOperand(0).getReg();
3616   unsigned SecondRegOp = Inst.getOperand(1).getReg();
3617 
3618   emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, Out, STI);
3619   if (FirstRegOp != SecondRegOp)
3620     emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, Out, STI);
3621   else
3622     createNop(false, IDLoc, Out, STI);
3623   emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, Out, STI);
3624 
3625   return false;
3626 }
3627 
3628 void MipsAsmParser::createNop(bool hasShortDelaySlot, SMLoc IDLoc,
3629                               MCStreamer &Out, const MCSubtargetInfo *STI) {
3630   if (hasShortDelaySlot)
3631     emitRR(Mips::MOVE16_MM, Mips::ZERO, Mips::ZERO, IDLoc, Out, STI);
3632   else
3633     emitRRI(Mips::SLL, Mips::ZERO, Mips::ZERO, 0, IDLoc, Out, STI);
3634 }
3635 
3636 void MipsAsmParser::createAddu(unsigned DstReg, unsigned SrcReg,
3637                                unsigned TrgReg, bool Is64Bit, MCStreamer &Out,
3638                                const MCSubtargetInfo *STI) {
3639   emitRRR(Is64Bit ? Mips::DADDu : Mips::ADDu, DstReg, SrcReg, TrgReg, SMLoc(),
3640           Out, STI);
3641 }
3642 
3643 void MipsAsmParser::createCpRestoreMemOp(bool IsLoad, int StackOffset,
3644                                          SMLoc IDLoc, MCStreamer &Out,
3645                                          const MCSubtargetInfo *STI) {
3646   // If the offset can not fit into 16 bits, we need to expand.
3647   if (!isInt<16>(StackOffset)) {
3648     MCInst MemInst;
3649     MemInst.setOpcode(IsLoad ? Mips::LW : Mips::SW);
3650     MemInst.addOperand(MCOperand::createReg(Mips::GP));
3651     MemInst.addOperand(MCOperand::createReg(Mips::SP));
3652     MemInst.addOperand(MCOperand::createImm(StackOffset));
3653     expandMemInst(MemInst, IDLoc, Out, STI, IsLoad, true /*HasImmOpnd*/);
3654     return;
3655   }
3656 
3657   emitRRI(IsLoad ? Mips::LW : Mips::SW, Mips::GP, Mips::SP, StackOffset, IDLoc,
3658           Out, STI);
3659 }
3660 
3661 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3662   // As described by the Mips32r2 spec, the registers Rd and Rs for
3663   // jalr.hb must be different.
3664   // It also applies for registers Rt and Rs of microMIPSr6 jalrc.hb instruction
3665   unsigned Opcode = Inst.getOpcode();
3666 
3667   if ((Opcode == Mips::JALR_HB || Opcode == Mips::JALRC_HB_MMR6) &&
3668       (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()))
3669     return Match_RequiresDifferentSrcAndDst;
3670 
3671   return Match_Success;
3672 }
3673 
3674 static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands,
3675                             uint64_t ErrorInfo) {
3676   if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) {
3677     SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3678     if (ErrorLoc == SMLoc())
3679       return Loc;
3680     return ErrorLoc;
3681   }
3682   return Loc;
3683 }
3684 
3685 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3686                                             OperandVector &Operands,
3687                                             MCStreamer &Out,
3688                                             uint64_t &ErrorInfo,
3689                                             bool MatchingInlineAsm) {
3690 
3691   MCInst Inst;
3692   unsigned MatchResult =
3693       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
3694 
3695   switch (MatchResult) {
3696   case Match_Success: {
3697     if (processInstruction(Inst, IDLoc, Out, STI))
3698       return true;
3699     return false;
3700   }
3701   case Match_MissingFeature:
3702     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3703     return true;
3704   case Match_InvalidOperand: {
3705     SMLoc ErrorLoc = IDLoc;
3706     if (ErrorInfo != ~0ULL) {
3707       if (ErrorInfo >= Operands.size())
3708         return Error(IDLoc, "too few operands for instruction");
3709 
3710       ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3711       if (ErrorLoc == SMLoc())
3712         ErrorLoc = IDLoc;
3713     }
3714 
3715     return Error(ErrorLoc, "invalid operand for instruction");
3716   }
3717   case Match_MnemonicFail:
3718     return Error(IDLoc, "invalid instruction");
3719   case Match_RequiresDifferentSrcAndDst:
3720     return Error(IDLoc, "source and destination must be different");
3721   case Match_Immz:
3722     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'");
3723   case Match_UImm1_0:
3724     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3725                  "expected 1-bit unsigned immediate");
3726   case Match_UImm2_0:
3727     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3728                  "expected 2-bit unsigned immediate");
3729   case Match_UImm2_1:
3730     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3731                  "expected immediate in range 1 .. 4");
3732   case Match_UImm3_0:
3733     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3734                  "expected 3-bit unsigned immediate");
3735   case Match_UImm4_0:
3736     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3737                  "expected 4-bit unsigned immediate");
3738   case Match_SImm4_0:
3739     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3740                  "expected 4-bit signed immediate");
3741   case Match_UImm5_0:
3742     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3743                  "expected 5-bit unsigned immediate");
3744   case Match_SImm5_0:
3745     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3746                  "expected 5-bit signed immediate");
3747   case Match_UImm5_1:
3748     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3749                  "expected immediate in range 1 .. 32");
3750   case Match_UImm5_32:
3751     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3752                  "expected immediate in range 32 .. 63");
3753   case Match_UImm5_33:
3754     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3755                  "expected immediate in range 33 .. 64");
3756   case Match_UImm5_0_Report_UImm6:
3757     // This is used on UImm5 operands that have a corresponding UImm5_32
3758     // operand to avoid confusing the user.
3759     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3760                  "expected 6-bit unsigned immediate");
3761   case Match_UImm5_Lsl2:
3762     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3763                  "expected both 7-bit unsigned immediate and multiple of 4");
3764   case Match_UImmRange2_64:
3765     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3766                  "expected immediate in range 2 .. 64");
3767   case Match_UImm6_0:
3768     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3769                  "expected 6-bit unsigned immediate");
3770   case Match_UImm6_Lsl2:
3771     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3772                  "expected both 8-bit unsigned immediate and multiple of 4");
3773   case Match_SImm6_0:
3774     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3775                  "expected 6-bit signed immediate");
3776   case Match_UImm7_0:
3777     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3778                  "expected 7-bit unsigned immediate");
3779   case Match_UImm7_N1:
3780     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3781                  "expected immediate in range -1 .. 126");
3782   case Match_SImm7_Lsl2:
3783     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3784                  "expected both 9-bit signed immediate and multiple of 4");
3785   case Match_UImm8_0:
3786     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3787                  "expected 8-bit unsigned immediate");
3788   case Match_UImm10_0:
3789     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3790                  "expected 10-bit unsigned immediate");
3791   case Match_SImm10_0:
3792     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3793                  "expected 10-bit signed immediate");
3794   case Match_SImm11_0:
3795     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3796                  "expected 11-bit signed immediate");
3797   case Match_UImm16:
3798   case Match_UImm16_Relaxed:
3799     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3800                  "expected 16-bit unsigned immediate");
3801   case Match_SImm16:
3802   case Match_SImm16_Relaxed:
3803     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3804                  "expected 16-bit signed immediate");
3805   case Match_UImm20_0:
3806     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3807                  "expected 20-bit unsigned immediate");
3808   case Match_UImm26_0:
3809     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3810                  "expected 26-bit unsigned immediate");
3811   case Match_SImm32:
3812   case Match_SImm32_Relaxed:
3813     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3814                  "expected 32-bit signed immediate");
3815   case Match_MemSImm9:
3816     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3817                  "expected memory with 9-bit signed offset");
3818   case Match_MemGPSImm9:
3819     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3820                  "expected memory with $gp and 9-bit signed offset");
3821   case Match_MemSImm10:
3822     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3823                  "expected memory with 10-bit signed offset");
3824   case Match_MemSImm10Lsl1:
3825     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3826                  "expected memory with 11-bit signed offset and multiple of 2");
3827   case Match_MemSImm10Lsl2:
3828     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3829                  "expected memory with 12-bit signed offset and multiple of 4");
3830   case Match_MemSImm10Lsl3:
3831     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3832                  "expected memory with 13-bit signed offset and multiple of 8");
3833   case Match_MemSImm11:
3834     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3835                  "expected memory with 11-bit signed offset");
3836   case Match_MemSImm16:
3837     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3838                  "expected memory with 16-bit signed offset");
3839   }
3840 
3841   llvm_unreachable("Implement any new match types added!");
3842 }
3843 
3844 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
3845   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
3846     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
3847                      ") without \".set noat\"");
3848 }
3849 
3850 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
3851   if (!AssemblerOptions.back()->isMacro())
3852     Warning(Loc, "macro instruction expanded into multiple instructions");
3853 }
3854 
3855 void
3856 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
3857                                      SMRange Range, bool ShowColors) {
3858   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
3859                                   Range, SMFixIt(Range, FixMsg),
3860                                   ShowColors);
3861 }
3862 
3863 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
3864   int CC;
3865 
3866   CC = StringSwitch<unsigned>(Name)
3867            .Case("zero", 0)
3868            .Case("at", 1)
3869            .Case("a0", 4)
3870            .Case("a1", 5)
3871            .Case("a2", 6)
3872            .Case("a3", 7)
3873            .Case("v0", 2)
3874            .Case("v1", 3)
3875            .Case("s0", 16)
3876            .Case("s1", 17)
3877            .Case("s2", 18)
3878            .Case("s3", 19)
3879            .Case("s4", 20)
3880            .Case("s5", 21)
3881            .Case("s6", 22)
3882            .Case("s7", 23)
3883            .Case("k0", 26)
3884            .Case("k1", 27)
3885            .Case("gp", 28)
3886            .Case("sp", 29)
3887            .Case("fp", 30)
3888            .Case("s8", 30)
3889            .Case("ra", 31)
3890            .Case("t0", 8)
3891            .Case("t1", 9)
3892            .Case("t2", 10)
3893            .Case("t3", 11)
3894            .Case("t4", 12)
3895            .Case("t5", 13)
3896            .Case("t6", 14)
3897            .Case("t7", 15)
3898            .Case("t8", 24)
3899            .Case("t9", 25)
3900            .Default(-1);
3901 
3902   if (!(isABI_N32() || isABI_N64()))
3903     return CC;
3904 
3905   if (12 <= CC && CC <= 15) {
3906     // Name is one of t4-t7
3907     AsmToken RegTok = getLexer().peekTok();
3908     SMRange RegRange = RegTok.getLocRange();
3909 
3910     StringRef FixedName = StringSwitch<StringRef>(Name)
3911                               .Case("t4", "t0")
3912                               .Case("t5", "t1")
3913                               .Case("t6", "t2")
3914                               .Case("t7", "t3")
3915                               .Default("");
3916     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
3917 
3918     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
3919                           "Did you mean $" + FixedName + "?", RegRange);
3920   }
3921 
3922   // Although SGI documentation just cuts out t0-t3 for n32/n64,
3923   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
3924   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
3925   if (8 <= CC && CC <= 11)
3926     CC += 4;
3927 
3928   if (CC == -1)
3929     CC = StringSwitch<unsigned>(Name)
3930              .Case("a4", 8)
3931              .Case("a5", 9)
3932              .Case("a6", 10)
3933              .Case("a7", 11)
3934              .Case("kt0", 26)
3935              .Case("kt1", 27)
3936              .Default(-1);
3937 
3938   return CC;
3939 }
3940 
3941 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
3942   int CC;
3943 
3944   CC = StringSwitch<unsigned>(Name)
3945             .Case("hwr_cpunum", 0)
3946             .Case("hwr_synci_step", 1)
3947             .Case("hwr_cc", 2)
3948             .Case("hwr_ccres", 3)
3949             .Case("hwr_ulr", 29)
3950             .Default(-1);
3951 
3952   return CC;
3953 }
3954 
3955 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
3956 
3957   if (Name[0] == 'f') {
3958     StringRef NumString = Name.substr(1);
3959     unsigned IntVal;
3960     if (NumString.getAsInteger(10, IntVal))
3961       return -1;     // This is not an integer.
3962     if (IntVal > 31) // Maximum index for fpu register.
3963       return -1;
3964     return IntVal;
3965   }
3966   return -1;
3967 }
3968 
3969 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
3970 
3971   if (Name.startswith("fcc")) {
3972     StringRef NumString = Name.substr(3);
3973     unsigned IntVal;
3974     if (NumString.getAsInteger(10, IntVal))
3975       return -1;    // This is not an integer.
3976     if (IntVal > 7) // There are only 8 fcc registers.
3977       return -1;
3978     return IntVal;
3979   }
3980   return -1;
3981 }
3982 
3983 int MipsAsmParser::matchACRegisterName(StringRef Name) {
3984 
3985   if (Name.startswith("ac")) {
3986     StringRef NumString = Name.substr(2);
3987     unsigned IntVal;
3988     if (NumString.getAsInteger(10, IntVal))
3989       return -1;    // This is not an integer.
3990     if (IntVal > 3) // There are only 3 acc registers.
3991       return -1;
3992     return IntVal;
3993   }
3994   return -1;
3995 }
3996 
3997 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
3998   unsigned IntVal;
3999 
4000   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
4001     return -1;
4002 
4003   if (IntVal > 31)
4004     return -1;
4005 
4006   return IntVal;
4007 }
4008 
4009 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
4010   int CC;
4011 
4012   CC = StringSwitch<unsigned>(Name)
4013            .Case("msair", 0)
4014            .Case("msacsr", 1)
4015            .Case("msaaccess", 2)
4016            .Case("msasave", 3)
4017            .Case("msamodify", 4)
4018            .Case("msarequest", 5)
4019            .Case("msamap", 6)
4020            .Case("msaunmap", 7)
4021            .Default(-1);
4022 
4023   return CC;
4024 }
4025 
4026 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
4027   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
4028   if (ATIndex == 0) {
4029     reportParseError(Loc,
4030                      "pseudo-instruction requires $at, which is not available");
4031     return 0;
4032   }
4033   unsigned AT = getReg(
4034       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
4035   return AT;
4036 }
4037 
4038 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
4039   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
4040 }
4041 
4042 unsigned MipsAsmParser::getGPR(int RegNo) {
4043   return getReg(isGP64bit() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
4044                 RegNo);
4045 }
4046 
4047 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
4048   if (RegNum >
4049       getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
4050     return -1;
4051 
4052   return getReg(RegClass, RegNum);
4053 }
4054 
4055 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
4056   MCAsmParser &Parser = getParser();
4057   DEBUG(dbgs() << "parseOperand\n");
4058 
4059   // Check if the current operand has a custom associated parser, if so, try to
4060   // custom parse the operand, or fallback to the general approach.
4061   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
4062   if (ResTy == MatchOperand_Success)
4063     return false;
4064   // If there wasn't a custom match, try the generic matcher below. Otherwise,
4065   // there was a match, but an error occurred, in which case, just return that
4066   // the operand parsing failed.
4067   if (ResTy == MatchOperand_ParseFail)
4068     return true;
4069 
4070   DEBUG(dbgs() << ".. Generic Parser\n");
4071 
4072   switch (getLexer().getKind()) {
4073   default:
4074     Error(Parser.getTok().getLoc(), "unexpected token in operand");
4075     return true;
4076   case AsmToken::Dollar: {
4077     // Parse the register.
4078     SMLoc S = Parser.getTok().getLoc();
4079 
4080     // Almost all registers have been parsed by custom parsers. There is only
4081     // one exception to this. $zero (and it's alias $0) will reach this point
4082     // for div, divu, and similar instructions because it is not an operand
4083     // to the instruction definition but an explicit register. Special case
4084     // this situation for now.
4085     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
4086       return false;
4087 
4088     // Maybe it is a symbol reference.
4089     StringRef Identifier;
4090     if (Parser.parseIdentifier(Identifier))
4091       return true;
4092 
4093     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4094     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
4095     // Otherwise create a symbol reference.
4096     const MCExpr *Res =
4097         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
4098 
4099     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
4100     return false;
4101   }
4102   // Else drop to expression parsing.
4103   case AsmToken::LParen:
4104   case AsmToken::Minus:
4105   case AsmToken::Plus:
4106   case AsmToken::Integer:
4107   case AsmToken::Tilde:
4108   case AsmToken::String: {
4109     DEBUG(dbgs() << ".. generic integer\n");
4110     OperandMatchResultTy ResTy = parseImm(Operands);
4111     return ResTy != MatchOperand_Success;
4112   }
4113   case AsmToken::Percent: {
4114     // It is a symbol reference or constant expression.
4115     const MCExpr *IdVal;
4116     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
4117     if (parseRelocOperand(IdVal))
4118       return true;
4119 
4120     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4121 
4122     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4123     return false;
4124   } // case AsmToken::Percent
4125   } // switch(getLexer().getKind())
4126   return true;
4127 }
4128 
4129 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
4130                                                StringRef RelocStr) {
4131   const MCExpr *Res;
4132   // Check the type of the expression.
4133   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
4134     // It's a constant, evaluate reloc value.
4135     int16_t Val;
4136     switch (getVariantKind(RelocStr)) {
4137     case MCSymbolRefExpr::VK_Mips_ABS_LO:
4138       // Get the 1st 16-bits.
4139       Val = MCE->getValue() & 0xffff;
4140       break;
4141     case MCSymbolRefExpr::VK_Mips_ABS_HI:
4142     case MCSymbolRefExpr::VK_Mips_GOT:
4143       // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
4144       // 16 bits being negative.
4145       Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
4146       break;
4147     case MCSymbolRefExpr::VK_Mips_HIGHER:
4148       // Get the 3rd 16-bits.
4149       Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
4150       break;
4151     case MCSymbolRefExpr::VK_Mips_HIGHEST:
4152       // Get the 4th 16-bits.
4153       Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
4154       break;
4155     default:
4156       report_fatal_error("unsupported reloc value");
4157     }
4158     return MCConstantExpr::create(Val, getContext());
4159   }
4160 
4161   if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
4162     // It's a symbol, create a symbolic expression from the symbol.
4163     const MCSymbol *Symbol = &MSRE->getSymbol();
4164     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
4165     Res = MCSymbolRefExpr::create(Symbol, VK, getContext());
4166     return Res;
4167   }
4168 
4169   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
4170     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
4171 
4172     // Try to create target expression.
4173     if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
4174       return MipsMCExpr::create(VK, Expr, getContext());
4175 
4176     const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
4177     const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
4178     Res = MCBinaryExpr::create(BE->getOpcode(), LExp, RExp, getContext());
4179     return Res;
4180   }
4181 
4182   if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
4183     const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
4184     Res = MCUnaryExpr::create(UN->getOpcode(), UnExp, getContext());
4185     return Res;
4186   }
4187   // Just return the original expression.
4188   return Expr;
4189 }
4190 
4191 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
4192 
4193   switch (Expr->getKind()) {
4194   case MCExpr::Constant:
4195     return true;
4196   case MCExpr::SymbolRef:
4197     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
4198   case MCExpr::Binary:
4199     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
4200       if (!isEvaluated(BE->getLHS()))
4201         return false;
4202       return isEvaluated(BE->getRHS());
4203     }
4204   case MCExpr::Unary:
4205     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
4206   case MCExpr::Target:
4207     return true;
4208   }
4209   return false;
4210 }
4211 
4212 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
4213   MCAsmParser &Parser = getParser();
4214   Parser.Lex();                          // Eat the % token.
4215   const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
4216   if (Tok.isNot(AsmToken::Identifier))
4217     return true;
4218 
4219   std::string Str = Tok.getIdentifier();
4220 
4221   Parser.Lex(); // Eat the identifier.
4222   // Now make an expression from the rest of the operand.
4223   const MCExpr *IdVal;
4224   SMLoc EndLoc;
4225 
4226   if (getLexer().getKind() == AsmToken::LParen) {
4227     while (1) {
4228       Parser.Lex(); // Eat the '(' token.
4229       if (getLexer().getKind() == AsmToken::Percent) {
4230         Parser.Lex(); // Eat the % token.
4231         const AsmToken &nextTok = Parser.getTok();
4232         if (nextTok.isNot(AsmToken::Identifier))
4233           return true;
4234         Str += "(%";
4235         Str += nextTok.getIdentifier();
4236         Parser.Lex(); // Eat the identifier.
4237         if (getLexer().getKind() != AsmToken::LParen)
4238           return true;
4239       } else
4240         break;
4241     }
4242     if (getParser().parseParenExpression(IdVal, EndLoc))
4243       return true;
4244 
4245     while (getLexer().getKind() == AsmToken::RParen)
4246       Parser.Lex(); // Eat the ')' token.
4247 
4248   } else
4249     return true; // Parenthesis must follow the relocation operand.
4250 
4251   Res = evaluateRelocExpr(IdVal, Str);
4252   return false;
4253 }
4254 
4255 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
4256                                   SMLoc &EndLoc) {
4257   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
4258   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
4259   if (ResTy == MatchOperand_Success) {
4260     assert(Operands.size() == 1);
4261     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
4262     StartLoc = Operand.getStartLoc();
4263     EndLoc = Operand.getEndLoc();
4264 
4265     // AFAIK, we only support numeric registers and named GPR's in CFI
4266     // directives.
4267     // Don't worry about eating tokens before failing. Using an unrecognised
4268     // register is a parse error.
4269     if (Operand.isGPRAsmReg()) {
4270       // Resolve to GPR32 or GPR64 appropriately.
4271       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
4272     }
4273 
4274     return (RegNo == (unsigned)-1);
4275   }
4276 
4277   assert(Operands.size() == 0);
4278   return (RegNo == (unsigned)-1);
4279 }
4280 
4281 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
4282   MCAsmParser &Parser = getParser();
4283   SMLoc S;
4284   bool Result = true;
4285   unsigned NumOfLParen = 0;
4286 
4287   while (getLexer().getKind() == AsmToken::LParen) {
4288     Parser.Lex();
4289     ++NumOfLParen;
4290   }
4291 
4292   switch (getLexer().getKind()) {
4293   default:
4294     return true;
4295   case AsmToken::Identifier:
4296   case AsmToken::LParen:
4297   case AsmToken::Integer:
4298   case AsmToken::Minus:
4299   case AsmToken::Plus:
4300     if (isParenExpr)
4301       Result = getParser().parseParenExprOfDepth(NumOfLParen, Res, S);
4302     else
4303       Result = (getParser().parseExpression(Res));
4304     while (getLexer().getKind() == AsmToken::RParen)
4305       Parser.Lex();
4306     break;
4307   case AsmToken::Percent:
4308     Result = parseRelocOperand(Res);
4309   }
4310   return Result;
4311 }
4312 
4313 MipsAsmParser::OperandMatchResultTy
4314 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
4315   MCAsmParser &Parser = getParser();
4316   DEBUG(dbgs() << "parseMemOperand\n");
4317   const MCExpr *IdVal = nullptr;
4318   SMLoc S;
4319   bool isParenExpr = false;
4320   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
4321   // First operand is the offset.
4322   S = Parser.getTok().getLoc();
4323 
4324   if (getLexer().getKind() == AsmToken::LParen) {
4325     Parser.Lex();
4326     isParenExpr = true;
4327   }
4328 
4329   if (getLexer().getKind() != AsmToken::Dollar) {
4330     if (parseMemOffset(IdVal, isParenExpr))
4331       return MatchOperand_ParseFail;
4332 
4333     const AsmToken &Tok = Parser.getTok(); // Get the next token.
4334     if (Tok.isNot(AsmToken::LParen)) {
4335       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
4336       if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") {
4337         SMLoc E =
4338             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4339         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4340         return MatchOperand_Success;
4341       }
4342       if (Tok.is(AsmToken::EndOfStatement)) {
4343         SMLoc E =
4344             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4345 
4346         // Zero register assumed, add a memory operand with ZERO as its base.
4347         // "Base" will be managed by k_Memory.
4348         auto Base = MipsOperand::createGPRReg(0, getContext().getRegisterInfo(),
4349                                               S, E, *this);
4350         Operands.push_back(
4351             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
4352         return MatchOperand_Success;
4353       }
4354       Error(Parser.getTok().getLoc(), "'(' expected");
4355       return MatchOperand_ParseFail;
4356     }
4357 
4358     Parser.Lex(); // Eat the '(' token.
4359   }
4360 
4361   Res = parseAnyRegister(Operands);
4362   if (Res != MatchOperand_Success)
4363     return Res;
4364 
4365   if (Parser.getTok().isNot(AsmToken::RParen)) {
4366     Error(Parser.getTok().getLoc(), "')' expected");
4367     return MatchOperand_ParseFail;
4368   }
4369 
4370   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4371 
4372   Parser.Lex(); // Eat the ')' token.
4373 
4374   if (!IdVal)
4375     IdVal = MCConstantExpr::create(0, getContext());
4376 
4377   // Replace the register operand with the memory operand.
4378   std::unique_ptr<MipsOperand> op(
4379       static_cast<MipsOperand *>(Operands.back().release()));
4380   // Remove the register from the operands.
4381   // "op" will be managed by k_Memory.
4382   Operands.pop_back();
4383   // Add the memory operand.
4384   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
4385     int64_t Imm;
4386     if (IdVal->evaluateAsAbsolute(Imm))
4387       IdVal = MCConstantExpr::create(Imm, getContext());
4388     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
4389       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
4390                                    getContext());
4391   }
4392 
4393   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
4394   return MatchOperand_Success;
4395 }
4396 
4397 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
4398   MCAsmParser &Parser = getParser();
4399   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
4400   if (Sym) {
4401     SMLoc S = Parser.getTok().getLoc();
4402     const MCExpr *Expr;
4403     if (Sym->isVariable())
4404       Expr = Sym->getVariableValue();
4405     else
4406       return false;
4407     if (Expr->getKind() == MCExpr::SymbolRef) {
4408       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
4409       StringRef DefSymbol = Ref->getSymbol().getName();
4410       if (DefSymbol.startswith("$")) {
4411         OperandMatchResultTy ResTy =
4412             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
4413         if (ResTy == MatchOperand_Success) {
4414           Parser.Lex();
4415           return true;
4416         } else if (ResTy == MatchOperand_ParseFail)
4417           llvm_unreachable("Should never ParseFail");
4418         return false;
4419       }
4420     } else if (Expr->getKind() == MCExpr::Constant) {
4421       Parser.Lex();
4422       const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
4423       Operands.push_back(
4424           MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
4425       return true;
4426     }
4427   }
4428   return false;
4429 }
4430 
4431 MipsAsmParser::OperandMatchResultTy
4432 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
4433                                                  StringRef Identifier,
4434                                                  SMLoc S) {
4435   int Index = matchCPURegisterName(Identifier);
4436   if (Index != -1) {
4437     Operands.push_back(MipsOperand::createGPRReg(
4438         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4439     return MatchOperand_Success;
4440   }
4441 
4442   Index = matchHWRegsRegisterName(Identifier);
4443   if (Index != -1) {
4444     Operands.push_back(MipsOperand::createHWRegsReg(
4445         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4446     return MatchOperand_Success;
4447   }
4448 
4449   Index = matchFPURegisterName(Identifier);
4450   if (Index != -1) {
4451     Operands.push_back(MipsOperand::createFGRReg(
4452         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4453     return MatchOperand_Success;
4454   }
4455 
4456   Index = matchFCCRegisterName(Identifier);
4457   if (Index != -1) {
4458     Operands.push_back(MipsOperand::createFCCReg(
4459         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4460     return MatchOperand_Success;
4461   }
4462 
4463   Index = matchACRegisterName(Identifier);
4464   if (Index != -1) {
4465     Operands.push_back(MipsOperand::createACCReg(
4466         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4467     return MatchOperand_Success;
4468   }
4469 
4470   Index = matchMSA128RegisterName(Identifier);
4471   if (Index != -1) {
4472     Operands.push_back(MipsOperand::createMSA128Reg(
4473         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4474     return MatchOperand_Success;
4475   }
4476 
4477   Index = matchMSA128CtrlRegisterName(Identifier);
4478   if (Index != -1) {
4479     Operands.push_back(MipsOperand::createMSACtrlReg(
4480         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4481     return MatchOperand_Success;
4482   }
4483 
4484   return MatchOperand_NoMatch;
4485 }
4486 
4487 MipsAsmParser::OperandMatchResultTy
4488 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
4489   MCAsmParser &Parser = getParser();
4490   auto Token = Parser.getLexer().peekTok(false);
4491 
4492   if (Token.is(AsmToken::Identifier)) {
4493     DEBUG(dbgs() << ".. identifier\n");
4494     StringRef Identifier = Token.getIdentifier();
4495     OperandMatchResultTy ResTy =
4496         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
4497     return ResTy;
4498   } else if (Token.is(AsmToken::Integer)) {
4499     DEBUG(dbgs() << ".. integer\n");
4500     Operands.push_back(MipsOperand::createNumericReg(
4501         Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
4502         *this));
4503     return MatchOperand_Success;
4504   }
4505 
4506   DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
4507 
4508   return MatchOperand_NoMatch;
4509 }
4510 
4511 MipsAsmParser::OperandMatchResultTy
4512 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
4513   MCAsmParser &Parser = getParser();
4514   DEBUG(dbgs() << "parseAnyRegister\n");
4515 
4516   auto Token = Parser.getTok();
4517 
4518   SMLoc S = Token.getLoc();
4519 
4520   if (Token.isNot(AsmToken::Dollar)) {
4521     DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
4522     if (Token.is(AsmToken::Identifier)) {
4523       if (searchSymbolAlias(Operands))
4524         return MatchOperand_Success;
4525     }
4526     DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
4527     return MatchOperand_NoMatch;
4528   }
4529   DEBUG(dbgs() << ".. $\n");
4530 
4531   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
4532   if (ResTy == MatchOperand_Success) {
4533     Parser.Lex(); // $
4534     Parser.Lex(); // identifier
4535   }
4536   return ResTy;
4537 }
4538 
4539 MipsAsmParser::OperandMatchResultTy
4540 MipsAsmParser::parseImm(OperandVector &Operands) {
4541   MCAsmParser &Parser = getParser();
4542   switch (getLexer().getKind()) {
4543   default:
4544     return MatchOperand_NoMatch;
4545   case AsmToken::LParen:
4546   case AsmToken::Minus:
4547   case AsmToken::Plus:
4548   case AsmToken::Integer:
4549   case AsmToken::Tilde:
4550   case AsmToken::String:
4551     break;
4552   }
4553 
4554   const MCExpr *IdVal;
4555   SMLoc S = Parser.getTok().getLoc();
4556   if (getParser().parseExpression(IdVal))
4557     return MatchOperand_ParseFail;
4558 
4559   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4560   Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4561   return MatchOperand_Success;
4562 }
4563 
4564 MipsAsmParser::OperandMatchResultTy
4565 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
4566   MCAsmParser &Parser = getParser();
4567   DEBUG(dbgs() << "parseJumpTarget\n");
4568 
4569   SMLoc S = getLexer().getLoc();
4570 
4571   // Integers and expressions are acceptable
4572   OperandMatchResultTy ResTy = parseImm(Operands);
4573   if (ResTy != MatchOperand_NoMatch)
4574     return ResTy;
4575 
4576   // Registers are a valid target and have priority over symbols.
4577   ResTy = parseAnyRegister(Operands);
4578   if (ResTy != MatchOperand_NoMatch)
4579     return ResTy;
4580 
4581   const MCExpr *Expr = nullptr;
4582   if (Parser.parseExpression(Expr)) {
4583     // We have no way of knowing if a symbol was consumed so we must ParseFail
4584     return MatchOperand_ParseFail;
4585   }
4586   Operands.push_back(
4587       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
4588   return MatchOperand_Success;
4589 }
4590 
4591 MipsAsmParser::OperandMatchResultTy
4592 MipsAsmParser::parseInvNum(OperandVector &Operands) {
4593   MCAsmParser &Parser = getParser();
4594   const MCExpr *IdVal;
4595   // If the first token is '$' we may have register operand.
4596   if (Parser.getTok().is(AsmToken::Dollar))
4597     return MatchOperand_NoMatch;
4598   SMLoc S = Parser.getTok().getLoc();
4599   if (getParser().parseExpression(IdVal))
4600     return MatchOperand_ParseFail;
4601   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
4602   assert(MCE && "Unexpected MCExpr type.");
4603   int64_t Val = MCE->getValue();
4604   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4605   Operands.push_back(MipsOperand::CreateImm(
4606       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
4607   return MatchOperand_Success;
4608 }
4609 
4610 MipsAsmParser::OperandMatchResultTy
4611 MipsAsmParser::parseLSAImm(OperandVector &Operands) {
4612   MCAsmParser &Parser = getParser();
4613   switch (getLexer().getKind()) {
4614   default:
4615     return MatchOperand_NoMatch;
4616   case AsmToken::LParen:
4617   case AsmToken::Plus:
4618   case AsmToken::Minus:
4619   case AsmToken::Integer:
4620     break;
4621   }
4622 
4623   const MCExpr *Expr;
4624   SMLoc S = Parser.getTok().getLoc();
4625 
4626   if (getParser().parseExpression(Expr))
4627     return MatchOperand_ParseFail;
4628 
4629   int64_t Val;
4630   if (!Expr->evaluateAsAbsolute(Val)) {
4631     Error(S, "expected immediate value");
4632     return MatchOperand_ParseFail;
4633   }
4634 
4635   // The LSA instruction allows a 2-bit unsigned immediate. For this reason
4636   // and because the CPU always adds one to the immediate field, the allowed
4637   // range becomes 1..4. We'll only check the range here and will deal
4638   // with the addition/subtraction when actually decoding/encoding
4639   // the instruction.
4640   if (Val < 1 || Val > 4) {
4641     Error(S, "immediate not in range (1..4)");
4642     return MatchOperand_ParseFail;
4643   }
4644 
4645   Operands.push_back(
4646       MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
4647   return MatchOperand_Success;
4648 }
4649 
4650 MipsAsmParser::OperandMatchResultTy
4651 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
4652   MCAsmParser &Parser = getParser();
4653   SmallVector<unsigned, 10> Regs;
4654   unsigned RegNo;
4655   unsigned PrevReg = Mips::NoRegister;
4656   bool RegRange = false;
4657   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4658 
4659   if (Parser.getTok().isNot(AsmToken::Dollar))
4660     return MatchOperand_ParseFail;
4661 
4662   SMLoc S = Parser.getTok().getLoc();
4663   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
4664     SMLoc E = getLexer().getLoc();
4665     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
4666     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
4667     if (RegRange) {
4668       // Remove last register operand because registers from register range
4669       // should be inserted first.
4670       if ((isGP64bit() && RegNo == Mips::RA_64) ||
4671           (!isGP64bit() && RegNo == Mips::RA)) {
4672         Regs.push_back(RegNo);
4673       } else {
4674         unsigned TmpReg = PrevReg + 1;
4675         while (TmpReg <= RegNo) {
4676           if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) ||
4677               (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) &&
4678                isGP64bit())) {
4679             Error(E, "invalid register operand");
4680             return MatchOperand_ParseFail;
4681           }
4682 
4683           PrevReg = TmpReg;
4684           Regs.push_back(TmpReg++);
4685         }
4686       }
4687 
4688       RegRange = false;
4689     } else {
4690       if ((PrevReg == Mips::NoRegister) &&
4691           ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) ||
4692           (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) {
4693         Error(E, "$16 or $31 expected");
4694         return MatchOperand_ParseFail;
4695       } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA ||
4696                     (RegNo >= Mips::S0 && RegNo <= Mips::S7)) &&
4697                     !isGP64bit()) ||
4698                    ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 ||
4699                     (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) &&
4700                     isGP64bit()))) {
4701         Error(E, "invalid register operand");
4702         return MatchOperand_ParseFail;
4703       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
4704                  ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) ||
4705                   (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 &&
4706                    isGP64bit()))) {
4707         Error(E, "consecutive register numbers expected");
4708         return MatchOperand_ParseFail;
4709       }
4710 
4711       Regs.push_back(RegNo);
4712     }
4713 
4714     if (Parser.getTok().is(AsmToken::Minus))
4715       RegRange = true;
4716 
4717     if (!Parser.getTok().isNot(AsmToken::Minus) &&
4718         !Parser.getTok().isNot(AsmToken::Comma)) {
4719       Error(E, "',' or '-' expected");
4720       return MatchOperand_ParseFail;
4721     }
4722 
4723     Lex(); // Consume comma or minus
4724     if (Parser.getTok().isNot(AsmToken::Dollar))
4725       break;
4726 
4727     PrevReg = RegNo;
4728   }
4729 
4730   SMLoc E = Parser.getTok().getLoc();
4731   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4732   parseMemOperand(Operands);
4733   return MatchOperand_Success;
4734 }
4735 
4736 MipsAsmParser::OperandMatchResultTy
4737 MipsAsmParser::parseRegisterPair(OperandVector &Operands) {
4738   MCAsmParser &Parser = getParser();
4739 
4740   SMLoc S = Parser.getTok().getLoc();
4741   if (parseAnyRegister(Operands) != MatchOperand_Success)
4742     return MatchOperand_ParseFail;
4743 
4744   SMLoc E = Parser.getTok().getLoc();
4745   MipsOperand &Op = static_cast<MipsOperand &>(*Operands.back());
4746   unsigned Reg = Op.getGPR32Reg();
4747   Operands.pop_back();
4748   Operands.push_back(MipsOperand::CreateRegPair(Reg, S, E, *this));
4749   return MatchOperand_Success;
4750 }
4751 
4752 MipsAsmParser::OperandMatchResultTy
4753 MipsAsmParser::parseMovePRegPair(OperandVector &Operands) {
4754   MCAsmParser &Parser = getParser();
4755   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4756   SmallVector<unsigned, 10> Regs;
4757 
4758   if (Parser.getTok().isNot(AsmToken::Dollar))
4759     return MatchOperand_ParseFail;
4760 
4761   SMLoc S = Parser.getTok().getLoc();
4762 
4763   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4764     return MatchOperand_ParseFail;
4765 
4766   MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4767   unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4768   Regs.push_back(RegNo);
4769 
4770   SMLoc E = Parser.getTok().getLoc();
4771   if (Parser.getTok().isNot(AsmToken::Comma)) {
4772     Error(E, "',' expected");
4773     return MatchOperand_ParseFail;
4774   }
4775 
4776   // Remove comma.
4777   Parser.Lex();
4778 
4779   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4780     return MatchOperand_ParseFail;
4781 
4782   Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4783   RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4784   Regs.push_back(RegNo);
4785 
4786   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4787 
4788   return MatchOperand_Success;
4789 }
4790 
4791 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
4792 
4793   MCSymbolRefExpr::VariantKind VK =
4794       StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
4795           .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
4796           .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
4797           .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
4798           .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
4799           .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
4800           .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
4801           .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
4802           .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
4803           .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
4804           .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
4805           .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
4806           .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
4807           .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
4808           .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
4809           .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
4810           .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
4811           .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
4812           .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
4813           .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
4814           .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
4815           .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
4816           .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
4817           .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
4818           .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
4819           .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
4820           .Default(MCSymbolRefExpr::VK_None);
4821 
4822   assert(VK != MCSymbolRefExpr::VK_None);
4823 
4824   return VK;
4825 }
4826 
4827 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
4828 /// either this.
4829 /// ::= '(', register, ')'
4830 /// handle it before we iterate so we don't get tripped up by the lack of
4831 /// a comma.
4832 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
4833   MCAsmParser &Parser = getParser();
4834   if (getLexer().is(AsmToken::LParen)) {
4835     Operands.push_back(
4836         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
4837     Parser.Lex();
4838     if (parseOperand(Operands, Name)) {
4839       SMLoc Loc = getLexer().getLoc();
4840       Parser.eatToEndOfStatement();
4841       return Error(Loc, "unexpected token in argument list");
4842     }
4843     if (Parser.getTok().isNot(AsmToken::RParen)) {
4844       SMLoc Loc = getLexer().getLoc();
4845       Parser.eatToEndOfStatement();
4846       return Error(Loc, "unexpected token, expected ')'");
4847     }
4848     Operands.push_back(
4849         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
4850     Parser.Lex();
4851   }
4852   return false;
4853 }
4854 
4855 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
4856 /// either one of these.
4857 /// ::= '[', register, ']'
4858 /// ::= '[', integer, ']'
4859 /// handle it before we iterate so we don't get tripped up by the lack of
4860 /// a comma.
4861 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
4862                                        OperandVector &Operands) {
4863   MCAsmParser &Parser = getParser();
4864   if (getLexer().is(AsmToken::LBrac)) {
4865     Operands.push_back(
4866         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
4867     Parser.Lex();
4868     if (parseOperand(Operands, Name)) {
4869       SMLoc Loc = getLexer().getLoc();
4870       Parser.eatToEndOfStatement();
4871       return Error(Loc, "unexpected token in argument list");
4872     }
4873     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4874       SMLoc Loc = getLexer().getLoc();
4875       Parser.eatToEndOfStatement();
4876       return Error(Loc, "unexpected token, expected ']'");
4877     }
4878     Operands.push_back(
4879         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
4880     Parser.Lex();
4881   }
4882   return false;
4883 }
4884 
4885 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
4886                                      SMLoc NameLoc, OperandVector &Operands) {
4887   MCAsmParser &Parser = getParser();
4888   DEBUG(dbgs() << "ParseInstruction\n");
4889 
4890   // We have reached first instruction, module directive are now forbidden.
4891   getTargetStreamer().forbidModuleDirective();
4892 
4893   // Check if we have valid mnemonic
4894   if (!mnemonicIsValid(Name, 0)) {
4895     Parser.eatToEndOfStatement();
4896     return Error(NameLoc, "unknown instruction");
4897   }
4898   // First operand in MCInst is instruction mnemonic.
4899   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
4900 
4901   // Read the remaining operands.
4902   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4903     // Read the first operand.
4904     if (parseOperand(Operands, Name)) {
4905       SMLoc Loc = getLexer().getLoc();
4906       Parser.eatToEndOfStatement();
4907       return Error(Loc, "unexpected token in argument list");
4908     }
4909     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
4910       return true;
4911     // AFAIK, parenthesis suffixes are never on the first operand
4912 
4913     while (getLexer().is(AsmToken::Comma)) {
4914       Parser.Lex(); // Eat the comma.
4915       // Parse and remember the operand.
4916       if (parseOperand(Operands, Name)) {
4917         SMLoc Loc = getLexer().getLoc();
4918         Parser.eatToEndOfStatement();
4919         return Error(Loc, "unexpected token in argument list");
4920       }
4921       // Parse bracket and parenthesis suffixes before we iterate
4922       if (getLexer().is(AsmToken::LBrac)) {
4923         if (parseBracketSuffix(Name, Operands))
4924           return true;
4925       } else if (getLexer().is(AsmToken::LParen) &&
4926                  parseParenSuffix(Name, Operands))
4927         return true;
4928     }
4929   }
4930   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4931     SMLoc Loc = getLexer().getLoc();
4932     Parser.eatToEndOfStatement();
4933     return Error(Loc, "unexpected token in argument list");
4934   }
4935   Parser.Lex(); // Consume the EndOfStatement.
4936   return false;
4937 }
4938 
4939 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
4940   MCAsmParser &Parser = getParser();
4941   SMLoc Loc = getLexer().getLoc();
4942   Parser.eatToEndOfStatement();
4943   return Error(Loc, ErrorMsg);
4944 }
4945 
4946 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
4947   return Error(Loc, ErrorMsg);
4948 }
4949 
4950 bool MipsAsmParser::parseSetNoAtDirective() {
4951   MCAsmParser &Parser = getParser();
4952   // Line should look like: ".set noat".
4953 
4954   // Set the $at register to $0.
4955   AssemblerOptions.back()->setATRegIndex(0);
4956 
4957   Parser.Lex(); // Eat "noat".
4958 
4959   // If this is not the end of the statement, report an error.
4960   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4961     reportParseError("unexpected token, expected end of statement");
4962     return false;
4963   }
4964 
4965   getTargetStreamer().emitDirectiveSetNoAt();
4966   Parser.Lex(); // Consume the EndOfStatement.
4967   return false;
4968 }
4969 
4970 bool MipsAsmParser::parseSetAtDirective() {
4971   // Line can be: ".set at", which sets $at to $1
4972   //          or  ".set at=$reg", which sets $at to $reg.
4973   MCAsmParser &Parser = getParser();
4974   Parser.Lex(); // Eat "at".
4975 
4976   if (getLexer().is(AsmToken::EndOfStatement)) {
4977     // No register was specified, so we set $at to $1.
4978     AssemblerOptions.back()->setATRegIndex(1);
4979 
4980     getTargetStreamer().emitDirectiveSetAt();
4981     Parser.Lex(); // Consume the EndOfStatement.
4982     return false;
4983   }
4984 
4985   if (getLexer().isNot(AsmToken::Equal)) {
4986     reportParseError("unexpected token, expected equals sign");
4987     return false;
4988   }
4989   Parser.Lex(); // Eat "=".
4990 
4991   if (getLexer().isNot(AsmToken::Dollar)) {
4992     if (getLexer().is(AsmToken::EndOfStatement)) {
4993       reportParseError("no register specified");
4994       return false;
4995     } else {
4996       reportParseError("unexpected token, expected dollar sign '$'");
4997       return false;
4998     }
4999   }
5000   Parser.Lex(); // Eat "$".
5001 
5002   // Find out what "reg" is.
5003   unsigned AtRegNo;
5004   const AsmToken &Reg = Parser.getTok();
5005   if (Reg.is(AsmToken::Identifier)) {
5006     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
5007   } else if (Reg.is(AsmToken::Integer)) {
5008     AtRegNo = Reg.getIntVal();
5009   } else {
5010     reportParseError("unexpected token, expected identifier or integer");
5011     return false;
5012   }
5013 
5014   // Check if $reg is a valid register. If it is, set $at to $reg.
5015   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
5016     reportParseError("invalid register");
5017     return false;
5018   }
5019   Parser.Lex(); // Eat "reg".
5020 
5021   // If this is not the end of the statement, report an error.
5022   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5023     reportParseError("unexpected token, expected end of statement");
5024     return false;
5025   }
5026 
5027   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
5028 
5029   Parser.Lex(); // Consume the EndOfStatement.
5030   return false;
5031 }
5032 
5033 bool MipsAsmParser::parseSetReorderDirective() {
5034   MCAsmParser &Parser = getParser();
5035   Parser.Lex();
5036   // If this is not the end of the statement, report an error.
5037   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5038     reportParseError("unexpected token, expected end of statement");
5039     return false;
5040   }
5041   AssemblerOptions.back()->setReorder();
5042   getTargetStreamer().emitDirectiveSetReorder();
5043   Parser.Lex(); // Consume the EndOfStatement.
5044   return false;
5045 }
5046 
5047 bool MipsAsmParser::parseSetNoReorderDirective() {
5048   MCAsmParser &Parser = getParser();
5049   Parser.Lex();
5050   // If this is not the end of the statement, report an error.
5051   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5052     reportParseError("unexpected token, expected end of statement");
5053     return false;
5054   }
5055   AssemblerOptions.back()->setNoReorder();
5056   getTargetStreamer().emitDirectiveSetNoReorder();
5057   Parser.Lex(); // Consume the EndOfStatement.
5058   return false;
5059 }
5060 
5061 bool MipsAsmParser::parseSetMacroDirective() {
5062   MCAsmParser &Parser = getParser();
5063   Parser.Lex();
5064   // If this is not the end of the statement, report an error.
5065   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5066     reportParseError("unexpected token, expected end of statement");
5067     return false;
5068   }
5069   AssemblerOptions.back()->setMacro();
5070   getTargetStreamer().emitDirectiveSetMacro();
5071   Parser.Lex(); // Consume the EndOfStatement.
5072   return false;
5073 }
5074 
5075 bool MipsAsmParser::parseSetNoMacroDirective() {
5076   MCAsmParser &Parser = getParser();
5077   Parser.Lex();
5078   // If this is not the end of the statement, report an error.
5079   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5080     reportParseError("unexpected token, expected end of statement");
5081     return false;
5082   }
5083   if (AssemblerOptions.back()->isReorder()) {
5084     reportParseError("`noreorder' must be set before `nomacro'");
5085     return false;
5086   }
5087   AssemblerOptions.back()->setNoMacro();
5088   getTargetStreamer().emitDirectiveSetNoMacro();
5089   Parser.Lex(); // Consume the EndOfStatement.
5090   return false;
5091 }
5092 
5093 bool MipsAsmParser::parseSetMsaDirective() {
5094   MCAsmParser &Parser = getParser();
5095   Parser.Lex();
5096 
5097   // If this is not the end of the statement, report an error.
5098   if (getLexer().isNot(AsmToken::EndOfStatement))
5099     return reportParseError("unexpected token, expected end of statement");
5100 
5101   setFeatureBits(Mips::FeatureMSA, "msa");
5102   getTargetStreamer().emitDirectiveSetMsa();
5103   return false;
5104 }
5105 
5106 bool MipsAsmParser::parseSetNoMsaDirective() {
5107   MCAsmParser &Parser = getParser();
5108   Parser.Lex();
5109 
5110   // If this is not the end of the statement, report an error.
5111   if (getLexer().isNot(AsmToken::EndOfStatement))
5112     return reportParseError("unexpected token, expected end of statement");
5113 
5114   clearFeatureBits(Mips::FeatureMSA, "msa");
5115   getTargetStreamer().emitDirectiveSetNoMsa();
5116   return false;
5117 }
5118 
5119 bool MipsAsmParser::parseSetNoDspDirective() {
5120   MCAsmParser &Parser = getParser();
5121   Parser.Lex(); // Eat "nodsp".
5122 
5123   // If this is not the end of the statement, report an error.
5124   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5125     reportParseError("unexpected token, expected end of statement");
5126     return false;
5127   }
5128 
5129   clearFeatureBits(Mips::FeatureDSP, "dsp");
5130   getTargetStreamer().emitDirectiveSetNoDsp();
5131   return false;
5132 }
5133 
5134 bool MipsAsmParser::parseSetMips16Directive() {
5135   MCAsmParser &Parser = getParser();
5136   Parser.Lex(); // Eat "mips16".
5137 
5138   // If this is not the end of the statement, report an error.
5139   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5140     reportParseError("unexpected token, expected end of statement");
5141     return false;
5142   }
5143 
5144   setFeatureBits(Mips::FeatureMips16, "mips16");
5145   getTargetStreamer().emitDirectiveSetMips16();
5146   Parser.Lex(); // Consume the EndOfStatement.
5147   return false;
5148 }
5149 
5150 bool MipsAsmParser::parseSetNoMips16Directive() {
5151   MCAsmParser &Parser = getParser();
5152   Parser.Lex(); // Eat "nomips16".
5153 
5154   // If this is not the end of the statement, report an error.
5155   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5156     reportParseError("unexpected token, expected end of statement");
5157     return false;
5158   }
5159 
5160   clearFeatureBits(Mips::FeatureMips16, "mips16");
5161   getTargetStreamer().emitDirectiveSetNoMips16();
5162   Parser.Lex(); // Consume the EndOfStatement.
5163   return false;
5164 }
5165 
5166 bool MipsAsmParser::parseSetFpDirective() {
5167   MCAsmParser &Parser = getParser();
5168   MipsABIFlagsSection::FpABIKind FpAbiVal;
5169   // Line can be: .set fp=32
5170   //              .set fp=xx
5171   //              .set fp=64
5172   Parser.Lex(); // Eat fp token
5173   AsmToken Tok = Parser.getTok();
5174   if (Tok.isNot(AsmToken::Equal)) {
5175     reportParseError("unexpected token, expected equals sign '='");
5176     return false;
5177   }
5178   Parser.Lex(); // Eat '=' token.
5179   Tok = Parser.getTok();
5180 
5181   if (!parseFpABIValue(FpAbiVal, ".set"))
5182     return false;
5183 
5184   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5185     reportParseError("unexpected token, expected end of statement");
5186     return false;
5187   }
5188   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
5189   Parser.Lex(); // Consume the EndOfStatement.
5190   return false;
5191 }
5192 
5193 bool MipsAsmParser::parseSetOddSPRegDirective() {
5194   MCAsmParser &Parser = getParser();
5195 
5196   Parser.Lex(); // Eat "oddspreg".
5197   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5198     reportParseError("unexpected token, expected end of statement");
5199     return false;
5200   }
5201 
5202   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5203   getTargetStreamer().emitDirectiveSetOddSPReg();
5204   return false;
5205 }
5206 
5207 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
5208   MCAsmParser &Parser = getParser();
5209 
5210   Parser.Lex(); // Eat "nooddspreg".
5211   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5212     reportParseError("unexpected token, expected end of statement");
5213     return false;
5214   }
5215 
5216   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5217   getTargetStreamer().emitDirectiveSetNoOddSPReg();
5218   return false;
5219 }
5220 
5221 bool MipsAsmParser::parseSetPopDirective() {
5222   MCAsmParser &Parser = getParser();
5223   SMLoc Loc = getLexer().getLoc();
5224 
5225   Parser.Lex();
5226   if (getLexer().isNot(AsmToken::EndOfStatement))
5227     return reportParseError("unexpected token, expected end of statement");
5228 
5229   // Always keep an element on the options "stack" to prevent the user
5230   // from changing the initial options. This is how we remember them.
5231   if (AssemblerOptions.size() == 2)
5232     return reportParseError(Loc, ".set pop with no .set push");
5233 
5234   MCSubtargetInfo &STI = copySTI();
5235   AssemblerOptions.pop_back();
5236   setAvailableFeatures(
5237       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
5238   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
5239 
5240   getTargetStreamer().emitDirectiveSetPop();
5241   return false;
5242 }
5243 
5244 bool MipsAsmParser::parseSetPushDirective() {
5245   MCAsmParser &Parser = getParser();
5246   Parser.Lex();
5247   if (getLexer().isNot(AsmToken::EndOfStatement))
5248     return reportParseError("unexpected token, expected end of statement");
5249 
5250   // Create a copy of the current assembler options environment and push it.
5251   AssemblerOptions.push_back(
5252               make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
5253 
5254   getTargetStreamer().emitDirectiveSetPush();
5255   return false;
5256 }
5257 
5258 bool MipsAsmParser::parseSetSoftFloatDirective() {
5259   MCAsmParser &Parser = getParser();
5260   Parser.Lex();
5261   if (getLexer().isNot(AsmToken::EndOfStatement))
5262     return reportParseError("unexpected token, expected end of statement");
5263 
5264   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5265   getTargetStreamer().emitDirectiveSetSoftFloat();
5266   return false;
5267 }
5268 
5269 bool MipsAsmParser::parseSetHardFloatDirective() {
5270   MCAsmParser &Parser = getParser();
5271   Parser.Lex();
5272   if (getLexer().isNot(AsmToken::EndOfStatement))
5273     return reportParseError("unexpected token, expected end of statement");
5274 
5275   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5276   getTargetStreamer().emitDirectiveSetHardFloat();
5277   return false;
5278 }
5279 
5280 bool MipsAsmParser::parseSetAssignment() {
5281   StringRef Name;
5282   const MCExpr *Value;
5283   MCAsmParser &Parser = getParser();
5284 
5285   if (Parser.parseIdentifier(Name))
5286     reportParseError("expected identifier after .set");
5287 
5288   if (getLexer().isNot(AsmToken::Comma))
5289     return reportParseError("unexpected token, expected comma");
5290   Lex(); // Eat comma
5291 
5292   if (Parser.parseExpression(Value))
5293     return reportParseError("expected valid expression after comma");
5294 
5295   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5296   Sym->setVariableValue(Value);
5297 
5298   return false;
5299 }
5300 
5301 bool MipsAsmParser::parseSetMips0Directive() {
5302   MCAsmParser &Parser = getParser();
5303   Parser.Lex();
5304   if (getLexer().isNot(AsmToken::EndOfStatement))
5305     return reportParseError("unexpected token, expected end of statement");
5306 
5307   // Reset assembler options to their initial values.
5308   MCSubtargetInfo &STI = copySTI();
5309   setAvailableFeatures(
5310       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
5311   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
5312   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
5313 
5314   getTargetStreamer().emitDirectiveSetMips0();
5315   return false;
5316 }
5317 
5318 bool MipsAsmParser::parseSetArchDirective() {
5319   MCAsmParser &Parser = getParser();
5320   Parser.Lex();
5321   if (getLexer().isNot(AsmToken::Equal))
5322     return reportParseError("unexpected token, expected equals sign");
5323 
5324   Parser.Lex();
5325   StringRef Arch;
5326   if (Parser.parseIdentifier(Arch))
5327     return reportParseError("expected arch identifier");
5328 
5329   StringRef ArchFeatureName =
5330       StringSwitch<StringRef>(Arch)
5331           .Case("mips1", "mips1")
5332           .Case("mips2", "mips2")
5333           .Case("mips3", "mips3")
5334           .Case("mips4", "mips4")
5335           .Case("mips5", "mips5")
5336           .Case("mips32", "mips32")
5337           .Case("mips32r2", "mips32r2")
5338           .Case("mips32r3", "mips32r3")
5339           .Case("mips32r5", "mips32r5")
5340           .Case("mips32r6", "mips32r6")
5341           .Case("mips64", "mips64")
5342           .Case("mips64r2", "mips64r2")
5343           .Case("mips64r3", "mips64r3")
5344           .Case("mips64r5", "mips64r5")
5345           .Case("mips64r6", "mips64r6")
5346           .Case("octeon", "cnmips")
5347           .Case("r4000", "mips3") // This is an implementation of Mips3.
5348           .Default("");
5349 
5350   if (ArchFeatureName.empty())
5351     return reportParseError("unsupported architecture");
5352 
5353   selectArch(ArchFeatureName);
5354   getTargetStreamer().emitDirectiveSetArch(Arch);
5355   return false;
5356 }
5357 
5358 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
5359   MCAsmParser &Parser = getParser();
5360   Parser.Lex();
5361   if (getLexer().isNot(AsmToken::EndOfStatement))
5362     return reportParseError("unexpected token, expected end of statement");
5363 
5364   switch (Feature) {
5365   default:
5366     llvm_unreachable("Unimplemented feature");
5367   case Mips::FeatureDSP:
5368     setFeatureBits(Mips::FeatureDSP, "dsp");
5369     getTargetStreamer().emitDirectiveSetDsp();
5370     break;
5371   case Mips::FeatureMicroMips:
5372     getTargetStreamer().emitDirectiveSetMicroMips();
5373     break;
5374   case Mips::FeatureMips1:
5375     selectArch("mips1");
5376     getTargetStreamer().emitDirectiveSetMips1();
5377     break;
5378   case Mips::FeatureMips2:
5379     selectArch("mips2");
5380     getTargetStreamer().emitDirectiveSetMips2();
5381     break;
5382   case Mips::FeatureMips3:
5383     selectArch("mips3");
5384     getTargetStreamer().emitDirectiveSetMips3();
5385     break;
5386   case Mips::FeatureMips4:
5387     selectArch("mips4");
5388     getTargetStreamer().emitDirectiveSetMips4();
5389     break;
5390   case Mips::FeatureMips5:
5391     selectArch("mips5");
5392     getTargetStreamer().emitDirectiveSetMips5();
5393     break;
5394   case Mips::FeatureMips32:
5395     selectArch("mips32");
5396     getTargetStreamer().emitDirectiveSetMips32();
5397     break;
5398   case Mips::FeatureMips32r2:
5399     selectArch("mips32r2");
5400     getTargetStreamer().emitDirectiveSetMips32R2();
5401     break;
5402   case Mips::FeatureMips32r3:
5403     selectArch("mips32r3");
5404     getTargetStreamer().emitDirectiveSetMips32R3();
5405     break;
5406   case Mips::FeatureMips32r5:
5407     selectArch("mips32r5");
5408     getTargetStreamer().emitDirectiveSetMips32R5();
5409     break;
5410   case Mips::FeatureMips32r6:
5411     selectArch("mips32r6");
5412     getTargetStreamer().emitDirectiveSetMips32R6();
5413     break;
5414   case Mips::FeatureMips64:
5415     selectArch("mips64");
5416     getTargetStreamer().emitDirectiveSetMips64();
5417     break;
5418   case Mips::FeatureMips64r2:
5419     selectArch("mips64r2");
5420     getTargetStreamer().emitDirectiveSetMips64R2();
5421     break;
5422   case Mips::FeatureMips64r3:
5423     selectArch("mips64r3");
5424     getTargetStreamer().emitDirectiveSetMips64R3();
5425     break;
5426   case Mips::FeatureMips64r5:
5427     selectArch("mips64r5");
5428     getTargetStreamer().emitDirectiveSetMips64R5();
5429     break;
5430   case Mips::FeatureMips64r6:
5431     selectArch("mips64r6");
5432     getTargetStreamer().emitDirectiveSetMips64R6();
5433     break;
5434   }
5435   return false;
5436 }
5437 
5438 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
5439   MCAsmParser &Parser = getParser();
5440   if (getLexer().isNot(AsmToken::Comma)) {
5441     SMLoc Loc = getLexer().getLoc();
5442     Parser.eatToEndOfStatement();
5443     return Error(Loc, ErrorStr);
5444   }
5445 
5446   Parser.Lex(); // Eat the comma.
5447   return true;
5448 }
5449 
5450 // Used to determine if .cpload, .cprestore, and .cpsetup have any effect.
5451 // In this class, it is only used for .cprestore.
5452 // FIXME: Only keep track of IsPicEnabled in one place, instead of in both
5453 // MipsTargetELFStreamer and MipsAsmParser.
5454 bool MipsAsmParser::isPicAndNotNxxAbi() {
5455   return inPicMode() && !(isABI_N32() || isABI_N64());
5456 }
5457 
5458 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
5459   if (AssemblerOptions.back()->isReorder())
5460     Warning(Loc, ".cpload should be inside a noreorder section");
5461 
5462   if (inMips16Mode()) {
5463     reportParseError(".cpload is not supported in Mips16 mode");
5464     return false;
5465   }
5466 
5467   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
5468   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
5469   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
5470     reportParseError("expected register containing function address");
5471     return false;
5472   }
5473 
5474   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
5475   if (!RegOpnd.isGPRAsmReg()) {
5476     reportParseError(RegOpnd.getStartLoc(), "invalid register");
5477     return false;
5478   }
5479 
5480   // If this is not the end of the statement, report an error.
5481   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5482     reportParseError("unexpected token, expected end of statement");
5483     return false;
5484   }
5485 
5486   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
5487   return false;
5488 }
5489 
5490 bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) {
5491   MCAsmParser &Parser = getParser();
5492 
5493   // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
5494   // is used in non-PIC mode.
5495 
5496   if (inMips16Mode()) {
5497     reportParseError(".cprestore is not supported in Mips16 mode");
5498     return false;
5499   }
5500 
5501   // Get the stack offset value.
5502   const MCExpr *StackOffset;
5503   int64_t StackOffsetVal;
5504   if (Parser.parseExpression(StackOffset)) {
5505     reportParseError("expected stack offset value");
5506     return false;
5507   }
5508 
5509   if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) {
5510     reportParseError("stack offset is not an absolute expression");
5511     return false;
5512   }
5513 
5514   if (StackOffsetVal < 0) {
5515     Warning(Loc, ".cprestore with negative stack offset has no effect");
5516     IsCpRestoreSet = false;
5517   } else {
5518     IsCpRestoreSet = true;
5519     CpRestoreOffset = StackOffsetVal;
5520   }
5521 
5522   // If this is not the end of the statement, report an error.
5523   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5524     reportParseError("unexpected token, expected end of statement");
5525     return false;
5526   }
5527 
5528   // Store the $gp on the stack.
5529   if (getStreamer().isIntegratedAssemblerRequired()) {
5530     const MCSubtargetInfo &STI = getSTI();
5531     createCpRestoreMemOp(false /*IsLoad*/, CpRestoreOffset /*StackOffset*/, Loc,
5532                          getStreamer(), &STI);
5533   }
5534 
5535   getTargetStreamer().emitDirectiveCpRestore(CpRestoreOffset);
5536   Parser.Lex(); // Consume the EndOfStatement.
5537   return false;
5538 }
5539 
5540 bool MipsAsmParser::parseDirectiveCPSetup() {
5541   MCAsmParser &Parser = getParser();
5542   unsigned FuncReg;
5543   unsigned Save;
5544   bool SaveIsReg = true;
5545 
5546   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
5547   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
5548   if (ResTy == MatchOperand_NoMatch) {
5549     reportParseError("expected register containing function address");
5550     Parser.eatToEndOfStatement();
5551     return false;
5552   }
5553 
5554   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5555   if (!FuncRegOpnd.isGPRAsmReg()) {
5556     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
5557     Parser.eatToEndOfStatement();
5558     return false;
5559   }
5560 
5561   FuncReg = FuncRegOpnd.getGPR32Reg();
5562   TmpReg.clear();
5563 
5564   if (!eatComma("unexpected token, expected comma"))
5565     return true;
5566 
5567   ResTy = parseAnyRegister(TmpReg);
5568   if (ResTy == MatchOperand_NoMatch) {
5569     const MCExpr *OffsetExpr;
5570     int64_t OffsetVal;
5571     SMLoc ExprLoc = getLexer().getLoc();
5572 
5573     if (Parser.parseExpression(OffsetExpr) ||
5574         !OffsetExpr->evaluateAsAbsolute(OffsetVal)) {
5575       reportParseError(ExprLoc, "expected save register or stack offset");
5576       Parser.eatToEndOfStatement();
5577       return false;
5578     }
5579 
5580     Save = OffsetVal;
5581     SaveIsReg = false;
5582   } else {
5583     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5584     if (!SaveOpnd.isGPRAsmReg()) {
5585       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
5586       Parser.eatToEndOfStatement();
5587       return false;
5588     }
5589     Save = SaveOpnd.getGPR32Reg();
5590   }
5591 
5592   if (!eatComma("unexpected token, expected comma"))
5593     return true;
5594 
5595   const MCExpr *Expr;
5596   if (Parser.parseExpression(Expr)) {
5597     reportParseError("expected expression");
5598     return false;
5599   }
5600 
5601   if (Expr->getKind() != MCExpr::SymbolRef) {
5602     reportParseError("expected symbol");
5603     return false;
5604   }
5605   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
5606 
5607   CpSaveLocation = Save;
5608   CpSaveLocationIsRegister = SaveIsReg;
5609 
5610   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
5611                                            SaveIsReg);
5612   return false;
5613 }
5614 
5615 bool MipsAsmParser::parseDirectiveCPReturn() {
5616   getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation,
5617                                             CpSaveLocationIsRegister);
5618   return false;
5619 }
5620 
5621 bool MipsAsmParser::parseDirectiveNaN() {
5622   MCAsmParser &Parser = getParser();
5623   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5624     const AsmToken &Tok = Parser.getTok();
5625 
5626     if (Tok.getString() == "2008") {
5627       Parser.Lex();
5628       getTargetStreamer().emitDirectiveNaN2008();
5629       return false;
5630     } else if (Tok.getString() == "legacy") {
5631       Parser.Lex();
5632       getTargetStreamer().emitDirectiveNaNLegacy();
5633       return false;
5634     }
5635   }
5636   // If we don't recognize the option passed to the .nan
5637   // directive (e.g. no option or unknown option), emit an error.
5638   reportParseError("invalid option in .nan directive");
5639   return false;
5640 }
5641 
5642 bool MipsAsmParser::parseDirectiveSet() {
5643   MCAsmParser &Parser = getParser();
5644   // Get the next token.
5645   const AsmToken &Tok = Parser.getTok();
5646 
5647   if (Tok.getString() == "noat") {
5648     return parseSetNoAtDirective();
5649   } else if (Tok.getString() == "at") {
5650     return parseSetAtDirective();
5651   } else if (Tok.getString() == "arch") {
5652     return parseSetArchDirective();
5653   } else if (Tok.getString() == "fp") {
5654     return parseSetFpDirective();
5655   } else if (Tok.getString() == "oddspreg") {
5656     return parseSetOddSPRegDirective();
5657   } else if (Tok.getString() == "nooddspreg") {
5658     return parseSetNoOddSPRegDirective();
5659   } else if (Tok.getString() == "pop") {
5660     return parseSetPopDirective();
5661   } else if (Tok.getString() == "push") {
5662     return parseSetPushDirective();
5663   } else if (Tok.getString() == "reorder") {
5664     return parseSetReorderDirective();
5665   } else if (Tok.getString() == "noreorder") {
5666     return parseSetNoReorderDirective();
5667   } else if (Tok.getString() == "macro") {
5668     return parseSetMacroDirective();
5669   } else if (Tok.getString() == "nomacro") {
5670     return parseSetNoMacroDirective();
5671   } else if (Tok.getString() == "mips16") {
5672     return parseSetMips16Directive();
5673   } else if (Tok.getString() == "nomips16") {
5674     return parseSetNoMips16Directive();
5675   } else if (Tok.getString() == "nomicromips") {
5676     getTargetStreamer().emitDirectiveSetNoMicroMips();
5677     Parser.eatToEndOfStatement();
5678     return false;
5679   } else if (Tok.getString() == "micromips") {
5680     return parseSetFeature(Mips::FeatureMicroMips);
5681   } else if (Tok.getString() == "mips0") {
5682     return parseSetMips0Directive();
5683   } else if (Tok.getString() == "mips1") {
5684     return parseSetFeature(Mips::FeatureMips1);
5685   } else if (Tok.getString() == "mips2") {
5686     return parseSetFeature(Mips::FeatureMips2);
5687   } else if (Tok.getString() == "mips3") {
5688     return parseSetFeature(Mips::FeatureMips3);
5689   } else if (Tok.getString() == "mips4") {
5690     return parseSetFeature(Mips::FeatureMips4);
5691   } else if (Tok.getString() == "mips5") {
5692     return parseSetFeature(Mips::FeatureMips5);
5693   } else if (Tok.getString() == "mips32") {
5694     return parseSetFeature(Mips::FeatureMips32);
5695   } else if (Tok.getString() == "mips32r2") {
5696     return parseSetFeature(Mips::FeatureMips32r2);
5697   } else if (Tok.getString() == "mips32r3") {
5698     return parseSetFeature(Mips::FeatureMips32r3);
5699   } else if (Tok.getString() == "mips32r5") {
5700     return parseSetFeature(Mips::FeatureMips32r5);
5701   } else if (Tok.getString() == "mips32r6") {
5702     return parseSetFeature(Mips::FeatureMips32r6);
5703   } else if (Tok.getString() == "mips64") {
5704     return parseSetFeature(Mips::FeatureMips64);
5705   } else if (Tok.getString() == "mips64r2") {
5706     return parseSetFeature(Mips::FeatureMips64r2);
5707   } else if (Tok.getString() == "mips64r3") {
5708     return parseSetFeature(Mips::FeatureMips64r3);
5709   } else if (Tok.getString() == "mips64r5") {
5710     return parseSetFeature(Mips::FeatureMips64r5);
5711   } else if (Tok.getString() == "mips64r6") {
5712     return parseSetFeature(Mips::FeatureMips64r6);
5713   } else if (Tok.getString() == "dsp") {
5714     return parseSetFeature(Mips::FeatureDSP);
5715   } else if (Tok.getString() == "nodsp") {
5716     return parseSetNoDspDirective();
5717   } else if (Tok.getString() == "msa") {
5718     return parseSetMsaDirective();
5719   } else if (Tok.getString() == "nomsa") {
5720     return parseSetNoMsaDirective();
5721   } else if (Tok.getString() == "softfloat") {
5722     return parseSetSoftFloatDirective();
5723   } else if (Tok.getString() == "hardfloat") {
5724     return parseSetHardFloatDirective();
5725   } else {
5726     // It is just an identifier, look for an assignment.
5727     parseSetAssignment();
5728     return false;
5729   }
5730 
5731   return true;
5732 }
5733 
5734 /// parseDataDirective
5735 ///  ::= .word [ expression (, expression)* ]
5736 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
5737   MCAsmParser &Parser = getParser();
5738   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5739     for (;;) {
5740       const MCExpr *Value;
5741       if (getParser().parseExpression(Value))
5742         return true;
5743 
5744       getParser().getStreamer().EmitValue(Value, Size);
5745 
5746       if (getLexer().is(AsmToken::EndOfStatement))
5747         break;
5748 
5749       if (getLexer().isNot(AsmToken::Comma))
5750         return Error(L, "unexpected token, expected comma");
5751       Parser.Lex();
5752     }
5753   }
5754 
5755   Parser.Lex();
5756   return false;
5757 }
5758 
5759 /// parseDirectiveGpWord
5760 ///  ::= .gpword local_sym
5761 bool MipsAsmParser::parseDirectiveGpWord() {
5762   MCAsmParser &Parser = getParser();
5763   const MCExpr *Value;
5764   // EmitGPRel32Value requires an expression, so we are using base class
5765   // method to evaluate the expression.
5766   if (getParser().parseExpression(Value))
5767     return true;
5768   getParser().getStreamer().EmitGPRel32Value(Value);
5769 
5770   if (getLexer().isNot(AsmToken::EndOfStatement))
5771     return Error(getLexer().getLoc(),
5772                 "unexpected token, expected end of statement");
5773   Parser.Lex(); // Eat EndOfStatement token.
5774   return false;
5775 }
5776 
5777 /// parseDirectiveGpDWord
5778 ///  ::= .gpdword local_sym
5779 bool MipsAsmParser::parseDirectiveGpDWord() {
5780   MCAsmParser &Parser = getParser();
5781   const MCExpr *Value;
5782   // EmitGPRel64Value requires an expression, so we are using base class
5783   // method to evaluate the expression.
5784   if (getParser().parseExpression(Value))
5785     return true;
5786   getParser().getStreamer().EmitGPRel64Value(Value);
5787 
5788   if (getLexer().isNot(AsmToken::EndOfStatement))
5789     return Error(getLexer().getLoc(),
5790                 "unexpected token, expected end of statement");
5791   Parser.Lex(); // Eat EndOfStatement token.
5792   return false;
5793 }
5794 
5795 bool MipsAsmParser::parseDirectiveOption() {
5796   MCAsmParser &Parser = getParser();
5797   // Get the option token.
5798   AsmToken Tok = Parser.getTok();
5799   // At the moment only identifiers are supported.
5800   if (Tok.isNot(AsmToken::Identifier)) {
5801     Error(Parser.getTok().getLoc(), "unexpected token, expected identifier");
5802     Parser.eatToEndOfStatement();
5803     return false;
5804   }
5805 
5806   StringRef Option = Tok.getIdentifier();
5807 
5808   if (Option == "pic0") {
5809     // MipsAsmParser needs to know if the current PIC mode changes.
5810     IsPicEnabled = false;
5811 
5812     getTargetStreamer().emitDirectiveOptionPic0();
5813     Parser.Lex();
5814     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5815       Error(Parser.getTok().getLoc(),
5816             "unexpected token, expected end of statement");
5817       Parser.eatToEndOfStatement();
5818     }
5819     return false;
5820   }
5821 
5822   if (Option == "pic2") {
5823     // MipsAsmParser needs to know if the current PIC mode changes.
5824     IsPicEnabled = true;
5825 
5826     getTargetStreamer().emitDirectiveOptionPic2();
5827     Parser.Lex();
5828     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5829       Error(Parser.getTok().getLoc(),
5830             "unexpected token, expected end of statement");
5831       Parser.eatToEndOfStatement();
5832     }
5833     return false;
5834   }
5835 
5836   // Unknown option.
5837   Warning(Parser.getTok().getLoc(),
5838           "unknown option, expected 'pic0' or 'pic2'");
5839   Parser.eatToEndOfStatement();
5840   return false;
5841 }
5842 
5843 /// parseInsnDirective
5844 ///  ::= .insn
5845 bool MipsAsmParser::parseInsnDirective() {
5846   // If this is not the end of the statement, report an error.
5847   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5848     reportParseError("unexpected token, expected end of statement");
5849     return false;
5850   }
5851 
5852   // The actual label marking happens in
5853   // MipsELFStreamer::createPendingLabelRelocs().
5854   getTargetStreamer().emitDirectiveInsn();
5855 
5856   getParser().Lex(); // Eat EndOfStatement token.
5857   return false;
5858 }
5859 
5860 /// parseSSectionDirective
5861 ///  ::= .sbss
5862 ///  ::= .sdata
5863 bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) {
5864   // If this is not the end of the statement, report an error.
5865   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5866     reportParseError("unexpected token, expected end of statement");
5867     return false;
5868   }
5869 
5870   MCSection *ELFSection = getContext().getELFSection(
5871       Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
5872   getParser().getStreamer().SwitchSection(ELFSection);
5873 
5874   getParser().Lex(); // Eat EndOfStatement token.
5875   return false;
5876 }
5877 
5878 /// parseDirectiveModule
5879 ///  ::= .module oddspreg
5880 ///  ::= .module nooddspreg
5881 ///  ::= .module fp=value
5882 ///  ::= .module softfloat
5883 ///  ::= .module hardfloat
5884 bool MipsAsmParser::parseDirectiveModule() {
5885   MCAsmParser &Parser = getParser();
5886   MCAsmLexer &Lexer = getLexer();
5887   SMLoc L = Lexer.getLoc();
5888 
5889   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
5890     // TODO : get a better message.
5891     reportParseError(".module directive must appear before any code");
5892     return false;
5893   }
5894 
5895   StringRef Option;
5896   if (Parser.parseIdentifier(Option)) {
5897     reportParseError("expected .module option identifier");
5898     return false;
5899   }
5900 
5901   if (Option == "oddspreg") {
5902     clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5903 
5904     // Synchronize the abiflags information with the FeatureBits information we
5905     // changed above.
5906     getTargetStreamer().updateABIInfo(*this);
5907 
5908     // If printing assembly, use the recently updated abiflags information.
5909     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5910     // emitted at the end).
5911     getTargetStreamer().emitDirectiveModuleOddSPReg();
5912 
5913     // If this is not the end of the statement, report an error.
5914     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5915       reportParseError("unexpected token, expected end of statement");
5916       return false;
5917     }
5918 
5919     return false; // parseDirectiveModule has finished successfully.
5920   } else if (Option == "nooddspreg") {
5921     if (!isABI_O32()) {
5922       Error(L, "'.module nooddspreg' requires the O32 ABI");
5923       return false;
5924     }
5925 
5926     setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5927 
5928     // Synchronize the abiflags information with the FeatureBits information we
5929     // changed above.
5930     getTargetStreamer().updateABIInfo(*this);
5931 
5932     // If printing assembly, use the recently updated abiflags information.
5933     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5934     // emitted at the end).
5935     getTargetStreamer().emitDirectiveModuleOddSPReg();
5936 
5937     // If this is not the end of the statement, report an error.
5938     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5939       reportParseError("unexpected token, expected end of statement");
5940       return false;
5941     }
5942 
5943     return false; // parseDirectiveModule has finished successfully.
5944   } else if (Option == "fp") {
5945     return parseDirectiveModuleFP();
5946   } else if (Option == "softfloat") {
5947     setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5948 
5949     // Synchronize the ABI Flags information with the FeatureBits information we
5950     // updated above.
5951     getTargetStreamer().updateABIInfo(*this);
5952 
5953     // If printing assembly, use the recently updated ABI Flags information.
5954     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5955     // emitted later).
5956     getTargetStreamer().emitDirectiveModuleSoftFloat();
5957 
5958     // If this is not the end of the statement, report an error.
5959     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5960       reportParseError("unexpected token, expected end of statement");
5961       return false;
5962     }
5963 
5964     return false; // parseDirectiveModule has finished successfully.
5965   } else if (Option == "hardfloat") {
5966     clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5967 
5968     // Synchronize the ABI Flags information with the FeatureBits information we
5969     // updated above.
5970     getTargetStreamer().updateABIInfo(*this);
5971 
5972     // If printing assembly, use the recently updated ABI Flags information.
5973     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5974     // emitted later).
5975     getTargetStreamer().emitDirectiveModuleHardFloat();
5976 
5977     // If this is not the end of the statement, report an error.
5978     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5979       reportParseError("unexpected token, expected end of statement");
5980       return false;
5981     }
5982 
5983     return false; // parseDirectiveModule has finished successfully.
5984   } else {
5985     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
5986   }
5987 }
5988 
5989 /// parseDirectiveModuleFP
5990 ///  ::= =32
5991 ///  ::= =xx
5992 ///  ::= =64
5993 bool MipsAsmParser::parseDirectiveModuleFP() {
5994   MCAsmParser &Parser = getParser();
5995   MCAsmLexer &Lexer = getLexer();
5996 
5997   if (Lexer.isNot(AsmToken::Equal)) {
5998     reportParseError("unexpected token, expected equals sign '='");
5999     return false;
6000   }
6001   Parser.Lex(); // Eat '=' token.
6002 
6003   MipsABIFlagsSection::FpABIKind FpABI;
6004   if (!parseFpABIValue(FpABI, ".module"))
6005     return false;
6006 
6007   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6008     reportParseError("unexpected token, expected end of statement");
6009     return false;
6010   }
6011 
6012   // Synchronize the abiflags information with the FeatureBits information we
6013   // changed above.
6014   getTargetStreamer().updateABIInfo(*this);
6015 
6016   // If printing assembly, use the recently updated abiflags information.
6017   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
6018   // emitted at the end).
6019   getTargetStreamer().emitDirectiveModuleFP();
6020 
6021   Parser.Lex(); // Consume the EndOfStatement.
6022   return false;
6023 }
6024 
6025 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
6026                                     StringRef Directive) {
6027   MCAsmParser &Parser = getParser();
6028   MCAsmLexer &Lexer = getLexer();
6029   bool ModuleLevelOptions = Directive == ".module";
6030 
6031   if (Lexer.is(AsmToken::Identifier)) {
6032     StringRef Value = Parser.getTok().getString();
6033     Parser.Lex();
6034 
6035     if (Value != "xx") {
6036       reportParseError("unsupported value, expected 'xx', '32' or '64'");
6037       return false;
6038     }
6039 
6040     if (!isABI_O32()) {
6041       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
6042       return false;
6043     }
6044 
6045     FpABI = MipsABIFlagsSection::FpABIKind::XX;
6046     if (ModuleLevelOptions) {
6047       setModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6048       clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6049     } else {
6050       setFeatureBits(Mips::FeatureFPXX, "fpxx");
6051       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6052     }
6053     return true;
6054   }
6055 
6056   if (Lexer.is(AsmToken::Integer)) {
6057     unsigned Value = Parser.getTok().getIntVal();
6058     Parser.Lex();
6059 
6060     if (Value != 32 && Value != 64) {
6061       reportParseError("unsupported value, expected 'xx', '32' or '64'");
6062       return false;
6063     }
6064 
6065     if (Value == 32) {
6066       if (!isABI_O32()) {
6067         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
6068         return false;
6069       }
6070 
6071       FpABI = MipsABIFlagsSection::FpABIKind::S32;
6072       if (ModuleLevelOptions) {
6073         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6074         clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6075       } else {
6076         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6077         clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6078       }
6079     } else {
6080       FpABI = MipsABIFlagsSection::FpABIKind::S64;
6081       if (ModuleLevelOptions) {
6082         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6083         setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6084       } else {
6085         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6086         setFeatureBits(Mips::FeatureFP64Bit, "fp64");
6087       }
6088     }
6089 
6090     return true;
6091   }
6092 
6093   return false;
6094 }
6095 
6096 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
6097   MCAsmParser &Parser = getParser();
6098   StringRef IDVal = DirectiveID.getString();
6099 
6100   if (IDVal == ".cpload")
6101     return parseDirectiveCpLoad(DirectiveID.getLoc());
6102   if (IDVal == ".cprestore")
6103     return parseDirectiveCpRestore(DirectiveID.getLoc());
6104   if (IDVal == ".dword") {
6105     parseDataDirective(8, DirectiveID.getLoc());
6106     return false;
6107   }
6108   if (IDVal == ".ent") {
6109     StringRef SymbolName;
6110 
6111     if (Parser.parseIdentifier(SymbolName)) {
6112       reportParseError("expected identifier after .ent");
6113       return false;
6114     }
6115 
6116     // There's an undocumented extension that allows an integer to
6117     // follow the name of the procedure which AFAICS is ignored by GAS.
6118     // Example: .ent foo,2
6119     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6120       if (getLexer().isNot(AsmToken::Comma)) {
6121         // Even though we accept this undocumented extension for compatibility
6122         // reasons, the additional integer argument does not actually change
6123         // the behaviour of the '.ent' directive, so we would like to discourage
6124         // its use. We do this by not referring to the extended version in
6125         // error messages which are not directly related to its use.
6126         reportParseError("unexpected token, expected end of statement");
6127         return false;
6128       }
6129       Parser.Lex(); // Eat the comma.
6130       const MCExpr *DummyNumber;
6131       int64_t DummyNumberVal;
6132       // If the user was explicitly trying to use the extended version,
6133       // we still give helpful extension-related error messages.
6134       if (Parser.parseExpression(DummyNumber)) {
6135         reportParseError("expected number after comma");
6136         return false;
6137       }
6138       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
6139         reportParseError("expected an absolute expression after comma");
6140         return false;
6141       }
6142     }
6143 
6144     // If this is not the end of the statement, report an error.
6145     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6146       reportParseError("unexpected token, expected end of statement");
6147       return false;
6148     }
6149 
6150     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
6151 
6152     getTargetStreamer().emitDirectiveEnt(*Sym);
6153     CurrentFn = Sym;
6154     IsCpRestoreSet = false;
6155     return false;
6156   }
6157 
6158   if (IDVal == ".end") {
6159     StringRef SymbolName;
6160 
6161     if (Parser.parseIdentifier(SymbolName)) {
6162       reportParseError("expected identifier after .end");
6163       return false;
6164     }
6165 
6166     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6167       reportParseError("unexpected token, expected end of statement");
6168       return false;
6169     }
6170 
6171     if (CurrentFn == nullptr) {
6172       reportParseError(".end used without .ent");
6173       return false;
6174     }
6175 
6176     if ((SymbolName != CurrentFn->getName())) {
6177       reportParseError(".end symbol does not match .ent symbol");
6178       return false;
6179     }
6180 
6181     getTargetStreamer().emitDirectiveEnd(SymbolName);
6182     CurrentFn = nullptr;
6183     IsCpRestoreSet = false;
6184     return false;
6185   }
6186 
6187   if (IDVal == ".frame") {
6188     // .frame $stack_reg, frame_size_in_bytes, $return_reg
6189     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
6190     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
6191     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6192       reportParseError("expected stack register");
6193       return false;
6194     }
6195 
6196     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6197     if (!StackRegOpnd.isGPRAsmReg()) {
6198       reportParseError(StackRegOpnd.getStartLoc(),
6199                        "expected general purpose register");
6200       return false;
6201     }
6202     unsigned StackReg = StackRegOpnd.getGPR32Reg();
6203 
6204     if (Parser.getTok().is(AsmToken::Comma))
6205       Parser.Lex();
6206     else {
6207       reportParseError("unexpected token, expected comma");
6208       return false;
6209     }
6210 
6211     // Parse the frame size.
6212     const MCExpr *FrameSize;
6213     int64_t FrameSizeVal;
6214 
6215     if (Parser.parseExpression(FrameSize)) {
6216       reportParseError("expected frame size value");
6217       return false;
6218     }
6219 
6220     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
6221       reportParseError("frame size not an absolute expression");
6222       return false;
6223     }
6224 
6225     if (Parser.getTok().is(AsmToken::Comma))
6226       Parser.Lex();
6227     else {
6228       reportParseError("unexpected token, expected comma");
6229       return false;
6230     }
6231 
6232     // Parse the return register.
6233     TmpReg.clear();
6234     ResTy = parseAnyRegister(TmpReg);
6235     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6236       reportParseError("expected return register");
6237       return false;
6238     }
6239 
6240     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6241     if (!ReturnRegOpnd.isGPRAsmReg()) {
6242       reportParseError(ReturnRegOpnd.getStartLoc(),
6243                        "expected general purpose register");
6244       return false;
6245     }
6246 
6247     // If this is not the end of the statement, report an error.
6248     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6249       reportParseError("unexpected token, expected end of statement");
6250       return false;
6251     }
6252 
6253     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
6254                                   ReturnRegOpnd.getGPR32Reg());
6255     IsCpRestoreSet = false;
6256     return false;
6257   }
6258 
6259   if (IDVal == ".set") {
6260     return parseDirectiveSet();
6261   }
6262 
6263   if (IDVal == ".mask" || IDVal == ".fmask") {
6264     // .mask bitmask, frame_offset
6265     // bitmask: One bit for each register used.
6266     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
6267     //               first register is expected to be saved.
6268     // Examples:
6269     //   .mask 0x80000000, -4
6270     //   .fmask 0x80000000, -4
6271     //
6272 
6273     // Parse the bitmask
6274     const MCExpr *BitMask;
6275     int64_t BitMaskVal;
6276 
6277     if (Parser.parseExpression(BitMask)) {
6278       reportParseError("expected bitmask value");
6279       return false;
6280     }
6281 
6282     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
6283       reportParseError("bitmask not an absolute expression");
6284       return false;
6285     }
6286 
6287     if (Parser.getTok().is(AsmToken::Comma))
6288       Parser.Lex();
6289     else {
6290       reportParseError("unexpected token, expected comma");
6291       return false;
6292     }
6293 
6294     // Parse the frame_offset
6295     const MCExpr *FrameOffset;
6296     int64_t FrameOffsetVal;
6297 
6298     if (Parser.parseExpression(FrameOffset)) {
6299       reportParseError("expected frame offset value");
6300       return false;
6301     }
6302 
6303     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
6304       reportParseError("frame offset not an absolute expression");
6305       return false;
6306     }
6307 
6308     // If this is not the end of the statement, report an error.
6309     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6310       reportParseError("unexpected token, expected end of statement");
6311       return false;
6312     }
6313 
6314     if (IDVal == ".mask")
6315       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
6316     else
6317       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
6318     return false;
6319   }
6320 
6321   if (IDVal == ".nan")
6322     return parseDirectiveNaN();
6323 
6324   if (IDVal == ".gpword") {
6325     parseDirectiveGpWord();
6326     return false;
6327   }
6328 
6329   if (IDVal == ".gpdword") {
6330     parseDirectiveGpDWord();
6331     return false;
6332   }
6333 
6334   if (IDVal == ".word") {
6335     parseDataDirective(4, DirectiveID.getLoc());
6336     return false;
6337   }
6338 
6339   if (IDVal == ".hword") {
6340     parseDataDirective(2, DirectiveID.getLoc());
6341     return false;
6342   }
6343 
6344   if (IDVal == ".option")
6345     return parseDirectiveOption();
6346 
6347   if (IDVal == ".abicalls") {
6348     getTargetStreamer().emitDirectiveAbiCalls();
6349     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
6350       Error(Parser.getTok().getLoc(),
6351             "unexpected token, expected end of statement");
6352       // Clear line
6353       Parser.eatToEndOfStatement();
6354     }
6355     return false;
6356   }
6357 
6358   if (IDVal == ".cpsetup")
6359     return parseDirectiveCPSetup();
6360 
6361   if (IDVal == ".cpreturn")
6362     return parseDirectiveCPReturn();
6363 
6364   if (IDVal == ".module")
6365     return parseDirectiveModule();
6366 
6367   if (IDVal == ".llvm_internal_mips_reallow_module_directive")
6368     return parseInternalDirectiveReallowModule();
6369 
6370   if (IDVal == ".insn")
6371     return parseInsnDirective();
6372 
6373   if (IDVal == ".sbss")
6374     return parseSSectionDirective(IDVal, ELF::SHT_NOBITS);
6375   if (IDVal == ".sdata")
6376     return parseSSectionDirective(IDVal, ELF::SHT_PROGBITS);
6377 
6378   return true;
6379 }
6380 
6381 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
6382   // If this is not the end of the statement, report an error.
6383   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6384     reportParseError("unexpected token, expected end of statement");
6385     return false;
6386   }
6387 
6388   getTargetStreamer().reallowModuleDirective();
6389 
6390   getParser().Lex(); // Eat EndOfStatement token.
6391   return false;
6392 }
6393 
6394 extern "C" void LLVMInitializeMipsAsmParser() {
6395   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
6396   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
6397   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
6398   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
6399 }
6400 
6401 #define GET_REGISTER_MATCHER
6402 #define GET_MATCHER_IMPLEMENTATION
6403 #include "MipsGenAsmMatcher.inc"
6404