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/MipsABIFlagsSection.h"
11 #include "MCTargetDesc/MipsABIInfo.h"
12 #include "MCTargetDesc/MipsBaseInfo.h"
13 #include "MCTargetDesc/MipsMCExpr.h"
14 #include "MCTargetDesc/MipsMCTargetDesc.h"
15 #include "MipsTargetStreamer.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmLexer.h"
30 #include "llvm/MC/MCParser/MCAsmParser.h"
31 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
32 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
33 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
34 #include "llvm/MC/MCSectionELF.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCSymbolELF.h"
39 #include "llvm/MC/MCValue.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SMLoc.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstdint>
53 #include <memory>
54 #include <string>
55 #include <utility>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "mips-asm-parser"
60 
61 namespace llvm {
62 
63 class MCInstrInfo;
64 
65 } // end namespace llvm
66 
67 namespace {
68 
69 class MipsAssemblerOptions {
70 public:
71   MipsAssemblerOptions(const FeatureBitset &Features_) : Features(Features_) {}
72 
73   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
74     ATReg = Opts->getATRegIndex();
75     Reorder = Opts->isReorder();
76     Macro = Opts->isMacro();
77     Features = Opts->getFeatures();
78   }
79 
80   unsigned getATRegIndex() const { return ATReg; }
81   bool setATRegIndex(unsigned Reg) {
82     if (Reg > 31)
83       return false;
84 
85     ATReg = Reg;
86     return true;
87   }
88 
89   bool isReorder() const { return Reorder; }
90   void setReorder() { Reorder = true; }
91   void setNoReorder() { Reorder = false; }
92 
93   bool isMacro() const { return Macro; }
94   void setMacro() { Macro = true; }
95   void setNoMacro() { Macro = false; }
96 
97   const FeatureBitset &getFeatures() const { return Features; }
98   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
99 
100   // Set of features that are either architecture features or referenced
101   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
102   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
103   // The reason we need this mask is explained in the selectArch function.
104   // FIXME: Ideally we would like TableGen to generate this information.
105   static const FeatureBitset AllArchRelatedMask;
106 
107 private:
108   unsigned ATReg = 1;
109   bool Reorder = true;
110   bool Macro = true;
111   FeatureBitset Features;
112 };
113 
114 } // end anonymous namespace
115 
116 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
117     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
118     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
119     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
120     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
121     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
122     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
123     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
124     Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008
125 };
126 
127 namespace {
128 
129 class MipsAsmParser : public MCTargetAsmParser {
130   MipsTargetStreamer &getTargetStreamer() {
131     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
132     return static_cast<MipsTargetStreamer &>(TS);
133   }
134 
135   MipsABIInfo ABI;
136   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
137   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
138                        // nullptr, which indicates that no function is currently
139                        // selected. This usually happens after an '.end func'
140                        // directive.
141   bool IsLittleEndian;
142   bool IsPicEnabled;
143   bool IsCpRestoreSet;
144   int CpRestoreOffset;
145   unsigned CpSaveLocation;
146   /// If true, then CpSaveLocation is a register, otherwise it's an offset.
147   bool     CpSaveLocationIsRegister;
148 
149   // Map of register aliases created via the .set directive.
150   StringMap<AsmToken> RegisterSets;
151 
152   // Print a warning along with its fix-it message at the given range.
153   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
154                              SMRange Range, bool ShowColors = true);
155 
156   void ConvertXWPOperands(MCInst &Inst, const OperandVector &Operands);
157 
158 #define GET_ASSEMBLER_HEADER
159 #include "MipsGenAsmMatcher.inc"
160 
161   unsigned
162   checkEarlyTargetMatchPredicate(MCInst &Inst,
163                                  const OperandVector &Operands) override;
164   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
165 
166   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
167                                OperandVector &Operands, MCStreamer &Out,
168                                uint64_t &ErrorInfo,
169                                bool MatchingInlineAsm) override;
170 
171   /// Parse a register as used in CFI directives
172   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
173 
174   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
175 
176   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
177 
178   bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);
179 
180   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
181                         SMLoc NameLoc, OperandVector &Operands) override;
182 
183   bool ParseDirective(AsmToken DirectiveID) override;
184 
185   OperandMatchResultTy parseMemOperand(OperandVector &Operands);
186   OperandMatchResultTy
187   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
188                                     StringRef Identifier, SMLoc S);
189   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
190                                                      const AsmToken &Token,
191                                                      SMLoc S);
192   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
193                                                      SMLoc S);
194   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
195   OperandMatchResultTy parseImm(OperandVector &Operands);
196   OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
197   OperandMatchResultTy parseInvNum(OperandVector &Operands);
198   OperandMatchResultTy parseMovePRegPair(OperandVector &Operands);
199   OperandMatchResultTy parseRegisterList(OperandVector &Operands);
200 
201   bool searchSymbolAlias(OperandVector &Operands);
202 
203   bool parseOperand(OperandVector &, StringRef Mnemonic);
204 
205   enum MacroExpanderResultTy {
206     MER_NotAMacro,
207     MER_Success,
208     MER_Fail,
209   };
210 
211   // Expands assembly pseudo instructions.
212   MacroExpanderResultTy tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
213                                              MCStreamer &Out,
214                                              const MCSubtargetInfo *STI);
215 
216   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
217                          const MCSubtargetInfo *STI);
218 
219   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
220                      bool Is32BitImm, bool IsAddress, SMLoc IDLoc,
221                      MCStreamer &Out, const MCSubtargetInfo *STI);
222 
223   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
224                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
225                                MCStreamer &Out, const MCSubtargetInfo *STI);
226 
227   bool emitPartialAddress(MipsTargetStreamer &TOut, SMLoc IDLoc, MCSymbol *Sym);
228 
229   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
230                      MCStreamer &Out, const MCSubtargetInfo *STI);
231 
232   bool expandLoadImmReal(MCInst &Inst, bool IsSingle, bool IsGPR, bool Is64FPU,
233                          SMLoc IDLoc, MCStreamer &Out,
234                          const MCSubtargetInfo *STI);
235 
236   bool expandLoadAddress(unsigned DstReg, unsigned BaseReg,
237                          const MCOperand &Offset, bool Is32BitAddress,
238                          SMLoc IDLoc, MCStreamer &Out,
239                          const MCSubtargetInfo *STI);
240 
241   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
242                                   const MCSubtargetInfo *STI);
243 
244   void expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
245                      const MCSubtargetInfo *STI, bool IsLoad);
246 
247   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
248                                const MCSubtargetInfo *STI);
249 
250   bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
251                             const MCSubtargetInfo *STI);
252 
253   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
254                        const MCSubtargetInfo *STI);
255 
256   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
257                           const MCSubtargetInfo *STI);
258 
259   bool expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
260                     const MCSubtargetInfo *STI, const bool IsMips64,
261                     const bool Signed);
262 
263   bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc,
264                    MCStreamer &Out, const MCSubtargetInfo *STI);
265 
266   bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out,
267                  const MCSubtargetInfo *STI);
268 
269   bool expandUsh(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
270                  const MCSubtargetInfo *STI);
271 
272   bool expandUxw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
273                  const MCSubtargetInfo *STI);
274 
275   bool expandRotation(MCInst &Inst, SMLoc IDLoc,
276                       MCStreamer &Out, const MCSubtargetInfo *STI);
277   bool expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
278                          const MCSubtargetInfo *STI);
279   bool expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
280                        const MCSubtargetInfo *STI);
281   bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
282                           const MCSubtargetInfo *STI);
283 
284   bool expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
285                  const MCSubtargetInfo *STI);
286 
287   bool expandMulImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
288                     const MCSubtargetInfo *STI);
289 
290   bool expandMulO(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
291                   const MCSubtargetInfo *STI);
292 
293   bool expandMulOU(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
294                    const MCSubtargetInfo *STI);
295 
296   bool expandDMULMacro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
297                        const MCSubtargetInfo *STI);
298 
299   bool expandLoadStoreDMacro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
300                              const MCSubtargetInfo *STI, bool IsLoad);
301 
302   bool expandSeq(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
303                  const MCSubtargetInfo *STI);
304 
305   bool expandSeqI(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
306                   const MCSubtargetInfo *STI);
307 
308   bool expandMXTRAlias(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
309                        const MCSubtargetInfo *STI);
310 
311   bool reportParseError(Twine ErrorMsg);
312   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
313 
314   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
315 
316   bool isEvaluated(const MCExpr *Expr);
317   bool parseSetMips0Directive();
318   bool parseSetArchDirective();
319   bool parseSetFeature(uint64_t Feature);
320   bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup.
321   bool parseDirectiveCpLoad(SMLoc Loc);
322   bool parseDirectiveCpRestore(SMLoc Loc);
323   bool parseDirectiveCPSetup();
324   bool parseDirectiveCPReturn();
325   bool parseDirectiveNaN();
326   bool parseDirectiveSet();
327   bool parseDirectiveOption();
328   bool parseInsnDirective();
329   bool parseRSectionDirective(StringRef Section);
330   bool parseSSectionDirective(StringRef Section, unsigned Type);
331 
332   bool parseSetAtDirective();
333   bool parseSetNoAtDirective();
334   bool parseSetMacroDirective();
335   bool parseSetNoMacroDirective();
336   bool parseSetMsaDirective();
337   bool parseSetNoMsaDirective();
338   bool parseSetNoDspDirective();
339   bool parseSetReorderDirective();
340   bool parseSetNoReorderDirective();
341   bool parseSetMips16Directive();
342   bool parseSetNoMips16Directive();
343   bool parseSetFpDirective();
344   bool parseSetOddSPRegDirective();
345   bool parseSetNoOddSPRegDirective();
346   bool parseSetPopDirective();
347   bool parseSetPushDirective();
348   bool parseSetSoftFloatDirective();
349   bool parseSetHardFloatDirective();
350   bool parseSetMtDirective();
351   bool parseSetNoMtDirective();
352   bool parseSetNoCRCDirective();
353   bool parseSetNoVirtDirective();
354   bool parseSetNoGINVDirective();
355 
356   bool parseSetAssignment();
357 
358   bool parseDataDirective(unsigned Size, SMLoc L);
359   bool parseDirectiveGpWord();
360   bool parseDirectiveGpDWord();
361   bool parseDirectiveDtpRelWord();
362   bool parseDirectiveDtpRelDWord();
363   bool parseDirectiveTpRelWord();
364   bool parseDirectiveTpRelDWord();
365   bool parseDirectiveModule();
366   bool parseDirectiveModuleFP();
367   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
368                        StringRef Directive);
369 
370   bool parseInternalDirectiveReallowModule();
371 
372   bool eatComma(StringRef ErrorStr);
373 
374   int matchCPURegisterName(StringRef Symbol);
375 
376   int matchHWRegsRegisterName(StringRef Symbol);
377 
378   int matchFPURegisterName(StringRef Name);
379 
380   int matchFCCRegisterName(StringRef Name);
381 
382   int matchACRegisterName(StringRef Name);
383 
384   int matchMSA128RegisterName(StringRef Name);
385 
386   int matchMSA128CtrlRegisterName(StringRef Name);
387 
388   unsigned getReg(int RC, int RegNo);
389 
390   /// Returns the internal register number for the current AT. Also checks if
391   /// the current AT is unavailable (set to $0) and gives an error if it is.
392   /// This should be used in pseudo-instruction expansions which need AT.
393   unsigned getATReg(SMLoc Loc);
394 
395   bool canUseATReg();
396 
397   bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
398                           const MCSubtargetInfo *STI);
399 
400   // Helper function that checks if the value of a vector index is within the
401   // boundaries of accepted values for each RegisterKind
402   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
403   bool validateMSAIndex(int Val, int RegKind);
404 
405   // Selects a new architecture by updating the FeatureBits with the necessary
406   // info including implied dependencies.
407   // Internally, it clears all the feature bits related to *any* architecture
408   // and selects the new one using the ToggleFeature functionality of the
409   // MCSubtargetInfo object that handles implied dependencies. The reason we
410   // clear all the arch related bits manually is because ToggleFeature only
411   // clears the features that imply the feature being cleared and not the
412   // features implied by the feature being cleared. This is easier to see
413   // with an example:
414   //  --------------------------------------------------
415   // | Feature         | Implies                        |
416   // | -------------------------------------------------|
417   // | FeatureMips1    | None                           |
418   // | FeatureMips2    | FeatureMips1                   |
419   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
420   // | FeatureMips4    | FeatureMips3                   |
421   // | ...             |                                |
422   //  --------------------------------------------------
423   //
424   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
425   // FeatureMipsGP64 | FeatureMips1)
426   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
427   void selectArch(StringRef ArchFeature) {
428     MCSubtargetInfo &STI = copySTI();
429     FeatureBitset FeatureBits = STI.getFeatureBits();
430     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
431     STI.setFeatureBits(FeatureBits);
432     setAvailableFeatures(
433         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
434     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
435   }
436 
437   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
438     if (!(getSTI().getFeatureBits()[Feature])) {
439       MCSubtargetInfo &STI = copySTI();
440       setAvailableFeatures(
441           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
442       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
443     }
444   }
445 
446   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
447     if (getSTI().getFeatureBits()[Feature]) {
448       MCSubtargetInfo &STI = copySTI();
449       setAvailableFeatures(
450           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
451       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
452     }
453   }
454 
455   void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
456     setFeatureBits(Feature, FeatureString);
457     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
458   }
459 
460   void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
461     clearFeatureBits(Feature, FeatureString);
462     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
463   }
464 
465 public:
466   enum MipsMatchResultTy {
467     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY,
468     Match_RequiresDifferentOperands,
469     Match_RequiresNoZeroRegister,
470     Match_RequiresSameSrcAndDst,
471     Match_NoFCCRegisterForCurrentISA,
472     Match_NonZeroOperandForSync,
473     Match_NonZeroOperandForMTCX,
474     Match_RequiresPosSizeRange0_32,
475     Match_RequiresPosSizeRange33_64,
476     Match_RequiresPosSizeUImm6,
477 #define GET_OPERAND_DIAGNOSTIC_TYPES
478 #include "MipsGenAsmMatcher.inc"
479 #undef GET_OPERAND_DIAGNOSTIC_TYPES
480   };
481 
482   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
483                 const MCInstrInfo &MII, const MCTargetOptions &Options)
484     : MCTargetAsmParser(Options, sti, MII),
485         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
486                                           sti.getCPU(), Options)) {
487     MCAsmParserExtension::Initialize(parser);
488 
489     parser.addAliasForDirective(".asciiz", ".asciz");
490 
491     // Initialize the set of available features.
492     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
493 
494     // Remember the initial assembler options. The user can not modify these.
495     AssemblerOptions.push_back(
496         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
497 
498     // Create an assembler options environment for the user to modify.
499     AssemblerOptions.push_back(
500         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
501 
502     getTargetStreamer().updateABIInfo(*this);
503 
504     if (!isABI_O32() && !useOddSPReg() != 0)
505       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
506 
507     CurrentFn = nullptr;
508 
509     IsPicEnabled = getContext().getObjectFileInfo()->isPositionIndependent();
510 
511     IsCpRestoreSet = false;
512     CpRestoreOffset = -1;
513 
514     const Triple &TheTriple = sti.getTargetTriple();
515     IsLittleEndian = TheTriple.isLittleEndian();
516 
517     if (getSTI().getCPU() == "mips64r6" && inMicroMipsMode())
518       report_fatal_error("microMIPS64R6 is not supported", false);
519 
520     if (!isABI_O32() && inMicroMipsMode())
521       report_fatal_error("microMIPS64 is not supported", false);
522   }
523 
524   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
525   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
526 
527   bool isGP64bit() const {
528     return getSTI().getFeatureBits()[Mips::FeatureGP64Bit];
529   }
530 
531   bool isFP64bit() const {
532     return getSTI().getFeatureBits()[Mips::FeatureFP64Bit];
533   }
534 
535   const MipsABIInfo &getABI() const { return ABI; }
536   bool isABI_N32() const { return ABI.IsN32(); }
537   bool isABI_N64() const { return ABI.IsN64(); }
538   bool isABI_O32() const { return ABI.IsO32(); }
539   bool isABI_FPXX() const {
540     return getSTI().getFeatureBits()[Mips::FeatureFPXX];
541   }
542 
543   bool useOddSPReg() const {
544     return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]);
545   }
546 
547   bool inMicroMipsMode() const {
548     return getSTI().getFeatureBits()[Mips::FeatureMicroMips];
549   }
550 
551   bool hasMips1() const {
552     return getSTI().getFeatureBits()[Mips::FeatureMips1];
553   }
554 
555   bool hasMips2() const {
556     return getSTI().getFeatureBits()[Mips::FeatureMips2];
557   }
558 
559   bool hasMips3() const {
560     return getSTI().getFeatureBits()[Mips::FeatureMips3];
561   }
562 
563   bool hasMips4() const {
564     return getSTI().getFeatureBits()[Mips::FeatureMips4];
565   }
566 
567   bool hasMips5() const {
568     return getSTI().getFeatureBits()[Mips::FeatureMips5];
569   }
570 
571   bool hasMips32() const {
572     return getSTI().getFeatureBits()[Mips::FeatureMips32];
573   }
574 
575   bool hasMips64() const {
576     return getSTI().getFeatureBits()[Mips::FeatureMips64];
577   }
578 
579   bool hasMips32r2() const {
580     return getSTI().getFeatureBits()[Mips::FeatureMips32r2];
581   }
582 
583   bool hasMips64r2() const {
584     return getSTI().getFeatureBits()[Mips::FeatureMips64r2];
585   }
586 
587   bool hasMips32r3() const {
588     return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]);
589   }
590 
591   bool hasMips64r3() const {
592     return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]);
593   }
594 
595   bool hasMips32r5() const {
596     return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]);
597   }
598 
599   bool hasMips64r5() const {
600     return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]);
601   }
602 
603   bool hasMips32r6() const {
604     return getSTI().getFeatureBits()[Mips::FeatureMips32r6];
605   }
606 
607   bool hasMips64r6() const {
608     return getSTI().getFeatureBits()[Mips::FeatureMips64r6];
609   }
610 
611   bool hasDSP() const {
612     return getSTI().getFeatureBits()[Mips::FeatureDSP];
613   }
614 
615   bool hasDSPR2() const {
616     return getSTI().getFeatureBits()[Mips::FeatureDSPR2];
617   }
618 
619   bool hasDSPR3() const {
620     return getSTI().getFeatureBits()[Mips::FeatureDSPR3];
621   }
622 
623   bool hasMSA() const {
624     return getSTI().getFeatureBits()[Mips::FeatureMSA];
625   }
626 
627   bool hasCnMips() const {
628     return (getSTI().getFeatureBits()[Mips::FeatureCnMips]);
629   }
630 
631   bool inPicMode() {
632     return IsPicEnabled;
633   }
634 
635   bool inMips16Mode() const {
636     return getSTI().getFeatureBits()[Mips::FeatureMips16];
637   }
638 
639   bool useTraps() const {
640     return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV];
641   }
642 
643   bool useSoftFloat() const {
644     return getSTI().getFeatureBits()[Mips::FeatureSoftFloat];
645   }
646   bool hasMT() const {
647     return getSTI().getFeatureBits()[Mips::FeatureMT];
648   }
649 
650   bool hasCRC() const {
651     return getSTI().getFeatureBits()[Mips::FeatureCRC];
652   }
653 
654   bool hasVirt() const {
655     return getSTI().getFeatureBits()[Mips::FeatureVirt];
656   }
657 
658   bool hasGINV() const {
659     return getSTI().getFeatureBits()[Mips::FeatureGINV];
660   }
661 
662   /// Warn if RegIndex is the same as the current AT.
663   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
664 
665   void warnIfNoMacro(SMLoc Loc);
666 
667   bool isLittle() const { return IsLittleEndian; }
668 
669   const MCExpr *createTargetUnaryExpr(const MCExpr *E,
670                                       AsmToken::TokenKind OperatorToken,
671                                       MCContext &Ctx) override {
672     switch(OperatorToken) {
673     default:
674       llvm_unreachable("Unknown token");
675       return nullptr;
676     case AsmToken::PercentCall16:
677       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, E, Ctx);
678     case AsmToken::PercentCall_Hi:
679       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_HI16, E, Ctx);
680     case AsmToken::PercentCall_Lo:
681       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_LO16, E, Ctx);
682     case AsmToken::PercentDtprel_Hi:
683       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_HI, E, Ctx);
684     case AsmToken::PercentDtprel_Lo:
685       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_LO, E, Ctx);
686     case AsmToken::PercentGot:
687       return MipsMCExpr::create(MipsMCExpr::MEK_GOT, E, Ctx);
688     case AsmToken::PercentGot_Disp:
689       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, E, Ctx);
690     case AsmToken::PercentGot_Hi:
691       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_HI16, E, Ctx);
692     case AsmToken::PercentGot_Lo:
693       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_LO16, E, Ctx);
694     case AsmToken::PercentGot_Ofst:
695       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_OFST, E, Ctx);
696     case AsmToken::PercentGot_Page:
697       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_PAGE, E, Ctx);
698     case AsmToken::PercentGottprel:
699       return MipsMCExpr::create(MipsMCExpr::MEK_GOTTPREL, E, Ctx);
700     case AsmToken::PercentGp_Rel:
701       return MipsMCExpr::create(MipsMCExpr::MEK_GPREL, E, Ctx);
702     case AsmToken::PercentHi:
703       return MipsMCExpr::create(MipsMCExpr::MEK_HI, E, Ctx);
704     case AsmToken::PercentHigher:
705       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, E, Ctx);
706     case AsmToken::PercentHighest:
707       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, E, Ctx);
708     case AsmToken::PercentLo:
709       return MipsMCExpr::create(MipsMCExpr::MEK_LO, E, Ctx);
710     case AsmToken::PercentNeg:
711       return MipsMCExpr::create(MipsMCExpr::MEK_NEG, E, Ctx);
712     case AsmToken::PercentPcrel_Hi:
713       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_HI16, E, Ctx);
714     case AsmToken::PercentPcrel_Lo:
715       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_LO16, E, Ctx);
716     case AsmToken::PercentTlsgd:
717       return MipsMCExpr::create(MipsMCExpr::MEK_TLSGD, E, Ctx);
718     case AsmToken::PercentTlsldm:
719       return MipsMCExpr::create(MipsMCExpr::MEK_TLSLDM, E, Ctx);
720     case AsmToken::PercentTprel_Hi:
721       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_HI, E, Ctx);
722     case AsmToken::PercentTprel_Lo:
723       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_LO, E, Ctx);
724     }
725   }
726 };
727 
728 /// MipsOperand - Instances of this class represent a parsed Mips machine
729 /// instruction.
730 class MipsOperand : public MCParsedAsmOperand {
731 public:
732   /// Broad categories of register classes
733   /// The exact class is finalized by the render method.
734   enum RegKind {
735     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
736     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
737                           /// isFP64bit())
738     RegKind_FCC = 4,      /// FCC
739     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
740     RegKind_MSACtrl = 16, /// MSA control registers
741     RegKind_COP2 = 32,    /// COP2
742     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
743                           /// context).
744     RegKind_CCR = 128,    /// CCR
745     RegKind_HWRegs = 256, /// HWRegs
746     RegKind_COP3 = 512,   /// COP3
747     RegKind_COP0 = 1024,  /// COP0
748     /// Potentially any (e.g. $1)
749     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
750                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
751                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
752   };
753 
754 private:
755   enum KindTy {
756     k_Immediate,     /// An immediate (possibly involving symbol references)
757     k_Memory,        /// Base + Offset Memory Address
758     k_RegisterIndex, /// A register index in one or more RegKind.
759     k_Token,         /// A simple token
760     k_RegList,       /// A physical register list
761     k_RegPair        /// A pair of physical register
762   } Kind;
763 
764 public:
765   MipsOperand(KindTy K, MipsAsmParser &Parser)
766       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
767 
768   ~MipsOperand() override {
769     switch (Kind) {
770     case k_Immediate:
771       break;
772     case k_Memory:
773       delete Mem.Base;
774       break;
775     case k_RegList:
776       delete RegList.List;
777     case k_RegisterIndex:
778     case k_Token:
779     case k_RegPair:
780       break;
781     }
782   }
783 
784 private:
785   /// For diagnostics, and checking the assembler temporary
786   MipsAsmParser &AsmParser;
787 
788   struct Token {
789     const char *Data;
790     unsigned Length;
791   };
792 
793   struct RegIdxOp {
794     unsigned Index; /// Index into the register class
795     RegKind Kind;   /// Bitfield of the kinds it could possibly be
796     struct Token Tok; /// The input token this operand originated from.
797     const MCRegisterInfo *RegInfo;
798   };
799 
800   struct ImmOp {
801     const MCExpr *Val;
802   };
803 
804   struct MemOp {
805     MipsOperand *Base;
806     const MCExpr *Off;
807   };
808 
809   struct RegListOp {
810     SmallVector<unsigned, 10> *List;
811   };
812 
813   union {
814     struct Token Tok;
815     struct RegIdxOp RegIdx;
816     struct ImmOp Imm;
817     struct MemOp Mem;
818     struct RegListOp RegList;
819   };
820 
821   SMLoc StartLoc, EndLoc;
822 
823   /// Internal constructor for register kinds
824   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, StringRef Str,
825                                                 RegKind RegKind,
826                                                 const MCRegisterInfo *RegInfo,
827                                                 SMLoc S, SMLoc E,
828                                                 MipsAsmParser &Parser) {
829     auto Op = llvm::make_unique<MipsOperand>(k_RegisterIndex, Parser);
830     Op->RegIdx.Index = Index;
831     Op->RegIdx.RegInfo = RegInfo;
832     Op->RegIdx.Kind = RegKind;
833     Op->RegIdx.Tok.Data = Str.data();
834     Op->RegIdx.Tok.Length = Str.size();
835     Op->StartLoc = S;
836     Op->EndLoc = E;
837     return Op;
838   }
839 
840 public:
841   /// Coerce the register to GPR32 and return the real register for the current
842   /// target.
843   unsigned getGPR32Reg() const {
844     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
845     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
846     unsigned ClassID = Mips::GPR32RegClassID;
847     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
848   }
849 
850   /// Coerce the register to GPR32 and return the real register for the current
851   /// target.
852   unsigned getGPRMM16Reg() const {
853     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
854     unsigned ClassID = Mips::GPR32RegClassID;
855     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
856   }
857 
858   /// Coerce the register to GPR64 and return the real register for the current
859   /// target.
860   unsigned getGPR64Reg() const {
861     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
862     unsigned ClassID = Mips::GPR64RegClassID;
863     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
864   }
865 
866 private:
867   /// Coerce the register to AFGR64 and return the real register for the current
868   /// target.
869   unsigned getAFGR64Reg() const {
870     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
871     if (RegIdx.Index % 2 != 0)
872       AsmParser.Warning(StartLoc, "Float register should be even.");
873     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
874         .getRegister(RegIdx.Index / 2);
875   }
876 
877   /// Coerce the register to FGR64 and return the real register for the current
878   /// target.
879   unsigned getFGR64Reg() const {
880     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
881     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
882         .getRegister(RegIdx.Index);
883   }
884 
885   /// Coerce the register to FGR32 and return the real register for the current
886   /// target.
887   unsigned getFGR32Reg() const {
888     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
889     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
890         .getRegister(RegIdx.Index);
891   }
892 
893   /// Coerce the register to FGRH32 and return the real register for the current
894   /// target.
895   unsigned getFGRH32Reg() const {
896     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
897     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
898         .getRegister(RegIdx.Index);
899   }
900 
901   /// Coerce the register to FCC and return the real register for the current
902   /// target.
903   unsigned getFCCReg() const {
904     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
905     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
906         .getRegister(RegIdx.Index);
907   }
908 
909   /// Coerce the register to MSA128 and return the real register for the current
910   /// target.
911   unsigned getMSA128Reg() const {
912     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
913     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
914     // identical
915     unsigned ClassID = Mips::MSA128BRegClassID;
916     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
917   }
918 
919   /// Coerce the register to MSACtrl and return the real register for the
920   /// current target.
921   unsigned getMSACtrlReg() const {
922     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
923     unsigned ClassID = Mips::MSACtrlRegClassID;
924     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
925   }
926 
927   /// Coerce the register to COP0 and return the real register for the
928   /// current target.
929   unsigned getCOP0Reg() const {
930     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
931     unsigned ClassID = Mips::COP0RegClassID;
932     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
933   }
934 
935   /// Coerce the register to COP2 and return the real register for the
936   /// current target.
937   unsigned getCOP2Reg() const {
938     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
939     unsigned ClassID = Mips::COP2RegClassID;
940     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
941   }
942 
943   /// Coerce the register to COP3 and return the real register for the
944   /// current target.
945   unsigned getCOP3Reg() const {
946     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
947     unsigned ClassID = Mips::COP3RegClassID;
948     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
949   }
950 
951   /// Coerce the register to ACC64DSP and return the real register for the
952   /// current target.
953   unsigned getACC64DSPReg() const {
954     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
955     unsigned ClassID = Mips::ACC64DSPRegClassID;
956     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
957   }
958 
959   /// Coerce the register to HI32DSP and return the real register for the
960   /// current target.
961   unsigned getHI32DSPReg() const {
962     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
963     unsigned ClassID = Mips::HI32DSPRegClassID;
964     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
965   }
966 
967   /// Coerce the register to LO32DSP and return the real register for the
968   /// current target.
969   unsigned getLO32DSPReg() const {
970     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
971     unsigned ClassID = Mips::LO32DSPRegClassID;
972     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
973   }
974 
975   /// Coerce the register to CCR and return the real register for the
976   /// current target.
977   unsigned getCCRReg() const {
978     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
979     unsigned ClassID = Mips::CCRRegClassID;
980     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
981   }
982 
983   /// Coerce the register to HWRegs and return the real register for the
984   /// current target.
985   unsigned getHWRegsReg() const {
986     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
987     unsigned ClassID = Mips::HWRegsRegClassID;
988     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
989   }
990 
991 public:
992   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
993     // Add as immediate when possible.  Null MCExpr = 0.
994     if (!Expr)
995       Inst.addOperand(MCOperand::createImm(0));
996     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
997       Inst.addOperand(MCOperand::createImm(CE->getValue()));
998     else
999       Inst.addOperand(MCOperand::createExpr(Expr));
1000   }
1001 
1002   void addRegOperands(MCInst &Inst, unsigned N) const {
1003     llvm_unreachable("Use a custom parser instead");
1004   }
1005 
1006   /// Render the operand to an MCInst as a GPR32
1007   /// Asserts if the wrong number of operands are requested, or the operand
1008   /// is not a k_RegisterIndex compatible with RegKind_GPR
1009   void addGPR32ZeroAsmRegOperands(MCInst &Inst, unsigned N) const {
1010     assert(N == 1 && "Invalid number of operands!");
1011     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
1012   }
1013 
1014   void addGPR32NonZeroAsmRegOperands(MCInst &Inst, unsigned N) const {
1015     assert(N == 1 && "Invalid number of operands!");
1016     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
1017   }
1018 
1019   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
1020     assert(N == 1 && "Invalid number of operands!");
1021     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
1022   }
1023 
1024   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
1025     assert(N == 1 && "Invalid number of operands!");
1026     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1027   }
1028 
1029   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
1030     assert(N == 1 && "Invalid number of operands!");
1031     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1032   }
1033 
1034   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
1035     assert(N == 1 && "Invalid number of operands!");
1036     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1037   }
1038 
1039   /// Render the operand to an MCInst as a GPR64
1040   /// Asserts if the wrong number of operands are requested, or the operand
1041   /// is not a k_RegisterIndex compatible with RegKind_GPR
1042   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1043     assert(N == 1 && "Invalid number of operands!");
1044     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
1045   }
1046 
1047   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1048     assert(N == 1 && "Invalid number of operands!");
1049     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
1050   }
1051 
1052   void addStrictlyAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1053     assert(N == 1 && "Invalid number of operands!");
1054     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
1055   }
1056 
1057   void addStrictlyFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1058     assert(N == 1 && "Invalid number of operands!");
1059     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
1060   }
1061 
1062   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1063     assert(N == 1 && "Invalid number of operands!");
1064     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
1065   }
1066 
1067   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
1068     assert(N == 1 && "Invalid number of operands!");
1069     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
1070     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
1071     // FIXME: This should propagate failure up to parseStatement.
1072     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
1073       AsmParser.getParser().printError(
1074           StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
1075                     "registers");
1076   }
1077 
1078   void addStrictlyFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
1079     assert(N == 1 && "Invalid number of operands!");
1080     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
1081     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
1082     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
1083       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
1084                                 "registers");
1085   }
1086 
1087   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
1088     assert(N == 1 && "Invalid number of operands!");
1089     Inst.addOperand(MCOperand::createReg(getFGRH32Reg()));
1090   }
1091 
1092   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
1093     assert(N == 1 && "Invalid number of operands!");
1094     Inst.addOperand(MCOperand::createReg(getFCCReg()));
1095   }
1096 
1097   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
1098     assert(N == 1 && "Invalid number of operands!");
1099     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
1100   }
1101 
1102   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
1103     assert(N == 1 && "Invalid number of operands!");
1104     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
1105   }
1106 
1107   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
1108     assert(N == 1 && "Invalid number of operands!");
1109     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
1110   }
1111 
1112   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
1113     assert(N == 1 && "Invalid number of operands!");
1114     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
1115   }
1116 
1117   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
1118     assert(N == 1 && "Invalid number of operands!");
1119     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
1120   }
1121 
1122   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
1123     assert(N == 1 && "Invalid number of operands!");
1124     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
1125   }
1126 
1127   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
1128     assert(N == 1 && "Invalid number of operands!");
1129     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
1130   }
1131 
1132   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
1133     assert(N == 1 && "Invalid number of operands!");
1134     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
1135   }
1136 
1137   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
1138     assert(N == 1 && "Invalid number of operands!");
1139     Inst.addOperand(MCOperand::createReg(getCCRReg()));
1140   }
1141 
1142   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
1143     assert(N == 1 && "Invalid number of operands!");
1144     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
1145   }
1146 
1147   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
1148   void addConstantUImmOperands(MCInst &Inst, unsigned N) const {
1149     assert(N == 1 && "Invalid number of operands!");
1150     uint64_t Imm = getConstantImm() - Offset;
1151     Imm &= (1ULL << Bits) - 1;
1152     Imm += Offset;
1153     Imm += AdjustOffset;
1154     Inst.addOperand(MCOperand::createImm(Imm));
1155   }
1156 
1157   template <unsigned Bits>
1158   void addSImmOperands(MCInst &Inst, unsigned N) const {
1159     if (isImm() && !isConstantImm()) {
1160       addExpr(Inst, getImm());
1161       return;
1162     }
1163     addConstantSImmOperands<Bits, 0, 0>(Inst, N);
1164   }
1165 
1166   template <unsigned Bits>
1167   void addUImmOperands(MCInst &Inst, unsigned N) const {
1168     if (isImm() && !isConstantImm()) {
1169       addExpr(Inst, getImm());
1170       return;
1171     }
1172     addConstantUImmOperands<Bits, 0, 0>(Inst, N);
1173   }
1174 
1175   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
1176   void addConstantSImmOperands(MCInst &Inst, unsigned N) const {
1177     assert(N == 1 && "Invalid number of operands!");
1178     int64_t Imm = getConstantImm() - Offset;
1179     Imm = SignExtend64<Bits>(Imm);
1180     Imm += Offset;
1181     Imm += AdjustOffset;
1182     Inst.addOperand(MCOperand::createImm(Imm));
1183   }
1184 
1185   void addImmOperands(MCInst &Inst, unsigned N) const {
1186     assert(N == 1 && "Invalid number of operands!");
1187     const MCExpr *Expr = getImm();
1188     addExpr(Inst, Expr);
1189   }
1190 
1191   void addMemOperands(MCInst &Inst, unsigned N) const {
1192     assert(N == 2 && "Invalid number of operands!");
1193 
1194     Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit()
1195                                              ? getMemBase()->getGPR64Reg()
1196                                              : getMemBase()->getGPR32Reg()));
1197 
1198     const MCExpr *Expr = getMemOff();
1199     addExpr(Inst, Expr);
1200   }
1201 
1202   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
1203     assert(N == 2 && "Invalid number of operands!");
1204 
1205     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
1206 
1207     const MCExpr *Expr = getMemOff();
1208     addExpr(Inst, Expr);
1209   }
1210 
1211   void addRegListOperands(MCInst &Inst, unsigned N) const {
1212     assert(N == 1 && "Invalid number of operands!");
1213 
1214     for (auto RegNo : getRegList())
1215       Inst.addOperand(MCOperand::createReg(RegNo));
1216   }
1217 
1218   void addRegPairOperands(MCInst &Inst, unsigned N) const {
1219     assert(N == 2 && "Invalid number of operands!");
1220     assert((RegIdx.Kind & RegKind_GPR) && "Invalid access!");
1221     unsigned RegNo = getRegPair();
1222     AsmParser.warnIfRegIndexIsAT(RegNo, StartLoc);
1223     Inst.addOperand(MCOperand::createReg(
1224       RegIdx.RegInfo->getRegClass(
1225         AsmParser.getABI().AreGprs64bit()
1226           ? Mips::GPR64RegClassID
1227           : Mips::GPR32RegClassID).getRegister(RegNo++)));
1228     Inst.addOperand(MCOperand::createReg(
1229       RegIdx.RegInfo->getRegClass(
1230         AsmParser.getABI().AreGprs64bit()
1231           ? Mips::GPR64RegClassID
1232           : Mips::GPR32RegClassID).getRegister(RegNo)));
1233   }
1234 
1235   void addMovePRegPairOperands(MCInst &Inst, unsigned N) const {
1236     assert(N == 2 && "Invalid number of operands!");
1237     for (auto RegNo : getRegList())
1238       Inst.addOperand(MCOperand::createReg(RegNo));
1239   }
1240 
1241   bool isReg() const override {
1242     // As a special case until we sort out the definition of div/divu, accept
1243     // $0/$zero here so that MCK_ZERO works correctly.
1244     return isGPRAsmReg() && RegIdx.Index == 0;
1245   }
1246 
1247   bool isRegIdx() const { return Kind == k_RegisterIndex; }
1248   bool isImm() const override { return Kind == k_Immediate; }
1249 
1250   bool isConstantImm() const {
1251     int64_t Res;
1252     return isImm() && getImm()->evaluateAsAbsolute(Res);
1253   }
1254 
1255   bool isConstantImmz() const {
1256     return isConstantImm() && getConstantImm() == 0;
1257   }
1258 
1259   template <unsigned Bits, int Offset = 0> bool isConstantUImm() const {
1260     return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset);
1261   }
1262 
1263   template <unsigned Bits> bool isSImm() const {
1264     return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm();
1265   }
1266 
1267   template <unsigned Bits> bool isUImm() const {
1268     return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm();
1269   }
1270 
1271   template <unsigned Bits> bool isAnyImm() const {
1272     return isConstantImm() ? (isInt<Bits>(getConstantImm()) ||
1273                               isUInt<Bits>(getConstantImm()))
1274                            : isImm();
1275   }
1276 
1277   template <unsigned Bits, int Offset = 0> bool isConstantSImm() const {
1278     return isConstantImm() && isInt<Bits>(getConstantImm() - Offset);
1279   }
1280 
1281   template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const {
1282     return isConstantImm() && getConstantImm() >= Bottom &&
1283            getConstantImm() <= Top;
1284   }
1285 
1286   bool isToken() const override {
1287     // Note: It's not possible to pretend that other operand kinds are tokens.
1288     // The matcher emitter checks tokens first.
1289     return Kind == k_Token;
1290   }
1291 
1292   bool isMem() const override { return Kind == k_Memory; }
1293 
1294   bool isConstantMemOff() const {
1295     return isMem() && isa<MCConstantExpr>(getMemOff());
1296   }
1297 
1298   // Allow relocation operators.
1299   // FIXME: This predicate and others need to look through binary expressions
1300   //        and determine whether a Value is a constant or not.
1301   template <unsigned Bits, unsigned ShiftAmount = 0>
1302   bool isMemWithSimmOffset() const {
1303     if (!isMem())
1304       return false;
1305     if (!getMemBase()->isGPRAsmReg())
1306       return false;
1307     if (isa<MCTargetExpr>(getMemOff()) ||
1308         (isConstantMemOff() &&
1309          isShiftedInt<Bits, ShiftAmount>(getConstantMemOff())))
1310       return true;
1311     MCValue Res;
1312     bool IsReloc = getMemOff()->evaluateAsRelocatable(Res, nullptr, nullptr);
1313     return IsReloc && isShiftedInt<Bits, ShiftAmount>(Res.getConstant());
1314   }
1315 
1316   bool isMemWithPtrSizeOffset() const {
1317     if (!isMem())
1318       return false;
1319     if (!getMemBase()->isGPRAsmReg())
1320       return false;
1321     const unsigned PtrBits = AsmParser.getABI().ArePtrs64bit() ? 64 : 32;
1322     if (isa<MCTargetExpr>(getMemOff()) ||
1323         (isConstantMemOff() && isIntN(PtrBits, getConstantMemOff())))
1324       return true;
1325     MCValue Res;
1326     bool IsReloc = getMemOff()->evaluateAsRelocatable(Res, nullptr, nullptr);
1327     return IsReloc && isIntN(PtrBits, Res.getConstant());
1328   }
1329 
1330   bool isMemWithGRPMM16Base() const {
1331     return isMem() && getMemBase()->isMM16AsmReg();
1332   }
1333 
1334   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
1335     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1336       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
1337   }
1338 
1339   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
1340     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1341       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1342       && (getMemBase()->getGPR32Reg() == Mips::SP);
1343   }
1344 
1345   template <unsigned Bits> bool isMemWithSimmWordAlignedOffsetGP() const {
1346     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff())
1347       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1348       && (getMemBase()->getGPR32Reg() == Mips::GP);
1349   }
1350 
1351   template <unsigned Bits, unsigned ShiftLeftAmount>
1352   bool isScaledUImm() const {
1353     return isConstantImm() &&
1354            isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm());
1355   }
1356 
1357   template <unsigned Bits, unsigned ShiftLeftAmount>
1358   bool isScaledSImm() const {
1359     if (isConstantImm() &&
1360         isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm()))
1361       return true;
1362     // Operand can also be a symbol or symbol plus
1363     // offset in case of relocations.
1364     if (Kind != k_Immediate)
1365       return false;
1366     MCValue Res;
1367     bool Success = getImm()->evaluateAsRelocatable(Res, nullptr, nullptr);
1368     return Success && isShiftedInt<Bits, ShiftLeftAmount>(Res.getConstant());
1369   }
1370 
1371   bool isRegList16() const {
1372     if (!isRegList())
1373       return false;
1374 
1375     int Size = RegList.List->size();
1376     if (Size < 2 || Size > 5)
1377       return false;
1378 
1379     unsigned R0 = RegList.List->front();
1380     unsigned R1 = RegList.List->back();
1381     if (!((R0 == Mips::S0 && R1 == Mips::RA) ||
1382           (R0 == Mips::S0_64 && R1 == Mips::RA_64)))
1383       return false;
1384 
1385     int PrevReg = *RegList.List->begin();
1386     for (int i = 1; i < Size - 1; i++) {
1387       int Reg = (*(RegList.List))[i];
1388       if ( Reg != PrevReg + 1)
1389         return false;
1390       PrevReg = Reg;
1391     }
1392 
1393     return true;
1394   }
1395 
1396   bool isInvNum() const { return Kind == k_Immediate; }
1397 
1398   bool isLSAImm() const {
1399     if (!isConstantImm())
1400       return false;
1401     int64_t Val = getConstantImm();
1402     return 1 <= Val && Val <= 4;
1403   }
1404 
1405   bool isRegList() const { return Kind == k_RegList; }
1406 
1407   bool isMovePRegPair() const {
1408     if (Kind != k_RegList || RegList.List->size() != 2)
1409       return false;
1410 
1411     unsigned R0 = RegList.List->front();
1412     unsigned R1 = RegList.List->back();
1413 
1414     if ((R0 == Mips::A1 && R1 == Mips::A2) ||
1415         (R0 == Mips::A1 && R1 == Mips::A3) ||
1416         (R0 == Mips::A2 && R1 == Mips::A3) ||
1417         (R0 == Mips::A0 && R1 == Mips::S5) ||
1418         (R0 == Mips::A0 && R1 == Mips::S6) ||
1419         (R0 == Mips::A0 && R1 == Mips::A1) ||
1420         (R0 == Mips::A0 && R1 == Mips::A2) ||
1421         (R0 == Mips::A0 && R1 == Mips::A3) ||
1422         (R0 == Mips::A1_64 && R1 == Mips::A2_64) ||
1423         (R0 == Mips::A1_64 && R1 == Mips::A3_64) ||
1424         (R0 == Mips::A2_64 && R1 == Mips::A3_64) ||
1425         (R0 == Mips::A0_64 && R1 == Mips::S5_64) ||
1426         (R0 == Mips::A0_64 && R1 == Mips::S6_64) ||
1427         (R0 == Mips::A0_64 && R1 == Mips::A1_64) ||
1428         (R0 == Mips::A0_64 && R1 == Mips::A2_64) ||
1429         (R0 == Mips::A0_64 && R1 == Mips::A3_64))
1430       return true;
1431 
1432     return false;
1433   }
1434 
1435   StringRef getToken() const {
1436     assert(Kind == k_Token && "Invalid access!");
1437     return StringRef(Tok.Data, Tok.Length);
1438   }
1439 
1440   unsigned getReg() const override {
1441     // As a special case until we sort out the definition of div/divu, accept
1442     // $0/$zero here so that MCK_ZERO works correctly.
1443     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1444         RegIdx.Kind & RegKind_GPR)
1445       return getGPR32Reg(); // FIXME: GPR64 too
1446 
1447     llvm_unreachable("Invalid access!");
1448     return 0;
1449   }
1450 
1451   const MCExpr *getImm() const {
1452     assert((Kind == k_Immediate) && "Invalid access!");
1453     return Imm.Val;
1454   }
1455 
1456   int64_t getConstantImm() const {
1457     const MCExpr *Val = getImm();
1458     int64_t Value = 0;
1459     (void)Val->evaluateAsAbsolute(Value);
1460     return Value;
1461   }
1462 
1463   MipsOperand *getMemBase() const {
1464     assert((Kind == k_Memory) && "Invalid access!");
1465     return Mem.Base;
1466   }
1467 
1468   const MCExpr *getMemOff() const {
1469     assert((Kind == k_Memory) && "Invalid access!");
1470     return Mem.Off;
1471   }
1472 
1473   int64_t getConstantMemOff() const {
1474     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1475   }
1476 
1477   const SmallVectorImpl<unsigned> &getRegList() const {
1478     assert((Kind == k_RegList) && "Invalid access!");
1479     return *(RegList.List);
1480   }
1481 
1482   unsigned getRegPair() const {
1483     assert((Kind == k_RegPair) && "Invalid access!");
1484     return RegIdx.Index;
1485   }
1486 
1487   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1488                                                   MipsAsmParser &Parser) {
1489     auto Op = llvm::make_unique<MipsOperand>(k_Token, Parser);
1490     Op->Tok.Data = Str.data();
1491     Op->Tok.Length = Str.size();
1492     Op->StartLoc = S;
1493     Op->EndLoc = S;
1494     return Op;
1495   }
1496 
1497   /// Create a numeric register (e.g. $1). The exact register remains
1498   /// unresolved until an instruction successfully matches
1499   static std::unique_ptr<MipsOperand>
1500   createNumericReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1501                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1502     LLVM_DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1503     return CreateReg(Index, Str, RegKind_Numeric, RegInfo, S, E, Parser);
1504   }
1505 
1506   /// Create a register that is definitely a GPR.
1507   /// This is typically only used for named registers such as $gp.
1508   static std::unique_ptr<MipsOperand>
1509   createGPRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1510                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1511     return CreateReg(Index, Str, RegKind_GPR, RegInfo, S, E, Parser);
1512   }
1513 
1514   /// Create a register that is definitely a FGR.
1515   /// This is typically only used for named registers such as $f0.
1516   static std::unique_ptr<MipsOperand>
1517   createFGRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1518                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1519     return CreateReg(Index, Str, RegKind_FGR, RegInfo, S, E, Parser);
1520   }
1521 
1522   /// Create a register that is definitely a HWReg.
1523   /// This is typically only used for named registers such as $hwr_cpunum.
1524   static std::unique_ptr<MipsOperand>
1525   createHWRegsReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1526                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1527     return CreateReg(Index, Str, RegKind_HWRegs, RegInfo, S, E, Parser);
1528   }
1529 
1530   /// Create a register that is definitely an FCC.
1531   /// This is typically only used for named registers such as $fcc0.
1532   static std::unique_ptr<MipsOperand>
1533   createFCCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1534                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1535     return CreateReg(Index, Str, RegKind_FCC, RegInfo, S, E, Parser);
1536   }
1537 
1538   /// Create a register that is definitely an ACC.
1539   /// This is typically only used for named registers such as $ac0.
1540   static std::unique_ptr<MipsOperand>
1541   createACCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1542                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1543     return CreateReg(Index, Str, RegKind_ACC, RegInfo, S, E, Parser);
1544   }
1545 
1546   /// Create a register that is definitely an MSA128.
1547   /// This is typically only used for named registers such as $w0.
1548   static std::unique_ptr<MipsOperand>
1549   createMSA128Reg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1550                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1551     return CreateReg(Index, Str, RegKind_MSA128, RegInfo, S, E, Parser);
1552   }
1553 
1554   /// Create a register that is definitely an MSACtrl.
1555   /// This is typically only used for named registers such as $msaaccess.
1556   static std::unique_ptr<MipsOperand>
1557   createMSACtrlReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1558                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1559     return CreateReg(Index, Str, RegKind_MSACtrl, RegInfo, S, E, Parser);
1560   }
1561 
1562   static std::unique_ptr<MipsOperand>
1563   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1564     auto Op = llvm::make_unique<MipsOperand>(k_Immediate, Parser);
1565     Op->Imm.Val = Val;
1566     Op->StartLoc = S;
1567     Op->EndLoc = E;
1568     return Op;
1569   }
1570 
1571   static std::unique_ptr<MipsOperand>
1572   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1573             SMLoc E, MipsAsmParser &Parser) {
1574     auto Op = llvm::make_unique<MipsOperand>(k_Memory, Parser);
1575     Op->Mem.Base = Base.release();
1576     Op->Mem.Off = Off;
1577     Op->StartLoc = S;
1578     Op->EndLoc = E;
1579     return Op;
1580   }
1581 
1582   static std::unique_ptr<MipsOperand>
1583   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1584                 MipsAsmParser &Parser) {
1585     assert(Regs.size() > 0 && "Empty list not allowed");
1586 
1587     auto Op = llvm::make_unique<MipsOperand>(k_RegList, Parser);
1588     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1589     Op->StartLoc = StartLoc;
1590     Op->EndLoc = EndLoc;
1591     return Op;
1592   }
1593 
1594   static std::unique_ptr<MipsOperand> CreateRegPair(const MipsOperand &MOP,
1595                                                     SMLoc S, SMLoc E,
1596                                                     MipsAsmParser &Parser) {
1597     auto Op = llvm::make_unique<MipsOperand>(k_RegPair, Parser);
1598     Op->RegIdx.Index = MOP.RegIdx.Index;
1599     Op->RegIdx.RegInfo = MOP.RegIdx.RegInfo;
1600     Op->RegIdx.Kind = MOP.RegIdx.Kind;
1601     Op->StartLoc = S;
1602     Op->EndLoc = E;
1603     return Op;
1604   }
1605 
1606  bool isGPRZeroAsmReg() const {
1607     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index == 0;
1608   }
1609 
1610  bool isGPRNonZeroAsmReg() const {
1611    return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index > 0 &&
1612           RegIdx.Index <= 31;
1613   }
1614 
1615   bool isGPRAsmReg() const {
1616     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1617   }
1618 
1619   bool isMM16AsmReg() const {
1620     if (!(isRegIdx() && RegIdx.Kind))
1621       return false;
1622     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1623             || RegIdx.Index == 16 || RegIdx.Index == 17);
1624 
1625   }
1626   bool isMM16AsmRegZero() const {
1627     if (!(isRegIdx() && RegIdx.Kind))
1628       return false;
1629     return (RegIdx.Index == 0 ||
1630             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1631             RegIdx.Index == 17);
1632   }
1633 
1634   bool isMM16AsmRegMoveP() const {
1635     if (!(isRegIdx() && RegIdx.Kind))
1636       return false;
1637     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1638       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1639   }
1640 
1641   bool isFGRAsmReg() const {
1642     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1643     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1644   }
1645 
1646   bool isStrictlyFGRAsmReg() const {
1647     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1648     return isRegIdx() && RegIdx.Kind == RegKind_FGR && RegIdx.Index <= 31;
1649   }
1650 
1651   bool isHWRegsAsmReg() const {
1652     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1653   }
1654 
1655   bool isCCRAsmReg() const {
1656     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1657   }
1658 
1659   bool isFCCAsmReg() const {
1660     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1661       return false;
1662     return RegIdx.Index <= 7;
1663   }
1664 
1665   bool isACCAsmReg() const {
1666     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1667   }
1668 
1669   bool isCOP0AsmReg() const {
1670     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1671   }
1672 
1673   bool isCOP2AsmReg() const {
1674     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1675   }
1676 
1677   bool isCOP3AsmReg() const {
1678     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1679   }
1680 
1681   bool isMSA128AsmReg() const {
1682     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1683   }
1684 
1685   bool isMSACtrlAsmReg() const {
1686     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1687   }
1688 
1689   /// getStartLoc - Get the location of the first token of this operand.
1690   SMLoc getStartLoc() const override { return StartLoc; }
1691   /// getEndLoc - Get the location of the last token of this operand.
1692   SMLoc getEndLoc() const override { return EndLoc; }
1693 
1694   void print(raw_ostream &OS) const override {
1695     switch (Kind) {
1696     case k_Immediate:
1697       OS << "Imm<";
1698       OS << *Imm.Val;
1699       OS << ">";
1700       break;
1701     case k_Memory:
1702       OS << "Mem<";
1703       Mem.Base->print(OS);
1704       OS << ", ";
1705       OS << *Mem.Off;
1706       OS << ">";
1707       break;
1708     case k_RegisterIndex:
1709       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ", "
1710          << StringRef(RegIdx.Tok.Data, RegIdx.Tok.Length) << ">";
1711       break;
1712     case k_Token:
1713       OS << getToken();
1714       break;
1715     case k_RegList:
1716       OS << "RegList< ";
1717       for (auto Reg : (*RegList.List))
1718         OS << Reg << " ";
1719       OS <<  ">";
1720       break;
1721     case k_RegPair:
1722       OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">";
1723       break;
1724     }
1725   }
1726 
1727   bool isValidForTie(const MipsOperand &Other) const {
1728     if (Kind != Other.Kind)
1729       return false;
1730 
1731     switch (Kind) {
1732     default:
1733       llvm_unreachable("Unexpected kind");
1734       return false;
1735     case k_RegisterIndex: {
1736       StringRef Token(RegIdx.Tok.Data, RegIdx.Tok.Length);
1737       StringRef OtherToken(Other.RegIdx.Tok.Data, Other.RegIdx.Tok.Length);
1738       return Token == OtherToken;
1739     }
1740     }
1741   }
1742 }; // class MipsOperand
1743 
1744 } // end anonymous namespace
1745 
1746 namespace llvm {
1747 
1748 extern const MCInstrDesc MipsInsts[];
1749 
1750 } // end namespace llvm
1751 
1752 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1753   return MipsInsts[Opcode];
1754 }
1755 
1756 static bool hasShortDelaySlot(unsigned Opcode) {
1757   switch (Opcode) {
1758     case Mips::JALS_MM:
1759     case Mips::JALRS_MM:
1760     case Mips::JALRS16_MM:
1761     case Mips::BGEZALS_MM:
1762     case Mips::BLTZALS_MM:
1763       return true;
1764     default:
1765       return false;
1766   }
1767 }
1768 
1769 static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) {
1770   if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) {
1771     return &SRExpr->getSymbol();
1772   }
1773 
1774   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) {
1775     const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS());
1776     const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS());
1777 
1778     if (LHSSym)
1779       return LHSSym;
1780 
1781     if (RHSSym)
1782       return RHSSym;
1783 
1784     return nullptr;
1785   }
1786 
1787   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1788     return getSingleMCSymbol(UExpr->getSubExpr());
1789 
1790   return nullptr;
1791 }
1792 
1793 static unsigned countMCSymbolRefExpr(const MCExpr *Expr) {
1794   if (isa<MCSymbolRefExpr>(Expr))
1795     return 1;
1796 
1797   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr))
1798     return countMCSymbolRefExpr(BExpr->getLHS()) +
1799            countMCSymbolRefExpr(BExpr->getRHS());
1800 
1801   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1802     return countMCSymbolRefExpr(UExpr->getSubExpr());
1803 
1804   return 0;
1805 }
1806 
1807 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1808                                        MCStreamer &Out,
1809                                        const MCSubtargetInfo *STI) {
1810   MipsTargetStreamer &TOut = getTargetStreamer();
1811   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1812   bool ExpandedJalSym = false;
1813 
1814   Inst.setLoc(IDLoc);
1815 
1816   if (MCID.isBranch() || MCID.isCall()) {
1817     const unsigned Opcode = Inst.getOpcode();
1818     MCOperand Offset;
1819 
1820     switch (Opcode) {
1821     default:
1822       break;
1823     case Mips::BBIT0:
1824     case Mips::BBIT032:
1825     case Mips::BBIT1:
1826     case Mips::BBIT132:
1827       assert(hasCnMips() && "instruction only valid for octeon cpus");
1828       LLVM_FALLTHROUGH;
1829 
1830     case Mips::BEQ:
1831     case Mips::BNE:
1832     case Mips::BEQ_MM:
1833     case Mips::BNE_MM:
1834       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1835       Offset = Inst.getOperand(2);
1836       if (!Offset.isImm())
1837         break; // We'll deal with this situation later on when applying fixups.
1838       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1839         return Error(IDLoc, "branch target out of range");
1840       if (OffsetToAlignment(Offset.getImm(),
1841                             1LL << (inMicroMipsMode() ? 1 : 2)))
1842         return Error(IDLoc, "branch to misaligned address");
1843       break;
1844     case Mips::BGEZ:
1845     case Mips::BGTZ:
1846     case Mips::BLEZ:
1847     case Mips::BLTZ:
1848     case Mips::BGEZAL:
1849     case Mips::BLTZAL:
1850     case Mips::BC1F:
1851     case Mips::BC1T:
1852     case Mips::BGEZ_MM:
1853     case Mips::BGTZ_MM:
1854     case Mips::BLEZ_MM:
1855     case Mips::BLTZ_MM:
1856     case Mips::BGEZAL_MM:
1857     case Mips::BLTZAL_MM:
1858     case Mips::BC1F_MM:
1859     case Mips::BC1T_MM:
1860     case Mips::BC1EQZC_MMR6:
1861     case Mips::BC1NEZC_MMR6:
1862     case Mips::BC2EQZC_MMR6:
1863     case Mips::BC2NEZC_MMR6:
1864       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1865       Offset = Inst.getOperand(1);
1866       if (!Offset.isImm())
1867         break; // We'll deal with this situation later on when applying fixups.
1868       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1869         return Error(IDLoc, "branch target out of range");
1870       if (OffsetToAlignment(Offset.getImm(),
1871                             1LL << (inMicroMipsMode() ? 1 : 2)))
1872         return Error(IDLoc, "branch to misaligned address");
1873       break;
1874     case Mips::BGEC:    case Mips::BGEC_MMR6:
1875     case Mips::BLTC:    case Mips::BLTC_MMR6:
1876     case Mips::BGEUC:   case Mips::BGEUC_MMR6:
1877     case Mips::BLTUC:   case Mips::BLTUC_MMR6:
1878     case Mips::BEQC:    case Mips::BEQC_MMR6:
1879     case Mips::BNEC:    case Mips::BNEC_MMR6:
1880       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1881       Offset = Inst.getOperand(2);
1882       if (!Offset.isImm())
1883         break; // We'll deal with this situation later on when applying fixups.
1884       if (!isIntN(18, Offset.getImm()))
1885         return Error(IDLoc, "branch target out of range");
1886       if (OffsetToAlignment(Offset.getImm(), 1LL << 2))
1887         return Error(IDLoc, "branch to misaligned address");
1888       break;
1889     case Mips::BLEZC:   case Mips::BLEZC_MMR6:
1890     case Mips::BGEZC:   case Mips::BGEZC_MMR6:
1891     case Mips::BGTZC:   case Mips::BGTZC_MMR6:
1892     case Mips::BLTZC:   case Mips::BLTZC_MMR6:
1893       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1894       Offset = Inst.getOperand(1);
1895       if (!Offset.isImm())
1896         break; // We'll deal with this situation later on when applying fixups.
1897       if (!isIntN(18, Offset.getImm()))
1898         return Error(IDLoc, "branch target out of range");
1899       if (OffsetToAlignment(Offset.getImm(), 1LL << 2))
1900         return Error(IDLoc, "branch to misaligned address");
1901       break;
1902     case Mips::BEQZC:   case Mips::BEQZC_MMR6:
1903     case Mips::BNEZC:   case Mips::BNEZC_MMR6:
1904       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1905       Offset = Inst.getOperand(1);
1906       if (!Offset.isImm())
1907         break; // We'll deal with this situation later on when applying fixups.
1908       if (!isIntN(23, Offset.getImm()))
1909         return Error(IDLoc, "branch target out of range");
1910       if (OffsetToAlignment(Offset.getImm(), 1LL << 2))
1911         return Error(IDLoc, "branch to misaligned address");
1912       break;
1913     case Mips::BEQZ16_MM:
1914     case Mips::BEQZC16_MMR6:
1915     case Mips::BNEZ16_MM:
1916     case Mips::BNEZC16_MMR6:
1917       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1918       Offset = Inst.getOperand(1);
1919       if (!Offset.isImm())
1920         break; // We'll deal with this situation later on when applying fixups.
1921       if (!isInt<8>(Offset.getImm()))
1922         return Error(IDLoc, "branch target out of range");
1923       if (OffsetToAlignment(Offset.getImm(), 2LL))
1924         return Error(IDLoc, "branch to misaligned address");
1925       break;
1926     }
1927   }
1928 
1929   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1930   // We still accept it but it is a normal nop.
1931   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1932     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1933     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1934                                                       "nop instruction");
1935   }
1936 
1937   if (hasCnMips()) {
1938     const unsigned Opcode = Inst.getOpcode();
1939     MCOperand Opnd;
1940     int Imm;
1941 
1942     switch (Opcode) {
1943       default:
1944         break;
1945 
1946       case Mips::BBIT0:
1947       case Mips::BBIT032:
1948       case Mips::BBIT1:
1949       case Mips::BBIT132:
1950         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1951         // The offset is handled above
1952         Opnd = Inst.getOperand(1);
1953         if (!Opnd.isImm())
1954           return Error(IDLoc, "expected immediate operand kind");
1955         Imm = Opnd.getImm();
1956         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1957                               Opcode == Mips::BBIT1 ? 63 : 31))
1958           return Error(IDLoc, "immediate operand value out of range");
1959         if (Imm > 31) {
1960           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1961                                                : Mips::BBIT132);
1962           Inst.getOperand(1).setImm(Imm - 32);
1963         }
1964         break;
1965 
1966       case Mips::SEQi:
1967       case Mips::SNEi:
1968         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1969         Opnd = Inst.getOperand(2);
1970         if (!Opnd.isImm())
1971           return Error(IDLoc, "expected immediate operand kind");
1972         Imm = Opnd.getImm();
1973         if (!isInt<10>(Imm))
1974           return Error(IDLoc, "immediate operand value out of range");
1975         break;
1976     }
1977   }
1978 
1979   // Warn on division by zero. We're checking here as all instructions get
1980   // processed here, not just the macros that need expansion.
1981   //
1982   // The MIPS backend models most of the divison instructions and macros as
1983   // three operand instructions. The pre-R6 divide instructions however have
1984   // two operands and explicitly define HI/LO as part of the instruction,
1985   // not in the operands.
1986   unsigned FirstOp = 1;
1987   unsigned SecondOp = 2;
1988   switch (Inst.getOpcode()) {
1989   default:
1990     break;
1991   case Mips::SDivIMacro:
1992   case Mips::UDivIMacro:
1993   case Mips::DSDivIMacro:
1994   case Mips::DUDivIMacro:
1995     if (Inst.getOperand(2).getImm() == 0) {
1996       if (Inst.getOperand(1).getReg() == Mips::ZERO ||
1997           Inst.getOperand(1).getReg() == Mips::ZERO_64)
1998         Warning(IDLoc, "dividing zero by zero");
1999       else
2000         Warning(IDLoc, "division by zero");
2001     }
2002     break;
2003   case Mips::DSDIV:
2004   case Mips::SDIV:
2005   case Mips::UDIV:
2006   case Mips::DUDIV:
2007   case Mips::UDIV_MM:
2008   case Mips::SDIV_MM:
2009     FirstOp = 0;
2010     SecondOp = 1;
2011     LLVM_FALLTHROUGH;
2012   case Mips::SDivMacro:
2013   case Mips::DSDivMacro:
2014   case Mips::UDivMacro:
2015   case Mips::DUDivMacro:
2016   case Mips::DIV:
2017   case Mips::DIVU:
2018   case Mips::DDIV:
2019   case Mips::DDIVU:
2020   case Mips::DIVU_MMR6:
2021   case Mips::DIV_MMR6:
2022     if (Inst.getOperand(SecondOp).getReg() == Mips::ZERO ||
2023         Inst.getOperand(SecondOp).getReg() == Mips::ZERO_64) {
2024       if (Inst.getOperand(FirstOp).getReg() == Mips::ZERO ||
2025           Inst.getOperand(FirstOp).getReg() == Mips::ZERO_64)
2026         Warning(IDLoc, "dividing zero by zero");
2027       else
2028         Warning(IDLoc, "division by zero");
2029     }
2030     break;
2031   }
2032 
2033   // For PIC code convert unconditional jump to unconditional branch.
2034   if ((Inst.getOpcode() == Mips::J || Inst.getOpcode() == Mips::J_MM) &&
2035       inPicMode()) {
2036     MCInst BInst;
2037     BInst.setOpcode(inMicroMipsMode() ? Mips::BEQ_MM : Mips::BEQ);
2038     BInst.addOperand(MCOperand::createReg(Mips::ZERO));
2039     BInst.addOperand(MCOperand::createReg(Mips::ZERO));
2040     BInst.addOperand(Inst.getOperand(0));
2041     Inst = BInst;
2042   }
2043 
2044   // This expansion is not in a function called by tryExpandInstruction()
2045   // because the pseudo-instruction doesn't have a distinct opcode.
2046   if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) &&
2047       inPicMode()) {
2048     warnIfNoMacro(IDLoc);
2049 
2050     const MCExpr *JalExpr = Inst.getOperand(0).getExpr();
2051 
2052     // We can do this expansion if there's only 1 symbol in the argument
2053     // expression.
2054     if (countMCSymbolRefExpr(JalExpr) > 1)
2055       return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode");
2056 
2057     // FIXME: This is checking the expression can be handled by the later stages
2058     //        of the assembler. We ought to leave it to those later stages.
2059     const MCSymbol *JalSym = getSingleMCSymbol(JalExpr);
2060 
2061     // FIXME: Add support for label+offset operands (currently causes an error).
2062     // FIXME: Add support for forward-declared local symbols.
2063     // FIXME: Add expansion for when the LargeGOT option is enabled.
2064     if (JalSym->isInSection() || JalSym->isTemporary() ||
2065         (JalSym->isELF() &&
2066          cast<MCSymbolELF>(JalSym)->getBinding() == ELF::STB_LOCAL)) {
2067       if (isABI_O32()) {
2068         // If it's a local symbol and the O32 ABI is being used, we expand to:
2069         //  lw $25, 0($gp)
2070         //    R_(MICRO)MIPS_GOT16  label
2071         //  addiu $25, $25, 0
2072         //    R_(MICRO)MIPS_LO16   label
2073         //  jalr  $25
2074         const MCExpr *Got16RelocExpr =
2075             MipsMCExpr::create(MipsMCExpr::MEK_GOT, JalExpr, getContext());
2076         const MCExpr *Lo16RelocExpr =
2077             MipsMCExpr::create(MipsMCExpr::MEK_LO, JalExpr, getContext());
2078 
2079         TOut.emitRRX(Mips::LW, Mips::T9, Mips::GP,
2080                      MCOperand::createExpr(Got16RelocExpr), IDLoc, STI);
2081         TOut.emitRRX(Mips::ADDiu, Mips::T9, Mips::T9,
2082                      MCOperand::createExpr(Lo16RelocExpr), IDLoc, STI);
2083       } else if (isABI_N32() || isABI_N64()) {
2084         // If it's a local symbol and the N32/N64 ABIs are being used,
2085         // we expand to:
2086         //  lw/ld $25, 0($gp)
2087         //    R_(MICRO)MIPS_GOT_DISP  label
2088         //  jalr  $25
2089         const MCExpr *GotDispRelocExpr =
2090             MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, JalExpr, getContext());
2091 
2092         TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9,
2093                      Mips::GP, MCOperand::createExpr(GotDispRelocExpr), IDLoc,
2094                      STI);
2095       }
2096     } else {
2097       // If it's an external/weak symbol, we expand to:
2098       //  lw/ld    $25, 0($gp)
2099       //    R_(MICRO)MIPS_CALL16  label
2100       //  jalr  $25
2101       const MCExpr *Call16RelocExpr =
2102           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, JalExpr, getContext());
2103 
2104       TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
2105                    MCOperand::createExpr(Call16RelocExpr), IDLoc, STI);
2106     }
2107 
2108     MCInst JalrInst;
2109     if (IsCpRestoreSet && inMicroMipsMode())
2110       JalrInst.setOpcode(Mips::JALRS_MM);
2111     else
2112       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2113     JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2114     JalrInst.addOperand(MCOperand::createReg(Mips::T9));
2115 
2116     // FIXME: Add an R_(MICRO)MIPS_JALR relocation after the JALR.
2117     // This relocation is supposed to be an optimization hint for the linker
2118     // and is not necessary for correctness.
2119 
2120     Inst = JalrInst;
2121     ExpandedJalSym = true;
2122   }
2123 
2124   bool IsPCRelativeLoad = (MCID.TSFlags & MipsII::IsPCRelativeLoad) != 0;
2125   if ((MCID.mayLoad() || MCID.mayStore()) && !IsPCRelativeLoad) {
2126     // Check the offset of memory operand, if it is a symbol
2127     // reference or immediate we may have to expand instructions.
2128     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
2129       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
2130       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
2131           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
2132         MCOperand &Op = Inst.getOperand(i);
2133         if (Op.isImm()) {
2134           int64_t MemOffset = Op.getImm();
2135           if (MemOffset < -32768 || MemOffset > 32767) {
2136             // Offset can't exceed 16bit value.
2137             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad());
2138             return getParser().hasPendingError();
2139           }
2140         } else if (Op.isExpr()) {
2141           const MCExpr *Expr = Op.getExpr();
2142           if (Expr->getKind() == MCExpr::SymbolRef) {
2143             const MCSymbolRefExpr *SR =
2144                 static_cast<const MCSymbolRefExpr *>(Expr);
2145             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
2146               // Expand symbol.
2147               expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad());
2148               return getParser().hasPendingError();
2149             }
2150           } else if (!isEvaluated(Expr)) {
2151             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad());
2152             return getParser().hasPendingError();
2153           }
2154         }
2155       }
2156     } // for
2157   }   // if load/store
2158 
2159   if (inMicroMipsMode()) {
2160     if (MCID.mayLoad() && Inst.getOpcode() != Mips::LWP_MM) {
2161       // Try to create 16-bit GP relative load instruction.
2162       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
2163         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
2164         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
2165             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
2166           MCOperand &Op = Inst.getOperand(i);
2167           if (Op.isImm()) {
2168             int MemOffset = Op.getImm();
2169             MCOperand &DstReg = Inst.getOperand(0);
2170             MCOperand &BaseReg = Inst.getOperand(1);
2171             if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) &&
2172                 getContext().getRegisterInfo()->getRegClass(
2173                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
2174                 (BaseReg.getReg() == Mips::GP ||
2175                 BaseReg.getReg() == Mips::GP_64)) {
2176 
2177               TOut.emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset,
2178                            IDLoc, STI);
2179               return false;
2180             }
2181           }
2182         }
2183       } // for
2184     }   // if load
2185 
2186     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
2187 
2188     MCOperand Opnd;
2189     int Imm;
2190 
2191     switch (Inst.getOpcode()) {
2192       default:
2193         break;
2194       case Mips::ADDIUSP_MM:
2195         Opnd = Inst.getOperand(0);
2196         if (!Opnd.isImm())
2197           return Error(IDLoc, "expected immediate operand kind");
2198         Imm = Opnd.getImm();
2199         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
2200             Imm % 4 != 0)
2201           return Error(IDLoc, "immediate operand value out of range");
2202         break;
2203       case Mips::SLL16_MM:
2204       case Mips::SRL16_MM:
2205         Opnd = Inst.getOperand(2);
2206         if (!Opnd.isImm())
2207           return Error(IDLoc, "expected immediate operand kind");
2208         Imm = Opnd.getImm();
2209         if (Imm < 1 || Imm > 8)
2210           return Error(IDLoc, "immediate operand value out of range");
2211         break;
2212       case Mips::LI16_MM:
2213         Opnd = Inst.getOperand(1);
2214         if (!Opnd.isImm())
2215           return Error(IDLoc, "expected immediate operand kind");
2216         Imm = Opnd.getImm();
2217         if (Imm < -1 || Imm > 126)
2218           return Error(IDLoc, "immediate operand value out of range");
2219         break;
2220       case Mips::ADDIUR2_MM:
2221         Opnd = Inst.getOperand(2);
2222         if (!Opnd.isImm())
2223           return Error(IDLoc, "expected immediate operand kind");
2224         Imm = Opnd.getImm();
2225         if (!(Imm == 1 || Imm == -1 ||
2226               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
2227           return Error(IDLoc, "immediate operand value out of range");
2228         break;
2229       case Mips::ANDI16_MM:
2230         Opnd = Inst.getOperand(2);
2231         if (!Opnd.isImm())
2232           return Error(IDLoc, "expected immediate operand kind");
2233         Imm = Opnd.getImm();
2234         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
2235               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
2236               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
2237           return Error(IDLoc, "immediate operand value out of range");
2238         break;
2239       case Mips::LBU16_MM:
2240         Opnd = Inst.getOperand(2);
2241         if (!Opnd.isImm())
2242           return Error(IDLoc, "expected immediate operand kind");
2243         Imm = Opnd.getImm();
2244         if (Imm < -1 || Imm > 14)
2245           return Error(IDLoc, "immediate operand value out of range");
2246         break;
2247       case Mips::SB16_MM:
2248       case Mips::SB16_MMR6:
2249         Opnd = Inst.getOperand(2);
2250         if (!Opnd.isImm())
2251           return Error(IDLoc, "expected immediate operand kind");
2252         Imm = Opnd.getImm();
2253         if (Imm < 0 || Imm > 15)
2254           return Error(IDLoc, "immediate operand value out of range");
2255         break;
2256       case Mips::LHU16_MM:
2257       case Mips::SH16_MM:
2258       case Mips::SH16_MMR6:
2259         Opnd = Inst.getOperand(2);
2260         if (!Opnd.isImm())
2261           return Error(IDLoc, "expected immediate operand kind");
2262         Imm = Opnd.getImm();
2263         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
2264           return Error(IDLoc, "immediate operand value out of range");
2265         break;
2266       case Mips::LW16_MM:
2267       case Mips::SW16_MM:
2268       case Mips::SW16_MMR6:
2269         Opnd = Inst.getOperand(2);
2270         if (!Opnd.isImm())
2271           return Error(IDLoc, "expected immediate operand kind");
2272         Imm = Opnd.getImm();
2273         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
2274           return Error(IDLoc, "immediate operand value out of range");
2275         break;
2276       case Mips::ADDIUPC_MM:
2277         Opnd = Inst.getOperand(1);
2278         if (!Opnd.isImm())
2279           return Error(IDLoc, "expected immediate operand kind");
2280         Imm = Opnd.getImm();
2281         if ((Imm % 4 != 0) || !isInt<25>(Imm))
2282           return Error(IDLoc, "immediate operand value out of range");
2283         break;
2284       case Mips::LWP_MM:
2285       case Mips::SWP_MM:
2286         if (Inst.getOperand(0).getReg() == Mips::RA)
2287           return Error(IDLoc, "invalid operand for instruction");
2288         break;
2289     }
2290   }
2291 
2292   bool FillDelaySlot =
2293       MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder();
2294   if (FillDelaySlot)
2295     TOut.emitDirectiveSetNoReorder();
2296 
2297   MacroExpanderResultTy ExpandResult =
2298       tryExpandInstruction(Inst, IDLoc, Out, STI);
2299   switch (ExpandResult) {
2300   case MER_NotAMacro:
2301     Out.EmitInstruction(Inst, *STI);
2302     break;
2303   case MER_Success:
2304     break;
2305   case MER_Fail:
2306     return true;
2307   }
2308 
2309   // We know we emitted an instruction on the MER_NotAMacro or MER_Success path.
2310   // If we're in microMIPS mode then we must also set EF_MIPS_MICROMIPS.
2311   if (inMicroMipsMode()) {
2312     TOut.setUsesMicroMips();
2313     TOut.updateABIInfo(*this);
2314   }
2315 
2316   // If this instruction has a delay slot and .set reorder is active,
2317   // emit a NOP after it.
2318   if (FillDelaySlot) {
2319     TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc, STI);
2320     TOut.emitDirectiveSetReorder();
2321   }
2322 
2323   if ((Inst.getOpcode() == Mips::JalOneReg ||
2324        Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) &&
2325       isPicAndNotNxxAbi()) {
2326     if (IsCpRestoreSet) {
2327       // We need a NOP between the JALR and the LW:
2328       // If .set reorder has been used, we've already emitted a NOP.
2329       // If .set noreorder has been used, we need to emit a NOP at this point.
2330       if (!AssemblerOptions.back()->isReorder())
2331         TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc,
2332                                 STI);
2333 
2334       // Load the $gp from the stack.
2335       TOut.emitGPRestore(CpRestoreOffset, IDLoc, STI);
2336     } else
2337       Warning(IDLoc, "no .cprestore used in PIC mode");
2338   }
2339 
2340   return false;
2341 }
2342 
2343 MipsAsmParser::MacroExpanderResultTy
2344 MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2345                                     const MCSubtargetInfo *STI) {
2346   switch (Inst.getOpcode()) {
2347   default:
2348     return MER_NotAMacro;
2349   case Mips::LoadImm32:
2350     return expandLoadImm(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2351   case Mips::LoadImm64:
2352     return expandLoadImm(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2353   case Mips::LoadAddrImm32:
2354   case Mips::LoadAddrImm64:
2355     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2356     assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) &&
2357            "expected immediate operand kind");
2358 
2359     return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister,
2360                              Inst.getOperand(1),
2361                              Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc,
2362                              Out, STI)
2363                ? MER_Fail
2364                : MER_Success;
2365   case Mips::LoadAddrReg32:
2366   case Mips::LoadAddrReg64:
2367     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2368     assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2369     assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) &&
2370            "expected immediate operand kind");
2371 
2372     return expandLoadAddress(Inst.getOperand(0).getReg(),
2373                              Inst.getOperand(1).getReg(), Inst.getOperand(2),
2374                              Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc,
2375                              Out, STI)
2376                ? MER_Fail
2377                : MER_Success;
2378   case Mips::B_MM_Pseudo:
2379   case Mips::B_MMR6_Pseudo:
2380     return expandUncondBranchMMPseudo(Inst, IDLoc, Out, STI) ? MER_Fail
2381                                                              : MER_Success;
2382   case Mips::SWM_MM:
2383   case Mips::LWM_MM:
2384     return expandLoadStoreMultiple(Inst, IDLoc, Out, STI) ? MER_Fail
2385                                                           : MER_Success;
2386   case Mips::JalOneReg:
2387   case Mips::JalTwoReg:
2388     return expandJalWithRegs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2389   case Mips::BneImm:
2390   case Mips::BeqImm:
2391   case Mips::BEQLImmMacro:
2392   case Mips::BNELImmMacro:
2393     return expandBranchImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2394   case Mips::BLT:
2395   case Mips::BLE:
2396   case Mips::BGE:
2397   case Mips::BGT:
2398   case Mips::BLTU:
2399   case Mips::BLEU:
2400   case Mips::BGEU:
2401   case Mips::BGTU:
2402   case Mips::BLTL:
2403   case Mips::BLEL:
2404   case Mips::BGEL:
2405   case Mips::BGTL:
2406   case Mips::BLTUL:
2407   case Mips::BLEUL:
2408   case Mips::BGEUL:
2409   case Mips::BGTUL:
2410   case Mips::BLTImmMacro:
2411   case Mips::BLEImmMacro:
2412   case Mips::BGEImmMacro:
2413   case Mips::BGTImmMacro:
2414   case Mips::BLTUImmMacro:
2415   case Mips::BLEUImmMacro:
2416   case Mips::BGEUImmMacro:
2417   case Mips::BGTUImmMacro:
2418   case Mips::BLTLImmMacro:
2419   case Mips::BLELImmMacro:
2420   case Mips::BGELImmMacro:
2421   case Mips::BGTLImmMacro:
2422   case Mips::BLTULImmMacro:
2423   case Mips::BLEULImmMacro:
2424   case Mips::BGEULImmMacro:
2425   case Mips::BGTULImmMacro:
2426     return expandCondBranches(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2427   case Mips::SDivMacro:
2428   case Mips::SDivIMacro:
2429   case Mips::SRemMacro:
2430   case Mips::SRemIMacro:
2431     return expandDivRem(Inst, IDLoc, Out, STI, false, true) ? MER_Fail
2432                                                             : MER_Success;
2433   case Mips::DSDivMacro:
2434   case Mips::DSDivIMacro:
2435   case Mips::DSRemMacro:
2436   case Mips::DSRemIMacro:
2437     return expandDivRem(Inst, IDLoc, Out, STI, true, true) ? MER_Fail
2438                                                            : MER_Success;
2439   case Mips::UDivMacro:
2440   case Mips::UDivIMacro:
2441   case Mips::URemMacro:
2442   case Mips::URemIMacro:
2443     return expandDivRem(Inst, IDLoc, Out, STI, false, false) ? MER_Fail
2444                                                              : MER_Success;
2445   case Mips::DUDivMacro:
2446   case Mips::DUDivIMacro:
2447   case Mips::DURemMacro:
2448   case Mips::DURemIMacro:
2449     return expandDivRem(Inst, IDLoc, Out, STI, true, false) ? MER_Fail
2450                                                             : MER_Success;
2451   case Mips::PseudoTRUNC_W_S:
2452     return expandTrunc(Inst, false, false, IDLoc, Out, STI) ? MER_Fail
2453                                                             : MER_Success;
2454   case Mips::PseudoTRUNC_W_D32:
2455     return expandTrunc(Inst, true, false, IDLoc, Out, STI) ? MER_Fail
2456                                                            : MER_Success;
2457   case Mips::PseudoTRUNC_W_D:
2458     return expandTrunc(Inst, true, true, IDLoc, Out, STI) ? MER_Fail
2459                                                           : MER_Success;
2460 
2461   case Mips::LoadImmSingleGPR:
2462     return expandLoadImmReal(Inst, true, true, false, IDLoc, Out, STI)
2463                ? MER_Fail
2464                : MER_Success;
2465   case Mips::LoadImmSingleFGR:
2466     return expandLoadImmReal(Inst, true, false, false, IDLoc, Out, STI)
2467                ? MER_Fail
2468                : MER_Success;
2469   case Mips::LoadImmDoubleGPR:
2470     return expandLoadImmReal(Inst, false, true, false, IDLoc, Out, STI)
2471                ? MER_Fail
2472                : MER_Success;
2473   case Mips::LoadImmDoubleFGR:
2474       return expandLoadImmReal(Inst, false, false, true, IDLoc, Out, STI)
2475                ? MER_Fail
2476                : MER_Success;
2477   case Mips::LoadImmDoubleFGR_32:
2478     return expandLoadImmReal(Inst, false, false, false, IDLoc, Out, STI)
2479                ? MER_Fail
2480                : MER_Success;
2481   case Mips::Ulh:
2482     return expandUlh(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2483   case Mips::Ulhu:
2484     return expandUlh(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2485   case Mips::Ush:
2486     return expandUsh(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2487   case Mips::Ulw:
2488   case Mips::Usw:
2489     return expandUxw(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2490   case Mips::NORImm:
2491   case Mips::NORImm64:
2492     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2493   case Mips::SLTImm64:
2494     if (isInt<16>(Inst.getOperand(2).getImm())) {
2495       Inst.setOpcode(Mips::SLTi64);
2496       return MER_NotAMacro;
2497     }
2498     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2499   case Mips::SLTUImm64:
2500     if (isInt<16>(Inst.getOperand(2).getImm())) {
2501       Inst.setOpcode(Mips::SLTiu64);
2502       return MER_NotAMacro;
2503     }
2504     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2505   case Mips::ADDi:   case Mips::ADDi_MM:
2506   case Mips::ADDiu:  case Mips::ADDiu_MM:
2507   case Mips::SLTi:   case Mips::SLTi_MM:
2508   case Mips::SLTiu:  case Mips::SLTiu_MM:
2509     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2510         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2511       int64_t ImmValue = Inst.getOperand(2).getImm();
2512       if (isInt<16>(ImmValue))
2513         return MER_NotAMacro;
2514       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2515                                                          : MER_Success;
2516     }
2517     return MER_NotAMacro;
2518   case Mips::ANDi:  case Mips::ANDi_MM:  case Mips::ANDi64:
2519   case Mips::ORi:   case Mips::ORi_MM:   case Mips::ORi64:
2520   case Mips::XORi:  case Mips::XORi_MM:  case Mips::XORi64:
2521     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2522         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2523       int64_t ImmValue = Inst.getOperand(2).getImm();
2524       if (isUInt<16>(ImmValue))
2525         return MER_NotAMacro;
2526       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2527                                                          : MER_Success;
2528     }
2529     return MER_NotAMacro;
2530   case Mips::ROL:
2531   case Mips::ROR:
2532     return expandRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2533   case Mips::ROLImm:
2534   case Mips::RORImm:
2535     return expandRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2536   case Mips::DROL:
2537   case Mips::DROR:
2538     return expandDRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2539   case Mips::DROLImm:
2540   case Mips::DRORImm:
2541     return expandDRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2542   case Mips::ABSMacro:
2543     return expandAbs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2544   case Mips::MULImmMacro:
2545   case Mips::DMULImmMacro:
2546     return expandMulImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2547   case Mips::MULOMacro:
2548   case Mips::DMULOMacro:
2549     return expandMulO(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2550   case Mips::MULOUMacro:
2551   case Mips::DMULOUMacro:
2552     return expandMulOU(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2553   case Mips::DMULMacro:
2554     return expandDMULMacro(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2555   case Mips::LDMacro:
2556   case Mips::SDMacro:
2557     return expandLoadStoreDMacro(Inst, IDLoc, Out, STI,
2558                                  Inst.getOpcode() == Mips::LDMacro)
2559                ? MER_Fail
2560                : MER_Success;
2561   case Mips::SEQMacro:
2562     return expandSeq(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2563   case Mips::SEQIMacro:
2564     return expandSeqI(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2565   case Mips::MFTC0:   case Mips::MTTC0:
2566   case Mips::MFTGPR:  case Mips::MTTGPR:
2567   case Mips::MFTLO:   case Mips::MTTLO:
2568   case Mips::MFTHI:   case Mips::MTTHI:
2569   case Mips::MFTACX:  case Mips::MTTACX:
2570   case Mips::MFTDSP:  case Mips::MTTDSP:
2571   case Mips::MFTC1:   case Mips::MTTC1:
2572   case Mips::MFTHC1:  case Mips::MTTHC1:
2573   case Mips::CFTC1:   case Mips::CTTC1:
2574     return expandMXTRAlias(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2575   }
2576 }
2577 
2578 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
2579                                       MCStreamer &Out,
2580                                       const MCSubtargetInfo *STI) {
2581   MipsTargetStreamer &TOut = getTargetStreamer();
2582 
2583   // Create a JALR instruction which is going to replace the pseudo-JAL.
2584   MCInst JalrInst;
2585   JalrInst.setLoc(IDLoc);
2586   const MCOperand FirstRegOp = Inst.getOperand(0);
2587   const unsigned Opcode = Inst.getOpcode();
2588 
2589   if (Opcode == Mips::JalOneReg) {
2590     // jal $rs => jalr $rs
2591     if (IsCpRestoreSet && inMicroMipsMode()) {
2592       JalrInst.setOpcode(Mips::JALRS16_MM);
2593       JalrInst.addOperand(FirstRegOp);
2594     } else if (inMicroMipsMode()) {
2595       JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM);
2596       JalrInst.addOperand(FirstRegOp);
2597     } else {
2598       JalrInst.setOpcode(Mips::JALR);
2599       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2600       JalrInst.addOperand(FirstRegOp);
2601     }
2602   } else if (Opcode == Mips::JalTwoReg) {
2603     // jal $rd, $rs => jalr $rd, $rs
2604     if (IsCpRestoreSet && inMicroMipsMode())
2605       JalrInst.setOpcode(Mips::JALRS_MM);
2606     else
2607       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2608     JalrInst.addOperand(FirstRegOp);
2609     const MCOperand SecondRegOp = Inst.getOperand(1);
2610     JalrInst.addOperand(SecondRegOp);
2611   }
2612   Out.EmitInstruction(JalrInst, *STI);
2613 
2614   // If .set reorder is active and branch instruction has a delay slot,
2615   // emit a NOP after it.
2616   const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode());
2617   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2618     TOut.emitEmptyDelaySlot(hasShortDelaySlot(JalrInst.getOpcode()), IDLoc,
2619                             STI);
2620 
2621   return false;
2622 }
2623 
2624 /// Can the value be represented by a unsigned N-bit value and a shift left?
2625 template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) {
2626   unsigned BitNum = findFirstSet(x);
2627 
2628   return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum);
2629 }
2630 
2631 /// Load (or add) an immediate into a register.
2632 ///
2633 /// @param ImmValue     The immediate to load.
2634 /// @param DstReg       The register that will hold the immediate.
2635 /// @param SrcReg       A register to add to the immediate or Mips::NoRegister
2636 ///                     for a simple initialization.
2637 /// @param Is32BitImm   Is ImmValue 32-bit or 64-bit?
2638 /// @param IsAddress    True if the immediate represents an address. False if it
2639 ///                     is an integer.
2640 /// @param IDLoc        Location of the immediate in the source file.
2641 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
2642                                   unsigned SrcReg, bool Is32BitImm,
2643                                   bool IsAddress, SMLoc IDLoc, MCStreamer &Out,
2644                                   const MCSubtargetInfo *STI) {
2645   MipsTargetStreamer &TOut = getTargetStreamer();
2646 
2647   if (!Is32BitImm && !isGP64bit()) {
2648     Error(IDLoc, "instruction requires a 64-bit architecture");
2649     return true;
2650   }
2651 
2652   if (Is32BitImm) {
2653     if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2654       // Sign extend up to 64-bit so that the predicates match the hardware
2655       // behaviour. In particular, isInt<16>(0xffff8000) and similar should be
2656       // true.
2657       ImmValue = SignExtend64<32>(ImmValue);
2658     } else {
2659       Error(IDLoc, "instruction requires a 32-bit immediate");
2660       return true;
2661     }
2662   }
2663 
2664   unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg();
2665   unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu;
2666 
2667   bool UseSrcReg = false;
2668   if (SrcReg != Mips::NoRegister)
2669     UseSrcReg = true;
2670 
2671   unsigned TmpReg = DstReg;
2672   if (UseSrcReg &&
2673       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2674     // At this point we need AT to perform the expansions and we exit if it is
2675     // not available.
2676     unsigned ATReg = getATReg(IDLoc);
2677     if (!ATReg)
2678       return true;
2679     TmpReg = ATReg;
2680   }
2681 
2682   if (isInt<16>(ImmValue)) {
2683     if (!UseSrcReg)
2684       SrcReg = ZeroReg;
2685 
2686     // This doesn't quite follow the usual ABI expectations for N32 but matches
2687     // traditional assembler behaviour. N32 would normally use addiu for both
2688     // integers and addresses.
2689     if (IsAddress && !Is32BitImm) {
2690       TOut.emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2691       return false;
2692     }
2693 
2694     TOut.emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2695     return false;
2696   }
2697 
2698   if (isUInt<16>(ImmValue)) {
2699     unsigned TmpReg = DstReg;
2700     if (SrcReg == DstReg) {
2701       TmpReg = getATReg(IDLoc);
2702       if (!TmpReg)
2703         return true;
2704     }
2705 
2706     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, STI);
2707     if (UseSrcReg)
2708       TOut.emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, STI);
2709     return false;
2710   }
2711 
2712   if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2713     warnIfNoMacro(IDLoc);
2714 
2715     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
2716     uint16_t Bits15To0 = ImmValue & 0xffff;
2717     if (!Is32BitImm && !isInt<32>(ImmValue)) {
2718       // Traditional behaviour seems to special case this particular value. It's
2719       // not clear why other masks are handled differently.
2720       if (ImmValue == 0xffffffff) {
2721         TOut.emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, STI);
2722         TOut.emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, STI);
2723         if (UseSrcReg)
2724           TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2725         return false;
2726       }
2727 
2728       // Expand to an ORi instead of a LUi to avoid sign-extending into the
2729       // upper 32 bits.
2730       TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, STI);
2731       TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, STI);
2732       if (Bits15To0)
2733         TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2734       if (UseSrcReg)
2735         TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2736       return false;
2737     }
2738 
2739     TOut.emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, STI);
2740     if (Bits15To0)
2741       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2742     if (UseSrcReg)
2743       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2744     return false;
2745   }
2746 
2747   if (isShiftedUIntAtAnyPosition<16>(ImmValue)) {
2748     if (Is32BitImm) {
2749       Error(IDLoc, "instruction requires a 32-bit immediate");
2750       return true;
2751     }
2752 
2753     // Traditionally, these immediates are shifted as little as possible and as
2754     // such we align the most significant bit to bit 15 of our temporary.
2755     unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
2756     unsigned LastSet = findLastSet((uint64_t)ImmValue);
2757     unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
2758     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
2759     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, STI);
2760     TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, STI);
2761 
2762     if (UseSrcReg)
2763       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2764 
2765     return false;
2766   }
2767 
2768   warnIfNoMacro(IDLoc);
2769 
2770   // The remaining case is packed with a sequence of dsll and ori with zeros
2771   // being omitted and any neighbouring dsll's being coalesced.
2772   // The highest 32-bit's are equivalent to a 32-bit immediate load.
2773 
2774   // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register.
2775   if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false,
2776                     IDLoc, Out, STI))
2777     return false;
2778 
2779   // Shift and accumulate into the register. If a 16-bit chunk is zero, then
2780   // skip it and defer the shift to the next chunk.
2781   unsigned ShiftCarriedForwards = 16;
2782   for (int BitNum = 16; BitNum >= 0; BitNum -= 16) {
2783     uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff;
2784 
2785     if (ImmChunk != 0) {
2786       TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2787       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, STI);
2788       ShiftCarriedForwards = 0;
2789     }
2790 
2791     ShiftCarriedForwards += 16;
2792   }
2793   ShiftCarriedForwards -= 16;
2794 
2795   // Finish any remaining shifts left by trailing zeros.
2796   if (ShiftCarriedForwards)
2797     TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2798 
2799   if (UseSrcReg)
2800     TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2801 
2802   return false;
2803 }
2804 
2805 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2806                                   MCStreamer &Out, const MCSubtargetInfo *STI) {
2807   const MCOperand &ImmOp = Inst.getOperand(1);
2808   assert(ImmOp.isImm() && "expected immediate operand kind");
2809   const MCOperand &DstRegOp = Inst.getOperand(0);
2810   assert(DstRegOp.isReg() && "expected register operand kind");
2811 
2812   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2813                     Is32BitImm, false, IDLoc, Out, STI))
2814     return true;
2815 
2816   return false;
2817 }
2818 
2819 bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg,
2820                                       const MCOperand &Offset,
2821                                       bool Is32BitAddress, SMLoc IDLoc,
2822                                       MCStreamer &Out,
2823                                       const MCSubtargetInfo *STI) {
2824   // la can't produce a usable address when addresses are 64-bit.
2825   if (Is32BitAddress && ABI.ArePtrs64bit()) {
2826     // FIXME: Demote this to a warning and continue as if we had 'dla' instead.
2827     //        We currently can't do this because we depend on the equality
2828     //        operator and N64 can end up with a GPR32/GPR64 mismatch.
2829     Error(IDLoc, "la used to load 64-bit address");
2830     // Continue as if we had 'dla' instead.
2831     Is32BitAddress = false;
2832     return true;
2833   }
2834 
2835   // dla requires 64-bit addresses.
2836   if (!Is32BitAddress && !hasMips3()) {
2837     Error(IDLoc, "instruction requires a 64-bit architecture");
2838     return true;
2839   }
2840 
2841   if (!Offset.isImm())
2842     return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg,
2843                                    Is32BitAddress, IDLoc, Out, STI);
2844 
2845   if (!ABI.ArePtrs64bit()) {
2846     // Continue as if we had 'la' whether we had 'la' or 'dla'.
2847     Is32BitAddress = true;
2848   }
2849 
2850   return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true,
2851                        IDLoc, Out, STI);
2852 }
2853 
2854 bool MipsAsmParser::loadAndAddSymbolAddress(const MCExpr *SymExpr,
2855                                             unsigned DstReg, unsigned SrcReg,
2856                                             bool Is32BitSym, SMLoc IDLoc,
2857                                             MCStreamer &Out,
2858                                             const MCSubtargetInfo *STI) {
2859   // FIXME: These expansions do not respect -mxgot.
2860   MipsTargetStreamer &TOut = getTargetStreamer();
2861   bool UseSrcReg = SrcReg != Mips::NoRegister;
2862   warnIfNoMacro(IDLoc);
2863 
2864   if (inPicMode() && ABI.IsO32()) {
2865     MCValue Res;
2866     if (!SymExpr->evaluateAsRelocatable(Res, nullptr, nullptr)) {
2867       Error(IDLoc, "expected relocatable expression");
2868       return true;
2869     }
2870     if (Res.getSymB() != nullptr) {
2871       Error(IDLoc, "expected relocatable expression with only one symbol");
2872       return true;
2873     }
2874 
2875     // The case where the result register is $25 is somewhat special. If the
2876     // symbol in the final relocation is external and not modified with a
2877     // constant then we must use R_MIPS_CALL16 instead of R_MIPS_GOT16.
2878     if ((DstReg == Mips::T9 || DstReg == Mips::T9_64) && !UseSrcReg &&
2879         Res.getConstant() == 0 &&
2880         !(Res.getSymA()->getSymbol().isInSection() ||
2881           Res.getSymA()->getSymbol().isTemporary() ||
2882           (Res.getSymA()->getSymbol().isELF() &&
2883            cast<MCSymbolELF>(Res.getSymA()->getSymbol()).getBinding() ==
2884                ELF::STB_LOCAL))) {
2885       const MCExpr *CallExpr =
2886           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, SymExpr, getContext());
2887       TOut.emitRRX(Mips::LW, DstReg, ABI.GetGlobalPtr(),
2888                    MCOperand::createExpr(CallExpr), IDLoc, STI);
2889       return false;
2890     }
2891 
2892     // The remaining cases are:
2893     //   External GOT: lw $tmp, %got(symbol+offset)($gp)
2894     //                >addiu $tmp, $tmp, %lo(offset)
2895     //                >addiu $rd, $tmp, $rs
2896     //   Local GOT:    lw $tmp, %got(symbol+offset)($gp)
2897     //                 addiu $tmp, $tmp, %lo(symbol+offset)($gp)
2898     //                >addiu $rd, $tmp, $rs
2899     // The addiu's marked with a '>' may be omitted if they are redundant. If
2900     // this happens then the last instruction must use $rd as the result
2901     // register.
2902     const MipsMCExpr *GotExpr =
2903         MipsMCExpr::create(MipsMCExpr::MEK_GOT, SymExpr, getContext());
2904     const MCExpr *LoExpr = nullptr;
2905     if (Res.getSymA()->getSymbol().isInSection() ||
2906         Res.getSymA()->getSymbol().isTemporary())
2907       LoExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
2908     else if (Res.getConstant() != 0) {
2909       // External symbols fully resolve the symbol with just the %got(symbol)
2910       // but we must still account for any offset to the symbol for expressions
2911       // like symbol+8.
2912       LoExpr = MCConstantExpr::create(Res.getConstant(), getContext());
2913     }
2914 
2915     unsigned TmpReg = DstReg;
2916     if (UseSrcReg &&
2917         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2918                                                                SrcReg)) {
2919       // If $rs is the same as $rd, we need to use AT.
2920       // If it is not available we exit.
2921       unsigned ATReg = getATReg(IDLoc);
2922       if (!ATReg)
2923         return true;
2924       TmpReg = ATReg;
2925     }
2926 
2927     TOut.emitRRX(Mips::LW, TmpReg, ABI.GetGlobalPtr(),
2928                  MCOperand::createExpr(GotExpr), IDLoc, STI);
2929 
2930     if (LoExpr)
2931       TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
2932                    IDLoc, STI);
2933 
2934     if (UseSrcReg)
2935       TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
2936 
2937     return false;
2938   }
2939 
2940   if (inPicMode() && ABI.ArePtrs64bit()) {
2941     MCValue Res;
2942     if (!SymExpr->evaluateAsRelocatable(Res, nullptr, nullptr)) {
2943       Error(IDLoc, "expected relocatable expression");
2944       return true;
2945     }
2946     if (Res.getSymB() != nullptr) {
2947       Error(IDLoc, "expected relocatable expression with only one symbol");
2948       return true;
2949     }
2950 
2951     // The case where the result register is $25 is somewhat special. If the
2952     // symbol in the final relocation is external and not modified with a
2953     // constant then we must use R_MIPS_CALL16 instead of R_MIPS_GOT_DISP.
2954     if ((DstReg == Mips::T9 || DstReg == Mips::T9_64) && !UseSrcReg &&
2955         Res.getConstant() == 0 &&
2956         !(Res.getSymA()->getSymbol().isInSection() ||
2957           Res.getSymA()->getSymbol().isTemporary() ||
2958           (Res.getSymA()->getSymbol().isELF() &&
2959            cast<MCSymbolELF>(Res.getSymA()->getSymbol()).getBinding() ==
2960                ELF::STB_LOCAL))) {
2961       const MCExpr *CallExpr =
2962           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, SymExpr, getContext());
2963       TOut.emitRRX(Mips::LD, DstReg, ABI.GetGlobalPtr(),
2964                    MCOperand::createExpr(CallExpr), IDLoc, STI);
2965       return false;
2966     }
2967 
2968     // The remaining cases are:
2969     //   Small offset: ld $tmp, %got_disp(symbol)($gp)
2970     //                >daddiu $tmp, $tmp, offset
2971     //                >daddu $rd, $tmp, $rs
2972     // The daddiu's marked with a '>' may be omitted if they are redundant. If
2973     // this happens then the last instruction must use $rd as the result
2974     // register.
2975     const MipsMCExpr *GotExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP,
2976                                                    Res.getSymA(),
2977                                                    getContext());
2978     const MCExpr *LoExpr = nullptr;
2979     if (Res.getConstant() != 0) {
2980       // Symbols fully resolve with just the %got_disp(symbol) but we
2981       // must still account for any offset to the symbol for
2982       // expressions like symbol+8.
2983       LoExpr = MCConstantExpr::create(Res.getConstant(), getContext());
2984 
2985       // FIXME: Offsets greater than 16 bits are not yet implemented.
2986       // FIXME: The correct range is a 32-bit sign-extended number.
2987       if (Res.getConstant() < -0x8000 || Res.getConstant() > 0x7fff) {
2988         Error(IDLoc, "macro instruction uses large offset, which is not "
2989                      "currently supported");
2990         return true;
2991       }
2992     }
2993 
2994     unsigned TmpReg = DstReg;
2995     if (UseSrcReg &&
2996         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2997                                                                SrcReg)) {
2998       // If $rs is the same as $rd, we need to use AT.
2999       // If it is not available we exit.
3000       unsigned ATReg = getATReg(IDLoc);
3001       if (!ATReg)
3002         return true;
3003       TmpReg = ATReg;
3004     }
3005 
3006     TOut.emitRRX(Mips::LD, TmpReg, ABI.GetGlobalPtr(),
3007                  MCOperand::createExpr(GotExpr), IDLoc, STI);
3008 
3009     if (LoExpr)
3010       TOut.emitRRX(Mips::DADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
3011                    IDLoc, STI);
3012 
3013     if (UseSrcReg)
3014       TOut.emitRRR(Mips::DADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
3015 
3016     return false;
3017   }
3018 
3019   const MipsMCExpr *HiExpr =
3020       MipsMCExpr::create(MipsMCExpr::MEK_HI, SymExpr, getContext());
3021   const MipsMCExpr *LoExpr =
3022       MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
3023 
3024   // This is the 64-bit symbol address expansion.
3025   if (ABI.ArePtrs64bit() && isGP64bit()) {
3026     // We need AT for the 64-bit expansion in the cases where the optional
3027     // source register is the destination register and for the superscalar
3028     // scheduled form.
3029     //
3030     // If it is not available we exit if the destination is the same as the
3031     // source register.
3032 
3033     const MipsMCExpr *HighestExpr =
3034         MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, SymExpr, getContext());
3035     const MipsMCExpr *HigherExpr =
3036         MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, SymExpr, getContext());
3037 
3038     bool RdRegIsRsReg =
3039         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg);
3040 
3041     if (canUseATReg() && UseSrcReg && RdRegIsRsReg) {
3042       unsigned ATReg = getATReg(IDLoc);
3043 
3044       // If $rs is the same as $rd:
3045       // (d)la $rd, sym($rd) => lui    $at, %highest(sym)
3046       //                        daddiu $at, $at, %higher(sym)
3047       //                        dsll   $at, $at, 16
3048       //                        daddiu $at, $at, %hi(sym)
3049       //                        dsll   $at, $at, 16
3050       //                        daddiu $at, $at, %lo(sym)
3051       //                        daddu  $rd, $at, $rd
3052       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
3053                   STI);
3054       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
3055                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3056       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3057       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr),
3058                    IDLoc, STI);
3059       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3060       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
3061                    IDLoc, STI);
3062       TOut.emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, STI);
3063 
3064       return false;
3065     } else if (canUseATReg() && !RdRegIsRsReg) {
3066       unsigned ATReg = getATReg(IDLoc);
3067 
3068       // If the $rs is different from $rd or if $rs isn't specified and we
3069       // have $at available:
3070       // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
3071       //                            lui    $at, %hi(sym)
3072       //                            daddiu $rd, $rd, %higher(sym)
3073       //                            daddiu $at, $at, %lo(sym)
3074       //                            dsll32 $rd, $rd, 0
3075       //                            daddu  $rd, $rd, $at
3076       //                            (daddu  $rd, $rd, $rs)
3077       //
3078       // Which is preferred for superscalar issue.
3079       TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
3080                   STI);
3081       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
3082       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3083                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3084       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
3085                    IDLoc, STI);
3086       TOut.emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, STI);
3087       TOut.emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, STI);
3088       if (UseSrcReg)
3089         TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI);
3090 
3091       return false;
3092     } else if (!canUseATReg() && !RdRegIsRsReg) {
3093       // Otherwise, synthesize the address in the destination register
3094       // serially:
3095       // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
3096       //                            daddiu $rd, $rd, %higher(sym)
3097       //                            dsll   $rd, $rd, 16
3098       //                            daddiu $rd, $rd, %hi(sym)
3099       //                            dsll   $rd, $rd, 16
3100       //                            daddiu $rd, $rd, %lo(sym)
3101       TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
3102                   STI);
3103       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3104                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3105       TOut.emitRRI(Mips::DSLL, DstReg, DstReg, 16, IDLoc, STI);
3106       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3107                    MCOperand::createExpr(HiExpr), IDLoc, STI);
3108       TOut.emitRRI(Mips::DSLL, DstReg, DstReg, 16, IDLoc, STI);
3109       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3110                    MCOperand::createExpr(LoExpr), IDLoc, STI);
3111       if (UseSrcReg)
3112         TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI);
3113 
3114       return false;
3115     } else {
3116       // We have a case where SrcReg == DstReg and we don't have $at
3117       // available. We can't expand this case, so error out appropriately.
3118       assert(SrcReg == DstReg && !canUseATReg() &&
3119              "Could have expanded dla but didn't?");
3120       reportParseError(IDLoc,
3121                      "pseudo-instruction requires $at, which is not available");
3122       return true;
3123     }
3124   }
3125 
3126   // And now, the 32-bit symbol address expansion:
3127   // If $rs is the same as $rd:
3128   // (d)la $rd, sym($rd)     => lui   $at, %hi(sym)
3129   //                            ori   $at, $at, %lo(sym)
3130   //                            addu  $rd, $at, $rd
3131   // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
3132   // (d)la $rd, sym/sym($rs) => lui   $rd, %hi(sym)
3133   //                            ori   $rd, $rd, %lo(sym)
3134   //                            (addu $rd, $rd, $rs)
3135   unsigned TmpReg = DstReg;
3136   if (UseSrcReg &&
3137       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
3138     // If $rs is the same as $rd, we need to use AT.
3139     // If it is not available we exit.
3140     unsigned ATReg = getATReg(IDLoc);
3141     if (!ATReg)
3142       return true;
3143     TmpReg = ATReg;
3144   }
3145 
3146   TOut.emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
3147   TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
3148                IDLoc, STI);
3149 
3150   if (UseSrcReg)
3151     TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
3152   else
3153     assert(
3154         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg));
3155 
3156   return false;
3157 }
3158 
3159 // Each double-precision register DO-D15 overlaps with two of the single
3160 // precision registers F0-F31. As an example, all of the following hold true:
3161 // D0 + 1 == F1, F1 + 1 == D1, F1 + 1 == F2, depending on the context.
3162 static unsigned nextReg(unsigned Reg) {
3163   if (MipsMCRegisterClasses[Mips::FGR32RegClassID].contains(Reg))
3164     return Reg == (unsigned)Mips::F31 ? (unsigned)Mips::F0 : Reg + 1;
3165   switch (Reg) {
3166   default: llvm_unreachable("Unknown register in assembly macro expansion!");
3167   case Mips::ZERO: return Mips::AT;
3168   case Mips::AT:   return Mips::V0;
3169   case Mips::V0:   return Mips::V1;
3170   case Mips::V1:   return Mips::A0;
3171   case Mips::A0:   return Mips::A1;
3172   case Mips::A1:   return Mips::A2;
3173   case Mips::A2:   return Mips::A3;
3174   case Mips::A3:   return Mips::T0;
3175   case Mips::T0:   return Mips::T1;
3176   case Mips::T1:   return Mips::T2;
3177   case Mips::T2:   return Mips::T3;
3178   case Mips::T3:   return Mips::T4;
3179   case Mips::T4:   return Mips::T5;
3180   case Mips::T5:   return Mips::T6;
3181   case Mips::T6:   return Mips::T7;
3182   case Mips::T7:   return Mips::S0;
3183   case Mips::S0:   return Mips::S1;
3184   case Mips::S1:   return Mips::S2;
3185   case Mips::S2:   return Mips::S3;
3186   case Mips::S3:   return Mips::S4;
3187   case Mips::S4:   return Mips::S5;
3188   case Mips::S5:   return Mips::S6;
3189   case Mips::S6:   return Mips::S7;
3190   case Mips::S7:   return Mips::T8;
3191   case Mips::T8:   return Mips::T9;
3192   case Mips::T9:   return Mips::K0;
3193   case Mips::K0:   return Mips::K1;
3194   case Mips::K1:   return Mips::GP;
3195   case Mips::GP:   return Mips::SP;
3196   case Mips::SP:   return Mips::FP;
3197   case Mips::FP:   return Mips::RA;
3198   case Mips::RA:   return Mips::ZERO;
3199   case Mips::D0:   return Mips::F1;
3200   case Mips::D1:   return Mips::F3;
3201   case Mips::D2:   return Mips::F5;
3202   case Mips::D3:   return Mips::F7;
3203   case Mips::D4:   return Mips::F9;
3204   case Mips::D5:   return Mips::F11;
3205   case Mips::D6:   return Mips::F13;
3206   case Mips::D7:   return Mips::F15;
3207   case Mips::D8:   return Mips::F17;
3208   case Mips::D9:   return Mips::F19;
3209   case Mips::D10:   return Mips::F21;
3210   case Mips::D11:   return Mips::F23;
3211   case Mips::D12:   return Mips::F25;
3212   case Mips::D13:   return Mips::F27;
3213   case Mips::D14:   return Mips::F29;
3214   case Mips::D15:   return Mips::F31;
3215   }
3216 }
3217 
3218 // FIXME: This method is too general. In principle we should compute the number
3219 // of instructions required to synthesize the immediate inline compared to
3220 // synthesizing the address inline and relying on non .text sections.
3221 // For static O32 and N32 this may yield a small benefit, for static N64 this is
3222 // likely to yield a much larger benefit as we have to synthesize a 64bit
3223 // address to load a 64 bit value.
3224 bool MipsAsmParser::emitPartialAddress(MipsTargetStreamer &TOut, SMLoc IDLoc,
3225                                        MCSymbol *Sym) {
3226   unsigned ATReg = getATReg(IDLoc);
3227   if (!ATReg)
3228     return true;
3229 
3230   if(IsPicEnabled) {
3231     const MCExpr *GotSym =
3232         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3233     const MipsMCExpr *GotExpr =
3234         MipsMCExpr::create(MipsMCExpr::MEK_GOT, GotSym, getContext());
3235 
3236     if(isABI_O32() || isABI_N32()) {
3237       TOut.emitRRX(Mips::LW, ATReg, Mips::GP, MCOperand::createExpr(GotExpr),
3238                    IDLoc, STI);
3239     } else { //isABI_N64()
3240       TOut.emitRRX(Mips::LD, ATReg, Mips::GP, MCOperand::createExpr(GotExpr),
3241                    IDLoc, STI);
3242     }
3243   } else { //!IsPicEnabled
3244     const MCExpr *HiSym =
3245         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3246     const MipsMCExpr *HiExpr =
3247         MipsMCExpr::create(MipsMCExpr::MEK_HI, HiSym, getContext());
3248 
3249     // FIXME: This is technically correct but gives a different result to gas,
3250     // but gas is incomplete there (it has a fixme noting it doesn't work with
3251     // 64-bit addresses).
3252     // FIXME: With -msym32 option, the address expansion for N64 should probably
3253     // use the O32 / N32 case. It's safe to use the 64 address expansion as the
3254     // symbol's value is considered sign extended.
3255     if(isABI_O32() || isABI_N32()) {
3256       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
3257     } else { //isABI_N64()
3258       const MCExpr *HighestSym =
3259           MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3260       const MipsMCExpr *HighestExpr =
3261           MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, HighestSym, getContext());
3262       const MCExpr *HigherSym =
3263           MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3264       const MipsMCExpr *HigherExpr =
3265           MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, HigherSym, getContext());
3266 
3267       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
3268                   STI);
3269       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
3270                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3271       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3272       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr),
3273                    IDLoc, STI);
3274       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3275     }
3276   }
3277   return false;
3278 }
3279 
3280 bool MipsAsmParser::expandLoadImmReal(MCInst &Inst, bool IsSingle, bool IsGPR,
3281                                       bool Is64FPU, SMLoc IDLoc,
3282                                       MCStreamer &Out,
3283                                       const MCSubtargetInfo *STI) {
3284   MipsTargetStreamer &TOut = getTargetStreamer();
3285   assert(Inst.getNumOperands() == 2 && "Invalid operand count");
3286   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isImm() &&
3287          "Invalid instruction operand.");
3288 
3289   unsigned FirstReg = Inst.getOperand(0).getReg();
3290   uint64_t ImmOp64 = Inst.getOperand(1).getImm();
3291 
3292   uint32_t HiImmOp64 = (ImmOp64 & 0xffffffff00000000) >> 32;
3293   // If ImmOp64 is AsmToken::Integer type (all bits set to zero in the
3294   // exponent field), convert it to double (e.g. 1 to 1.0)
3295   if ((HiImmOp64 & 0x7ff00000) == 0) {
3296     APFloat RealVal(APFloat::IEEEdouble(), ImmOp64);
3297     ImmOp64 = RealVal.bitcastToAPInt().getZExtValue();
3298   }
3299 
3300   uint32_t LoImmOp64 = ImmOp64 & 0xffffffff;
3301   HiImmOp64 = (ImmOp64 & 0xffffffff00000000) >> 32;
3302 
3303   if (IsSingle) {
3304     // Conversion of a double in an uint64_t to a float in a uint32_t,
3305     // retaining the bit pattern of a float.
3306     uint32_t ImmOp32;
3307     double doubleImm = BitsToDouble(ImmOp64);
3308     float tmp_float = static_cast<float>(doubleImm);
3309     ImmOp32 = FloatToBits(tmp_float);
3310 
3311     if (IsGPR) {
3312       if (loadImmediate(ImmOp32, FirstReg, Mips::NoRegister, true, true, IDLoc,
3313                         Out, STI))
3314         return true;
3315       return false;
3316     } else {
3317       unsigned ATReg = getATReg(IDLoc);
3318       if (!ATReg)
3319         return true;
3320       if (LoImmOp64 == 0) {
3321         if (loadImmediate(ImmOp32, ATReg, Mips::NoRegister, true, true, IDLoc,
3322                           Out, STI))
3323           return true;
3324         TOut.emitRR(Mips::MTC1, FirstReg, ATReg, IDLoc, STI);
3325         return false;
3326       }
3327 
3328       MCSection *CS = getStreamer().getCurrentSectionOnly();
3329       // FIXME: Enhance this expansion to use the .lit4 & .lit8 sections
3330       // where appropriate.
3331       MCSection *ReadOnlySection = getContext().getELFSection(
3332           ".rodata", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3333 
3334       MCSymbol *Sym = getContext().createTempSymbol();
3335       const MCExpr *LoSym =
3336           MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3337       const MipsMCExpr *LoExpr =
3338           MipsMCExpr::create(MipsMCExpr::MEK_LO, LoSym, getContext());
3339 
3340       getStreamer().SwitchSection(ReadOnlySection);
3341       getStreamer().EmitLabel(Sym, IDLoc);
3342       getStreamer().EmitIntValue(ImmOp32, 4);
3343       getStreamer().SwitchSection(CS);
3344 
3345       if(emitPartialAddress(TOut, IDLoc, Sym))
3346         return true;
3347       TOut.emitRRX(Mips::LWC1, FirstReg, ATReg,
3348                    MCOperand::createExpr(LoExpr), IDLoc, STI);
3349     }
3350     return false;
3351   }
3352 
3353   // if(!IsSingle)
3354   unsigned ATReg = getATReg(IDLoc);
3355   if (!ATReg)
3356     return true;
3357 
3358   if (IsGPR) {
3359     if (LoImmOp64 == 0) {
3360       if(isABI_N32() || isABI_N64()) {
3361         if (loadImmediate(HiImmOp64, FirstReg, Mips::NoRegister, false, true,
3362                           IDLoc, Out, STI))
3363           return true;
3364         return false;
3365       } else {
3366         if (loadImmediate(HiImmOp64, FirstReg, Mips::NoRegister, true, true,
3367                         IDLoc, Out, STI))
3368           return true;
3369 
3370         if (loadImmediate(0, nextReg(FirstReg), Mips::NoRegister, true, true,
3371                         IDLoc, Out, STI))
3372           return true;
3373         return false;
3374       }
3375     }
3376 
3377     MCSection *CS = getStreamer().getCurrentSectionOnly();
3378     MCSection *ReadOnlySection = getContext().getELFSection(
3379         ".rodata", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3380 
3381     MCSymbol *Sym = getContext().createTempSymbol();
3382     const MCExpr *LoSym =
3383         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3384     const MipsMCExpr *LoExpr =
3385         MipsMCExpr::create(MipsMCExpr::MEK_LO, LoSym, getContext());
3386 
3387     getStreamer().SwitchSection(ReadOnlySection);
3388     getStreamer().EmitLabel(Sym, IDLoc);
3389     getStreamer().EmitIntValue(HiImmOp64, 4);
3390     getStreamer().EmitIntValue(LoImmOp64, 4);
3391     getStreamer().SwitchSection(CS);
3392 
3393     if(emitPartialAddress(TOut, IDLoc, Sym))
3394       return true;
3395     if(isABI_N64())
3396       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
3397                    MCOperand::createExpr(LoExpr), IDLoc, STI);
3398     else
3399       TOut.emitRRX(Mips::ADDiu, ATReg, ATReg,
3400                    MCOperand::createExpr(LoExpr), IDLoc, STI);
3401 
3402     if(isABI_N32() || isABI_N64())
3403       TOut.emitRRI(Mips::LD, FirstReg, ATReg, 0, IDLoc, STI);
3404     else {
3405       TOut.emitRRI(Mips::LW, FirstReg, ATReg, 0, IDLoc, STI);
3406       TOut.emitRRI(Mips::LW, nextReg(FirstReg), ATReg, 4, IDLoc, STI);
3407     }
3408     return false;
3409   } else { // if(!IsGPR && !IsSingle)
3410     if ((LoImmOp64 == 0) &&
3411         !((HiImmOp64 & 0xffff0000) && (HiImmOp64 & 0x0000ffff))) {
3412       // FIXME: In the case where the constant is zero, we can load the
3413       // register directly from the zero register.
3414       if (loadImmediate(HiImmOp64, ATReg, Mips::NoRegister, true, true, IDLoc,
3415                         Out, STI))
3416         return true;
3417       if (isABI_N32() || isABI_N64())
3418         TOut.emitRR(Mips::DMTC1, FirstReg, ATReg, IDLoc, STI);
3419       else if (hasMips32r2()) {
3420         TOut.emitRR(Mips::MTC1, FirstReg, Mips::ZERO, IDLoc, STI);
3421         TOut.emitRRR(Mips::MTHC1_D32, FirstReg, FirstReg, ATReg, IDLoc, STI);
3422       } else {
3423         TOut.emitRR(Mips::MTC1, nextReg(FirstReg), ATReg, IDLoc, STI);
3424         TOut.emitRR(Mips::MTC1, FirstReg, Mips::ZERO, IDLoc, STI);
3425       }
3426       return false;
3427     }
3428 
3429     MCSection *CS = getStreamer().getCurrentSectionOnly();
3430     // FIXME: Enhance this expansion to use the .lit4 & .lit8 sections
3431     // where appropriate.
3432     MCSection *ReadOnlySection = getContext().getELFSection(
3433         ".rodata", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3434 
3435     MCSymbol *Sym = getContext().createTempSymbol();
3436     const MCExpr *LoSym =
3437         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3438     const MipsMCExpr *LoExpr =
3439         MipsMCExpr::create(MipsMCExpr::MEK_LO, LoSym, getContext());
3440 
3441     getStreamer().SwitchSection(ReadOnlySection);
3442     getStreamer().EmitLabel(Sym, IDLoc);
3443     getStreamer().EmitIntValue(HiImmOp64, 4);
3444     getStreamer().EmitIntValue(LoImmOp64, 4);
3445     getStreamer().SwitchSection(CS);
3446 
3447     if(emitPartialAddress(TOut, IDLoc, Sym))
3448       return true;
3449     TOut.emitRRX(Is64FPU ? Mips::LDC164 : Mips::LDC1, FirstReg, ATReg,
3450                  MCOperand::createExpr(LoExpr), IDLoc, STI);
3451   }
3452   return false;
3453 }
3454 
3455 bool MipsAsmParser::expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
3456                                                MCStreamer &Out,
3457                                                const MCSubtargetInfo *STI) {
3458   MipsTargetStreamer &TOut = getTargetStreamer();
3459 
3460   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
3461          "unexpected number of operands");
3462 
3463   MCOperand Offset = Inst.getOperand(0);
3464   if (Offset.isExpr()) {
3465     Inst.clear();
3466     Inst.setOpcode(Mips::BEQ_MM);
3467     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3468     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3469     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
3470   } else {
3471     assert(Offset.isImm() && "expected immediate operand kind");
3472     if (isInt<11>(Offset.getImm())) {
3473       // If offset fits into 11 bits then this instruction becomes microMIPS
3474       // 16-bit unconditional branch instruction.
3475       if (inMicroMipsMode())
3476         Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM);
3477     } else {
3478       if (!isInt<17>(Offset.getImm()))
3479         return Error(IDLoc, "branch target out of range");
3480       if (OffsetToAlignment(Offset.getImm(), 1LL << 1))
3481         return Error(IDLoc, "branch to misaligned address");
3482       Inst.clear();
3483       Inst.setOpcode(Mips::BEQ_MM);
3484       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3485       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3486       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
3487     }
3488   }
3489   Out.EmitInstruction(Inst, *STI);
3490 
3491   // If .set reorder is active and branch instruction has a delay slot,
3492   // emit a NOP after it.
3493   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3494   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
3495     TOut.emitEmptyDelaySlot(true, IDLoc, STI);
3496 
3497   return false;
3498 }
3499 
3500 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3501                                     const MCSubtargetInfo *STI) {
3502   MipsTargetStreamer &TOut = getTargetStreamer();
3503   const MCOperand &DstRegOp = Inst.getOperand(0);
3504   assert(DstRegOp.isReg() && "expected register operand kind");
3505 
3506   const MCOperand &ImmOp = Inst.getOperand(1);
3507   assert(ImmOp.isImm() && "expected immediate operand kind");
3508 
3509   const MCOperand &MemOffsetOp = Inst.getOperand(2);
3510   assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) &&
3511          "expected immediate or expression operand");
3512 
3513   bool IsLikely = false;
3514 
3515   unsigned OpCode = 0;
3516   switch(Inst.getOpcode()) {
3517     case Mips::BneImm:
3518       OpCode = Mips::BNE;
3519       break;
3520     case Mips::BeqImm:
3521       OpCode = Mips::BEQ;
3522       break;
3523     case Mips::BEQLImmMacro:
3524       OpCode = Mips::BEQL;
3525       IsLikely = true;
3526       break;
3527     case Mips::BNELImmMacro:
3528       OpCode = Mips::BNEL;
3529       IsLikely = true;
3530       break;
3531     default:
3532       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
3533       break;
3534   }
3535 
3536   int64_t ImmValue = ImmOp.getImm();
3537   if (ImmValue == 0) {
3538     if (IsLikely) {
3539       TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO,
3540                    MCOperand::createExpr(MemOffsetOp.getExpr()), IDLoc, STI);
3541       TOut.emitRRI(Mips::SLL, Mips::ZERO, Mips::ZERO, 0, IDLoc, STI);
3542     } else
3543       TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc,
3544               STI);
3545   } else {
3546     warnIfNoMacro(IDLoc);
3547 
3548     unsigned ATReg = getATReg(IDLoc);
3549     if (!ATReg)
3550       return true;
3551 
3552     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true,
3553                       IDLoc, Out, STI))
3554       return true;
3555 
3556     if (IsLikely) {
3557       TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg,
3558               MCOperand::createExpr(MemOffsetOp.getExpr()), IDLoc, STI);
3559       TOut.emitRRI(Mips::SLL, Mips::ZERO, Mips::ZERO, 0, IDLoc, STI);
3560     } else
3561       TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, STI);
3562   }
3563   return false;
3564 }
3565 
3566 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3567                                   const MCSubtargetInfo *STI, bool IsLoad) {
3568   const MCOperand &DstRegOp = Inst.getOperand(0);
3569   assert(DstRegOp.isReg() && "expected register operand kind");
3570   const MCOperand &BaseRegOp = Inst.getOperand(1);
3571   assert(BaseRegOp.isReg() && "expected register operand kind");
3572   const MCOperand &OffsetOp = Inst.getOperand(2);
3573 
3574   MipsTargetStreamer &TOut = getTargetStreamer();
3575   unsigned DstReg = DstRegOp.getReg();
3576   unsigned BaseReg = BaseRegOp.getReg();
3577   unsigned TmpReg = DstReg;
3578 
3579   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
3580   int16_t DstRegClass = Desc.OpInfo[0].RegClass;
3581   unsigned DstRegClassID =
3582       getContext().getRegisterInfo()->getRegClass(DstRegClass).getID();
3583   bool IsGPR = (DstRegClassID == Mips::GPR32RegClassID) ||
3584                (DstRegClassID == Mips::GPR64RegClassID);
3585 
3586   if (!IsLoad || !IsGPR || (BaseReg == DstReg)) {
3587     // At this point we need AT to perform the expansions
3588     // and we exit if it is not available.
3589     TmpReg = getATReg(IDLoc);
3590     if (!TmpReg)
3591       return;
3592   }
3593 
3594   if (OffsetOp.isImm()) {
3595     int64_t LoOffset = OffsetOp.getImm() & 0xffff;
3596     int64_t HiOffset = OffsetOp.getImm() & ~0xffff;
3597 
3598     // If msb of LoOffset is 1(negative number) we must increment
3599     // HiOffset to account for the sign-extension of the low part.
3600     if (LoOffset & 0x8000)
3601       HiOffset += 0x10000;
3602 
3603     bool IsLargeOffset = HiOffset != 0;
3604 
3605     if (IsLargeOffset) {
3606       bool Is32BitImm = (HiOffset >> 32) == 0;
3607       if (loadImmediate(HiOffset, TmpReg, Mips::NoRegister, Is32BitImm, true,
3608                         IDLoc, Out, STI))
3609         return;
3610     }
3611 
3612     if (BaseReg != Mips::ZERO && BaseReg != Mips::ZERO_64)
3613       TOut.emitRRR(isGP64bit() ? Mips::DADDu : Mips::ADDu, TmpReg, TmpReg,
3614                    BaseReg, IDLoc, STI);
3615     TOut.emitRRI(Inst.getOpcode(), DstReg, TmpReg, LoOffset, IDLoc, STI);
3616   } else {
3617     assert(OffsetOp.isExpr() && "expected expression operand kind");
3618     const MCExpr *ExprOffset = OffsetOp.getExpr();
3619     MCOperand LoOperand = MCOperand::createExpr(
3620         MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
3621     MCOperand HiOperand = MCOperand::createExpr(
3622         MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
3623 
3624     if (IsLoad)
3625       TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
3626                                  LoOperand, TmpReg, IDLoc, STI);
3627     else
3628       TOut.emitStoreWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
3629                                   LoOperand, TmpReg, IDLoc, STI);
3630   }
3631 }
3632 
3633 bool MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
3634                                             MCStreamer &Out,
3635                                             const MCSubtargetInfo *STI) {
3636   unsigned OpNum = Inst.getNumOperands();
3637   unsigned Opcode = Inst.getOpcode();
3638   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
3639 
3640   assert(Inst.getOperand(OpNum - 1).isImm() &&
3641          Inst.getOperand(OpNum - 2).isReg() &&
3642          Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
3643 
3644   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
3645       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
3646       (Inst.getOperand(OpNum - 2).getReg() == Mips::SP ||
3647        Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) &&
3648       (Inst.getOperand(OpNum - 3).getReg() == Mips::RA ||
3649        Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) {
3650     // It can be implemented as SWM16 or LWM16 instruction.
3651     if (inMicroMipsMode() && hasMips32r6())
3652       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6;
3653     else
3654       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
3655   }
3656 
3657   Inst.setOpcode(NewOpcode);
3658   Out.EmitInstruction(Inst, *STI);
3659   return false;
3660 }
3661 
3662 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
3663                                        MCStreamer &Out,
3664                                        const MCSubtargetInfo *STI) {
3665   MipsTargetStreamer &TOut = getTargetStreamer();
3666   bool EmittedNoMacroWarning = false;
3667   unsigned PseudoOpcode = Inst.getOpcode();
3668   unsigned SrcReg = Inst.getOperand(0).getReg();
3669   const MCOperand &TrgOp = Inst.getOperand(1);
3670   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
3671 
3672   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
3673   bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality;
3674 
3675   unsigned TrgReg;
3676   if (TrgOp.isReg())
3677     TrgReg = TrgOp.getReg();
3678   else if (TrgOp.isImm()) {
3679     warnIfNoMacro(IDLoc);
3680     EmittedNoMacroWarning = true;
3681 
3682     TrgReg = getATReg(IDLoc);
3683     if (!TrgReg)
3684       return true;
3685 
3686     switch(PseudoOpcode) {
3687     default:
3688       llvm_unreachable("unknown opcode for branch pseudo-instruction");
3689     case Mips::BLTImmMacro:
3690       PseudoOpcode = Mips::BLT;
3691       break;
3692     case Mips::BLEImmMacro:
3693       PseudoOpcode = Mips::BLE;
3694       break;
3695     case Mips::BGEImmMacro:
3696       PseudoOpcode = Mips::BGE;
3697       break;
3698     case Mips::BGTImmMacro:
3699       PseudoOpcode = Mips::BGT;
3700       break;
3701     case Mips::BLTUImmMacro:
3702       PseudoOpcode = Mips::BLTU;
3703       break;
3704     case Mips::BLEUImmMacro:
3705       PseudoOpcode = Mips::BLEU;
3706       break;
3707     case Mips::BGEUImmMacro:
3708       PseudoOpcode = Mips::BGEU;
3709       break;
3710     case Mips::BGTUImmMacro:
3711       PseudoOpcode = Mips::BGTU;
3712       break;
3713     case Mips::BLTLImmMacro:
3714       PseudoOpcode = Mips::BLTL;
3715       break;
3716     case Mips::BLELImmMacro:
3717       PseudoOpcode = Mips::BLEL;
3718       break;
3719     case Mips::BGELImmMacro:
3720       PseudoOpcode = Mips::BGEL;
3721       break;
3722     case Mips::BGTLImmMacro:
3723       PseudoOpcode = Mips::BGTL;
3724       break;
3725     case Mips::BLTULImmMacro:
3726       PseudoOpcode = Mips::BLTUL;
3727       break;
3728     case Mips::BLEULImmMacro:
3729       PseudoOpcode = Mips::BLEUL;
3730       break;
3731     case Mips::BGEULImmMacro:
3732       PseudoOpcode = Mips::BGEUL;
3733       break;
3734     case Mips::BGTULImmMacro:
3735       PseudoOpcode = Mips::BGTUL;
3736       break;
3737     }
3738 
3739     if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(),
3740                       false, IDLoc, Out, STI))
3741       return true;
3742   }
3743 
3744   switch (PseudoOpcode) {
3745   case Mips::BLT:
3746   case Mips::BLTU:
3747   case Mips::BLTL:
3748   case Mips::BLTUL:
3749     AcceptsEquality = false;
3750     ReverseOrderSLT = false;
3751     IsUnsigned =
3752         ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL));
3753     IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL));
3754     ZeroSrcOpcode = Mips::BGTZ;
3755     ZeroTrgOpcode = Mips::BLTZ;
3756     break;
3757   case Mips::BLE:
3758   case Mips::BLEU:
3759   case Mips::BLEL:
3760   case Mips::BLEUL:
3761     AcceptsEquality = true;
3762     ReverseOrderSLT = true;
3763     IsUnsigned =
3764         ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL));
3765     IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL));
3766     ZeroSrcOpcode = Mips::BGEZ;
3767     ZeroTrgOpcode = Mips::BLEZ;
3768     break;
3769   case Mips::BGE:
3770   case Mips::BGEU:
3771   case Mips::BGEL:
3772   case Mips::BGEUL:
3773     AcceptsEquality = true;
3774     ReverseOrderSLT = false;
3775     IsUnsigned =
3776         ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL));
3777     IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL));
3778     ZeroSrcOpcode = Mips::BLEZ;
3779     ZeroTrgOpcode = Mips::BGEZ;
3780     break;
3781   case Mips::BGT:
3782   case Mips::BGTU:
3783   case Mips::BGTL:
3784   case Mips::BGTUL:
3785     AcceptsEquality = false;
3786     ReverseOrderSLT = true;
3787     IsUnsigned =
3788         ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL));
3789     IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL));
3790     ZeroSrcOpcode = Mips::BLTZ;
3791     ZeroTrgOpcode = Mips::BGTZ;
3792     break;
3793   default:
3794     llvm_unreachable("unknown opcode for branch pseudo-instruction");
3795   }
3796 
3797   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
3798   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
3799   if (IsSrcRegZero && IsTrgRegZero) {
3800     // FIXME: All of these Opcode-specific if's are needed for compatibility
3801     // with GAS' behaviour. However, they may not generate the most efficient
3802     // code in some circumstances.
3803     if (PseudoOpcode == Mips::BLT) {
3804       TOut.emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3805                   IDLoc, STI);
3806       return false;
3807     }
3808     if (PseudoOpcode == Mips::BLE) {
3809       TOut.emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3810                   IDLoc, STI);
3811       Warning(IDLoc, "branch is always taken");
3812       return false;
3813     }
3814     if (PseudoOpcode == Mips::BGE) {
3815       TOut.emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3816                   IDLoc, STI);
3817       Warning(IDLoc, "branch is always taken");
3818       return false;
3819     }
3820     if (PseudoOpcode == Mips::BGT) {
3821       TOut.emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3822                   IDLoc, STI);
3823       return false;
3824     }
3825     if (PseudoOpcode == Mips::BGTU) {
3826       TOut.emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO,
3827                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3828       return false;
3829     }
3830     if (AcceptsEquality) {
3831       // If both registers are $0 and the pseudo-branch accepts equality, it
3832       // will always be taken, so we emit an unconditional branch.
3833       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3834                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3835       Warning(IDLoc, "branch is always taken");
3836       return false;
3837     }
3838     // If both registers are $0 and the pseudo-branch does not accept
3839     // equality, it will never be taken, so we don't have to emit anything.
3840     return false;
3841   }
3842   if (IsSrcRegZero || IsTrgRegZero) {
3843     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
3844         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
3845       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
3846       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
3847       // the pseudo-branch will never be taken, so we don't emit anything.
3848       // This only applies to unsigned pseudo-branches.
3849       return false;
3850     }
3851     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
3852         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
3853       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
3854       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
3855       // the pseudo-branch will always be taken, so we emit an unconditional
3856       // branch.
3857       // This only applies to unsigned pseudo-branches.
3858       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3859                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3860       Warning(IDLoc, "branch is always taken");
3861       return false;
3862     }
3863     if (IsUnsigned) {
3864       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
3865       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
3866       // the pseudo-branch will be taken only when the non-zero register is
3867       // different from 0, so we emit a BNEZ.
3868       //
3869       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
3870       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
3871       // the pseudo-branch will be taken only when the non-zero register is
3872       // equal to 0, so we emit a BEQZ.
3873       //
3874       // Because only BLEU and BGEU branch on equality, we can use the
3875       // AcceptsEquality variable to decide when to emit the BEQZ.
3876       TOut.emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE,
3877                    IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO,
3878                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3879       return false;
3880     }
3881     // If we have a signed pseudo-branch and one of the registers is $0,
3882     // we can use an appropriate compare-to-zero branch. We select which one
3883     // to use in the switch statement above.
3884     TOut.emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode,
3885                 IsSrcRegZero ? TrgReg : SrcReg,
3886                 MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3887     return false;
3888   }
3889 
3890   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
3891   // expansions. If it is not available, we return.
3892   unsigned ATRegNum = getATReg(IDLoc);
3893   if (!ATRegNum)
3894     return true;
3895 
3896   if (!EmittedNoMacroWarning)
3897     warnIfNoMacro(IDLoc);
3898 
3899   // SLT fits well with 2 of our 4 pseudo-branches:
3900   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
3901   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
3902   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
3903   // This is accomplished by using a BNEZ with the result of the SLT.
3904   //
3905   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
3906   // and BLE with BGT), so we change the BNEZ into a BEQZ.
3907   // Because only BGE and BLE branch on equality, we can use the
3908   // AcceptsEquality variable to decide when to emit the BEQZ.
3909   // Note that the order of the SLT arguments doesn't change between
3910   // opposites.
3911   //
3912   // The same applies to the unsigned variants, except that SLTu is used
3913   // instead of SLT.
3914   TOut.emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum,
3915                ReverseOrderSLT ? TrgReg : SrcReg,
3916                ReverseOrderSLT ? SrcReg : TrgReg, IDLoc, STI);
3917 
3918   TOut.emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL)
3919                         : (AcceptsEquality ? Mips::BEQ : Mips::BNE),
3920                ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
3921                STI);
3922   return false;
3923 }
3924 
3925 // Expand a integer division macro.
3926 //
3927 // Notably we don't have to emit a warning when encountering $rt as the $zero
3928 // register, or 0 as an immediate. processInstruction() has already done that.
3929 //
3930 // The destination register can only be $zero when expanding (S)DivIMacro or
3931 // D(S)DivMacro.
3932 
3933 bool MipsAsmParser::expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3934                                  const MCSubtargetInfo *STI, const bool IsMips64,
3935                                  const bool Signed) {
3936   MipsTargetStreamer &TOut = getTargetStreamer();
3937 
3938   warnIfNoMacro(IDLoc);
3939 
3940   const MCOperand &RdRegOp = Inst.getOperand(0);
3941   assert(RdRegOp.isReg() && "expected register operand kind");
3942   unsigned RdReg = RdRegOp.getReg();
3943 
3944   const MCOperand &RsRegOp = Inst.getOperand(1);
3945   assert(RsRegOp.isReg() && "expected register operand kind");
3946   unsigned RsReg = RsRegOp.getReg();
3947 
3948   unsigned RtReg;
3949   int64_t ImmValue;
3950 
3951   const MCOperand &RtOp = Inst.getOperand(2);
3952   assert((RtOp.isReg() || RtOp.isImm()) &&
3953          "expected register or immediate operand kind");
3954   if (RtOp.isReg())
3955     RtReg = RtOp.getReg();
3956   else
3957     ImmValue = RtOp.getImm();
3958 
3959   unsigned DivOp;
3960   unsigned ZeroReg;
3961   unsigned SubOp;
3962 
3963   if (IsMips64) {
3964     DivOp = Signed ? Mips::DSDIV : Mips::DUDIV;
3965     ZeroReg = Mips::ZERO_64;
3966     SubOp = Mips::DSUB;
3967   } else {
3968     DivOp = Signed ? Mips::SDIV : Mips::UDIV;
3969     ZeroReg = Mips::ZERO;
3970     SubOp = Mips::SUB;
3971   }
3972 
3973   bool UseTraps = useTraps();
3974 
3975   unsigned Opcode = Inst.getOpcode();
3976   bool isDiv = Opcode == Mips::SDivMacro || Opcode == Mips::SDivIMacro ||
3977                Opcode == Mips::UDivMacro || Opcode == Mips::UDivIMacro ||
3978                Opcode == Mips::DSDivMacro || Opcode == Mips::DSDivIMacro ||
3979                Opcode == Mips::DUDivMacro || Opcode == Mips::DUDivIMacro;
3980 
3981   bool isRem = Opcode == Mips::SRemMacro || Opcode == Mips::SRemIMacro ||
3982                Opcode == Mips::URemMacro || Opcode == Mips::URemIMacro ||
3983                Opcode == Mips::DSRemMacro || Opcode == Mips::DSRemIMacro ||
3984                Opcode == Mips::DURemMacro || Opcode == Mips::DURemIMacro;
3985 
3986   if (RtOp.isImm()) {
3987     unsigned ATReg = getATReg(IDLoc);
3988     if (!ATReg)
3989       return true;
3990 
3991     if (ImmValue == 0) {
3992       if (UseTraps)
3993         TOut.emitRRI(Mips::TEQ, ZeroReg, ZeroReg, 0x7, IDLoc, STI);
3994       else
3995         TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3996       return false;
3997     }
3998 
3999     if (isRem && (ImmValue == 1 || (Signed && (ImmValue == -1)))) {
4000       TOut.emitRRR(Mips::OR, RdReg, ZeroReg, ZeroReg, IDLoc, STI);
4001       return false;
4002     } else if (isDiv && ImmValue == 1) {
4003       TOut.emitRRR(Mips::OR, RdReg, RsReg, Mips::ZERO, IDLoc, STI);
4004       return false;
4005     } else if (isDiv && Signed && ImmValue == -1) {
4006       TOut.emitRRR(SubOp, RdReg, ZeroReg, RsReg, IDLoc, STI);
4007       return false;
4008     } else {
4009       if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, isInt<32>(ImmValue),
4010                         false, Inst.getLoc(), Out, STI))
4011         return true;
4012       TOut.emitRR(DivOp, RsReg, ATReg, IDLoc, STI);
4013       TOut.emitR(isDiv ? Mips::MFLO : Mips::MFHI, RdReg, IDLoc, STI);
4014       return false;
4015     }
4016     return true;
4017   }
4018 
4019   // If the macro expansion of (d)div(u) or (d)rem(u) would always trap or
4020   // break, insert the trap/break and exit. This gives a different result to
4021   // GAS. GAS has an inconsistency/missed optimization in that not all cases
4022   // are handled equivalently. As the observed behaviour is the same, we're ok.
4023   if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) {
4024     if (UseTraps) {
4025       TOut.emitRRI(Mips::TEQ, ZeroReg, ZeroReg, 0x7, IDLoc, STI);
4026       return false;
4027     }
4028     TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
4029     return false;
4030   }
4031 
4032   // (d)rem(u) $0, $X, $Y is a special case. Like div $zero, $X, $Y, it does
4033   // not expand to macro sequence.
4034   if (isRem && (RdReg == Mips::ZERO || RdReg == Mips::ZERO_64)) {
4035     TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
4036     return false;
4037   }
4038 
4039   // Temporary label for first branch traget
4040   MCContext &Context = TOut.getStreamer().getContext();
4041   MCSymbol *BrTarget;
4042   MCOperand LabelOp;
4043 
4044   if (UseTraps) {
4045     TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
4046   } else {
4047     // Branch to the li instruction.
4048     BrTarget = Context.createTempSymbol();
4049     LabelOp = MCOperand::createExpr(MCSymbolRefExpr::create(BrTarget, Context));
4050     TOut.emitRRX(Mips::BNE, RtReg, ZeroReg, LabelOp, IDLoc, STI);
4051   }
4052 
4053   TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
4054 
4055   if (!UseTraps)
4056     TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
4057 
4058   if (!Signed) {
4059     if (!UseTraps)
4060       TOut.getStreamer().EmitLabel(BrTarget);
4061 
4062     TOut.emitR(isDiv ? Mips::MFLO : Mips::MFHI, RdReg, IDLoc, STI);
4063     return false;
4064   }
4065 
4066   unsigned ATReg = getATReg(IDLoc);
4067   if (!ATReg)
4068     return true;
4069 
4070   if (!UseTraps)
4071     TOut.getStreamer().EmitLabel(BrTarget);
4072 
4073   TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, STI);
4074 
4075   // Temporary label for the second branch target.
4076   MCSymbol *BrTargetEnd = Context.createTempSymbol();
4077   MCOperand LabelOpEnd =
4078       MCOperand::createExpr(MCSymbolRefExpr::create(BrTargetEnd, Context));
4079 
4080   // Branch to the mflo instruction.
4081   TOut.emitRRX(Mips::BNE, RtReg, ATReg, LabelOpEnd, IDLoc, STI);
4082 
4083   if (IsMips64) {
4084     TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, STI);
4085     TOut.emitDSLL(ATReg, ATReg, 63, IDLoc, STI);
4086   } else {
4087     TOut.emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, STI);
4088   }
4089 
4090   if (UseTraps)
4091     TOut.emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, STI);
4092   else {
4093     // Branch to the mflo instruction.
4094     TOut.emitRRX(Mips::BNE, RsReg, ATReg, LabelOpEnd, IDLoc, STI);
4095     TOut.emitNop(IDLoc, STI);
4096     TOut.emitII(Mips::BREAK, 0x6, 0, IDLoc, STI);
4097   }
4098 
4099   TOut.getStreamer().EmitLabel(BrTargetEnd);
4100   TOut.emitR(isDiv ? Mips::MFLO : Mips::MFHI, RdReg, IDLoc, STI);
4101   return false;
4102 }
4103 
4104 bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU,
4105                                 SMLoc IDLoc, MCStreamer &Out,
4106                                 const MCSubtargetInfo *STI) {
4107   MipsTargetStreamer &TOut = getTargetStreamer();
4108 
4109   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4110   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() &&
4111          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
4112 
4113   unsigned FirstReg = Inst.getOperand(0).getReg();
4114   unsigned SecondReg = Inst.getOperand(1).getReg();
4115   unsigned ThirdReg = Inst.getOperand(2).getReg();
4116 
4117   if (hasMips1() && !hasMips2()) {
4118     unsigned ATReg = getATReg(IDLoc);
4119     if (!ATReg)
4120       return true;
4121     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
4122     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
4123     TOut.emitNop(IDLoc, STI);
4124     TOut.emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, STI);
4125     TOut.emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, STI);
4126     TOut.emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, STI);
4127     TOut.emitNop(IDLoc, STI);
4128     TOut.emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32)
4129                          : Mips::CVT_W_S,
4130                 FirstReg, SecondReg, IDLoc, STI);
4131     TOut.emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, STI);
4132     TOut.emitNop(IDLoc, STI);
4133     return false;
4134   }
4135 
4136   TOut.emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32)
4137                        : Mips::TRUNC_W_S,
4138               FirstReg, SecondReg, IDLoc, STI);
4139 
4140   return false;
4141 }
4142 
4143 bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
4144                               MCStreamer &Out, const MCSubtargetInfo *STI) {
4145   if (hasMips32r6() || hasMips64r6()) {
4146     return Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
4147   }
4148 
4149   const MCOperand &DstRegOp = Inst.getOperand(0);
4150   assert(DstRegOp.isReg() && "expected register operand kind");
4151   const MCOperand &SrcRegOp = Inst.getOperand(1);
4152   assert(SrcRegOp.isReg() && "expected register operand kind");
4153   const MCOperand &OffsetImmOp = Inst.getOperand(2);
4154   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
4155 
4156   MipsTargetStreamer &TOut = getTargetStreamer();
4157   unsigned DstReg = DstRegOp.getReg();
4158   unsigned SrcReg = SrcRegOp.getReg();
4159   int64_t OffsetValue = OffsetImmOp.getImm();
4160 
4161   // NOTE: We always need AT for ULHU, as it is always used as the source
4162   // register for one of the LBu's.
4163   warnIfNoMacro(IDLoc);
4164   unsigned ATReg = getATReg(IDLoc);
4165   if (!ATReg)
4166     return true;
4167 
4168   bool IsLargeOffset = !(isInt<16>(OffsetValue + 1) && isInt<16>(OffsetValue));
4169   if (IsLargeOffset) {
4170     if (loadImmediate(OffsetValue, ATReg, SrcReg, !ABI.ArePtrs64bit(), true,
4171                       IDLoc, Out, STI))
4172       return true;
4173   }
4174 
4175   int64_t FirstOffset = IsLargeOffset ? 0 : OffsetValue;
4176   int64_t SecondOffset = IsLargeOffset ? 1 : (OffsetValue + 1);
4177   if (isLittle())
4178     std::swap(FirstOffset, SecondOffset);
4179 
4180   unsigned FirstLbuDstReg = IsLargeOffset ? DstReg : ATReg;
4181   unsigned SecondLbuDstReg = IsLargeOffset ? ATReg : DstReg;
4182 
4183   unsigned LbuSrcReg = IsLargeOffset ? ATReg : SrcReg;
4184   unsigned SllReg = IsLargeOffset ? DstReg : ATReg;
4185 
4186   TOut.emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg,
4187                FirstOffset, IDLoc, STI);
4188   TOut.emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondOffset, IDLoc, STI);
4189   TOut.emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, STI);
4190   TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI);
4191 
4192   return false;
4193 }
4194 
4195 bool MipsAsmParser::expandUsh(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4196                               const MCSubtargetInfo *STI) {
4197   if (hasMips32r6() || hasMips64r6()) {
4198     return Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
4199   }
4200 
4201   const MCOperand &DstRegOp = Inst.getOperand(0);
4202   assert(DstRegOp.isReg() && "expected register operand kind");
4203   const MCOperand &SrcRegOp = Inst.getOperand(1);
4204   assert(SrcRegOp.isReg() && "expected register operand kind");
4205   const MCOperand &OffsetImmOp = Inst.getOperand(2);
4206   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
4207 
4208   MipsTargetStreamer &TOut = getTargetStreamer();
4209   unsigned DstReg = DstRegOp.getReg();
4210   unsigned SrcReg = SrcRegOp.getReg();
4211   int64_t OffsetValue = OffsetImmOp.getImm();
4212 
4213   warnIfNoMacro(IDLoc);
4214   unsigned ATReg = getATReg(IDLoc);
4215   if (!ATReg)
4216     return true;
4217 
4218   bool IsLargeOffset = !(isInt<16>(OffsetValue + 1) && isInt<16>(OffsetValue));
4219   if (IsLargeOffset) {
4220     if (loadImmediate(OffsetValue, ATReg, SrcReg, !ABI.ArePtrs64bit(), true,
4221                       IDLoc, Out, STI))
4222       return true;
4223   }
4224 
4225   int64_t FirstOffset = IsLargeOffset ? 1 : (OffsetValue + 1);
4226   int64_t SecondOffset = IsLargeOffset ? 0 : OffsetValue;
4227   if (isLittle())
4228     std::swap(FirstOffset, SecondOffset);
4229 
4230   if (IsLargeOffset) {
4231     TOut.emitRRI(Mips::SB, DstReg, ATReg, FirstOffset, IDLoc, STI);
4232     TOut.emitRRI(Mips::SRL, DstReg, DstReg, 8, IDLoc, STI);
4233     TOut.emitRRI(Mips::SB, DstReg, ATReg, SecondOffset, IDLoc, STI);
4234     TOut.emitRRI(Mips::LBu, ATReg, ATReg, 0, IDLoc, STI);
4235     TOut.emitRRI(Mips::SLL, DstReg, DstReg, 8, IDLoc, STI);
4236     TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI);
4237   } else {
4238     TOut.emitRRI(Mips::SB, DstReg, SrcReg, FirstOffset, IDLoc, STI);
4239     TOut.emitRRI(Mips::SRL, ATReg, DstReg, 8, IDLoc, STI);
4240     TOut.emitRRI(Mips::SB, ATReg, SrcReg, SecondOffset, IDLoc, STI);
4241   }
4242 
4243   return false;
4244 }
4245 
4246 bool MipsAsmParser::expandUxw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4247                               const MCSubtargetInfo *STI) {
4248   if (hasMips32r6() || hasMips64r6()) {
4249     return Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
4250   }
4251 
4252   const MCOperand &DstRegOp = Inst.getOperand(0);
4253   assert(DstRegOp.isReg() && "expected register operand kind");
4254   const MCOperand &SrcRegOp = Inst.getOperand(1);
4255   assert(SrcRegOp.isReg() && "expected register operand kind");
4256   const MCOperand &OffsetImmOp = Inst.getOperand(2);
4257   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
4258 
4259   MipsTargetStreamer &TOut = getTargetStreamer();
4260   unsigned DstReg = DstRegOp.getReg();
4261   unsigned SrcReg = SrcRegOp.getReg();
4262   int64_t OffsetValue = OffsetImmOp.getImm();
4263 
4264   // Compute left/right load/store offsets.
4265   bool IsLargeOffset = !(isInt<16>(OffsetValue + 3) && isInt<16>(OffsetValue));
4266   int64_t LxlOffset = IsLargeOffset ? 0 : OffsetValue;
4267   int64_t LxrOffset = IsLargeOffset ? 3 : (OffsetValue + 3);
4268   if (isLittle())
4269     std::swap(LxlOffset, LxrOffset);
4270 
4271   bool IsLoadInst = (Inst.getOpcode() == Mips::Ulw);
4272   bool DoMove = IsLoadInst && (SrcReg == DstReg) && !IsLargeOffset;
4273   unsigned TmpReg = SrcReg;
4274   if (IsLargeOffset || DoMove) {
4275     warnIfNoMacro(IDLoc);
4276     TmpReg = getATReg(IDLoc);
4277     if (!TmpReg)
4278       return true;
4279   }
4280 
4281   if (IsLargeOffset) {
4282     if (loadImmediate(OffsetValue, TmpReg, SrcReg, !ABI.ArePtrs64bit(), true,
4283                       IDLoc, Out, STI))
4284       return true;
4285   }
4286 
4287   if (DoMove)
4288     std::swap(DstReg, TmpReg);
4289 
4290   unsigned XWL = IsLoadInst ? Mips::LWL : Mips::SWL;
4291   unsigned XWR = IsLoadInst ? Mips::LWR : Mips::SWR;
4292   TOut.emitRRI(XWL, DstReg, TmpReg, LxlOffset, IDLoc, STI);
4293   TOut.emitRRI(XWR, DstReg, TmpReg, LxrOffset, IDLoc, STI);
4294 
4295   if (DoMove)
4296     TOut.emitRRR(Mips::OR, TmpReg, DstReg, Mips::ZERO, IDLoc, STI);
4297 
4298   return false;
4299 }
4300 
4301 bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
4302                                          MCStreamer &Out,
4303                                          const MCSubtargetInfo *STI) {
4304   MipsTargetStreamer &TOut = getTargetStreamer();
4305 
4306   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4307   assert(Inst.getOperand(0).isReg() &&
4308          Inst.getOperand(1).isReg() &&
4309          Inst.getOperand(2).isImm() && "Invalid instruction operand.");
4310 
4311   unsigned ATReg = Mips::NoRegister;
4312   unsigned FinalDstReg = Mips::NoRegister;
4313   unsigned DstReg = Inst.getOperand(0).getReg();
4314   unsigned SrcReg = Inst.getOperand(1).getReg();
4315   int64_t ImmValue = Inst.getOperand(2).getImm();
4316 
4317   bool Is32Bit = isInt<32>(ImmValue) || (!isGP64bit() && isUInt<32>(ImmValue));
4318 
4319   unsigned FinalOpcode = Inst.getOpcode();
4320 
4321   if (DstReg == SrcReg) {
4322     ATReg = getATReg(Inst.getLoc());
4323     if (!ATReg)
4324       return true;
4325     FinalDstReg = DstReg;
4326     DstReg = ATReg;
4327   }
4328 
4329   if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false,
4330                      Inst.getLoc(), Out, STI)) {
4331     switch (FinalOpcode) {
4332     default:
4333       llvm_unreachable("unimplemented expansion");
4334     case Mips::ADDi:
4335       FinalOpcode = Mips::ADD;
4336       break;
4337     case Mips::ADDiu:
4338       FinalOpcode = Mips::ADDu;
4339       break;
4340     case Mips::ANDi:
4341       FinalOpcode = Mips::AND;
4342       break;
4343     case Mips::NORImm:
4344       FinalOpcode = Mips::NOR;
4345       break;
4346     case Mips::ORi:
4347       FinalOpcode = Mips::OR;
4348       break;
4349     case Mips::SLTi:
4350       FinalOpcode = Mips::SLT;
4351       break;
4352     case Mips::SLTiu:
4353       FinalOpcode = Mips::SLTu;
4354       break;
4355     case Mips::XORi:
4356       FinalOpcode = Mips::XOR;
4357       break;
4358     case Mips::ADDi_MM:
4359       FinalOpcode = Mips::ADD_MM;
4360       break;
4361     case Mips::ADDiu_MM:
4362       FinalOpcode = Mips::ADDu_MM;
4363       break;
4364     case Mips::ANDi_MM:
4365       FinalOpcode = Mips::AND_MM;
4366       break;
4367     case Mips::ORi_MM:
4368       FinalOpcode = Mips::OR_MM;
4369       break;
4370     case Mips::SLTi_MM:
4371       FinalOpcode = Mips::SLT_MM;
4372       break;
4373     case Mips::SLTiu_MM:
4374       FinalOpcode = Mips::SLTu_MM;
4375       break;
4376     case Mips::XORi_MM:
4377       FinalOpcode = Mips::XOR_MM;
4378       break;
4379     case Mips::ANDi64:
4380       FinalOpcode = Mips::AND64;
4381       break;
4382     case Mips::NORImm64:
4383       FinalOpcode = Mips::NOR64;
4384       break;
4385     case Mips::ORi64:
4386       FinalOpcode = Mips::OR64;
4387       break;
4388     case Mips::SLTImm64:
4389       FinalOpcode = Mips::SLT64;
4390       break;
4391     case Mips::SLTUImm64:
4392       FinalOpcode = Mips::SLTu64;
4393       break;
4394     case Mips::XORi64:
4395       FinalOpcode = Mips::XOR64;
4396       break;
4397     }
4398 
4399     if (FinalDstReg == Mips::NoRegister)
4400       TOut.emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, STI);
4401     else
4402       TOut.emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc, STI);
4403     return false;
4404   }
4405   return true;
4406 }
4407 
4408 bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4409                                    const MCSubtargetInfo *STI) {
4410   MipsTargetStreamer &TOut = getTargetStreamer();
4411   unsigned ATReg = Mips::NoRegister;
4412   unsigned DReg = Inst.getOperand(0).getReg();
4413   unsigned SReg = Inst.getOperand(1).getReg();
4414   unsigned TReg = Inst.getOperand(2).getReg();
4415   unsigned TmpReg = DReg;
4416 
4417   unsigned FirstShift = Mips::NOP;
4418   unsigned SecondShift = Mips::NOP;
4419 
4420   if (hasMips32r2()) {
4421     if (DReg == SReg) {
4422       TmpReg = getATReg(Inst.getLoc());
4423       if (!TmpReg)
4424         return true;
4425     }
4426 
4427     if (Inst.getOpcode() == Mips::ROL) {
4428       TOut.emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4429       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
4430       return false;
4431     }
4432 
4433     if (Inst.getOpcode() == Mips::ROR) {
4434       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
4435       return false;
4436     }
4437 
4438     return true;
4439   }
4440 
4441   if (hasMips32()) {
4442     switch (Inst.getOpcode()) {
4443     default:
4444       llvm_unreachable("unexpected instruction opcode");
4445     case Mips::ROL:
4446       FirstShift = Mips::SRLV;
4447       SecondShift = Mips::SLLV;
4448       break;
4449     case Mips::ROR:
4450       FirstShift = Mips::SLLV;
4451       SecondShift = Mips::SRLV;
4452       break;
4453     }
4454 
4455     ATReg = getATReg(Inst.getLoc());
4456     if (!ATReg)
4457       return true;
4458 
4459     TOut.emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4460     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
4461     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
4462     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4463 
4464     return false;
4465   }
4466 
4467   return true;
4468 }
4469 
4470 bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc,
4471                                       MCStreamer &Out,
4472                                       const MCSubtargetInfo *STI) {
4473   MipsTargetStreamer &TOut = getTargetStreamer();
4474   unsigned ATReg = Mips::NoRegister;
4475   unsigned DReg = Inst.getOperand(0).getReg();
4476   unsigned SReg = Inst.getOperand(1).getReg();
4477   int64_t ImmValue = Inst.getOperand(2).getImm();
4478 
4479   unsigned FirstShift = Mips::NOP;
4480   unsigned SecondShift = Mips::NOP;
4481 
4482   if (hasMips32r2()) {
4483     if (Inst.getOpcode() == Mips::ROLImm) {
4484       uint64_t MaxShift = 32;
4485       uint64_t ShiftValue = ImmValue;
4486       if (ImmValue != 0)
4487         ShiftValue = MaxShift - ImmValue;
4488       TOut.emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
4489       return false;
4490     }
4491 
4492     if (Inst.getOpcode() == Mips::RORImm) {
4493       TOut.emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), STI);
4494       return false;
4495     }
4496 
4497     return true;
4498   }
4499 
4500   if (hasMips32()) {
4501     if (ImmValue == 0) {
4502       TOut.emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), STI);
4503       return false;
4504     }
4505 
4506     switch (Inst.getOpcode()) {
4507     default:
4508       llvm_unreachable("unexpected instruction opcode");
4509     case Mips::ROLImm:
4510       FirstShift = Mips::SLL;
4511       SecondShift = Mips::SRL;
4512       break;
4513     case Mips::RORImm:
4514       FirstShift = Mips::SRL;
4515       SecondShift = Mips::SLL;
4516       break;
4517     }
4518 
4519     ATReg = getATReg(Inst.getLoc());
4520     if (!ATReg)
4521       return true;
4522 
4523     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), STI);
4524     TOut.emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), STI);
4525     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4526 
4527     return false;
4528   }
4529 
4530   return true;
4531 }
4532 
4533 bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4534                                     const MCSubtargetInfo *STI) {
4535   MipsTargetStreamer &TOut = getTargetStreamer();
4536   unsigned ATReg = Mips::NoRegister;
4537   unsigned DReg = Inst.getOperand(0).getReg();
4538   unsigned SReg = Inst.getOperand(1).getReg();
4539   unsigned TReg = Inst.getOperand(2).getReg();
4540   unsigned TmpReg = DReg;
4541 
4542   unsigned FirstShift = Mips::NOP;
4543   unsigned SecondShift = Mips::NOP;
4544 
4545   if (hasMips64r2()) {
4546     if (TmpReg == SReg) {
4547       TmpReg = getATReg(Inst.getLoc());
4548       if (!TmpReg)
4549         return true;
4550     }
4551 
4552     if (Inst.getOpcode() == Mips::DROL) {
4553       TOut.emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4554       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
4555       return false;
4556     }
4557 
4558     if (Inst.getOpcode() == Mips::DROR) {
4559       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
4560       return false;
4561     }
4562 
4563     return true;
4564   }
4565 
4566   if (hasMips64()) {
4567     switch (Inst.getOpcode()) {
4568     default:
4569       llvm_unreachable("unexpected instruction opcode");
4570     case Mips::DROL:
4571       FirstShift = Mips::DSRLV;
4572       SecondShift = Mips::DSLLV;
4573       break;
4574     case Mips::DROR:
4575       FirstShift = Mips::DSLLV;
4576       SecondShift = Mips::DSRLV;
4577       break;
4578     }
4579 
4580     ATReg = getATReg(Inst.getLoc());
4581     if (!ATReg)
4582       return true;
4583 
4584     TOut.emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4585     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
4586     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
4587     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4588 
4589     return false;
4590   }
4591 
4592   return true;
4593 }
4594 
4595 bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
4596                                        MCStreamer &Out,
4597                                        const MCSubtargetInfo *STI) {
4598   MipsTargetStreamer &TOut = getTargetStreamer();
4599   unsigned ATReg = Mips::NoRegister;
4600   unsigned DReg = Inst.getOperand(0).getReg();
4601   unsigned SReg = Inst.getOperand(1).getReg();
4602   int64_t ImmValue = Inst.getOperand(2).getImm() % 64;
4603 
4604   unsigned FirstShift = Mips::NOP;
4605   unsigned SecondShift = Mips::NOP;
4606 
4607   MCInst TmpInst;
4608 
4609   if (hasMips64r2()) {
4610     unsigned FinalOpcode = Mips::NOP;
4611     if (ImmValue == 0)
4612       FinalOpcode = Mips::DROTR;
4613     else if (ImmValue % 32 == 0)
4614       FinalOpcode = Mips::DROTR32;
4615     else if ((ImmValue >= 1) && (ImmValue <= 32)) {
4616       if (Inst.getOpcode() == Mips::DROLImm)
4617         FinalOpcode = Mips::DROTR32;
4618       else
4619         FinalOpcode = Mips::DROTR;
4620     } else if (ImmValue >= 33) {
4621       if (Inst.getOpcode() == Mips::DROLImm)
4622         FinalOpcode = Mips::DROTR;
4623       else
4624         FinalOpcode = Mips::DROTR32;
4625     }
4626 
4627     uint64_t ShiftValue = ImmValue % 32;
4628     if (Inst.getOpcode() == Mips::DROLImm)
4629       ShiftValue = (32 - ImmValue % 32) % 32;
4630 
4631     TOut.emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
4632 
4633     return false;
4634   }
4635 
4636   if (hasMips64()) {
4637     if (ImmValue == 0) {
4638       TOut.emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), STI);
4639       return false;
4640     }
4641 
4642     switch (Inst.getOpcode()) {
4643     default:
4644       llvm_unreachable("unexpected instruction opcode");
4645     case Mips::DROLImm:
4646       if ((ImmValue >= 1) && (ImmValue <= 31)) {
4647         FirstShift = Mips::DSLL;
4648         SecondShift = Mips::DSRL32;
4649       }
4650       if (ImmValue == 32) {
4651         FirstShift = Mips::DSLL32;
4652         SecondShift = Mips::DSRL32;
4653       }
4654       if ((ImmValue >= 33) && (ImmValue <= 63)) {
4655         FirstShift = Mips::DSLL32;
4656         SecondShift = Mips::DSRL;
4657       }
4658       break;
4659     case Mips::DRORImm:
4660       if ((ImmValue >= 1) && (ImmValue <= 31)) {
4661         FirstShift = Mips::DSRL;
4662         SecondShift = Mips::DSLL32;
4663       }
4664       if (ImmValue == 32) {
4665         FirstShift = Mips::DSRL32;
4666         SecondShift = Mips::DSLL32;
4667       }
4668       if ((ImmValue >= 33) && (ImmValue <= 63)) {
4669         FirstShift = Mips::DSRL32;
4670         SecondShift = Mips::DSLL;
4671       }
4672       break;
4673     }
4674 
4675     ATReg = getATReg(Inst.getLoc());
4676     if (!ATReg)
4677       return true;
4678 
4679     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), STI);
4680     TOut.emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32,
4681                  Inst.getLoc(), STI);
4682     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4683 
4684     return false;
4685   }
4686 
4687   return true;
4688 }
4689 
4690 bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4691                               const MCSubtargetInfo *STI) {
4692   MipsTargetStreamer &TOut = getTargetStreamer();
4693   unsigned FirstRegOp = Inst.getOperand(0).getReg();
4694   unsigned SecondRegOp = Inst.getOperand(1).getReg();
4695 
4696   TOut.emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, STI);
4697   if (FirstRegOp != SecondRegOp)
4698     TOut.emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, STI);
4699   else
4700     TOut.emitEmptyDelaySlot(false, IDLoc, STI);
4701   TOut.emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, STI);
4702 
4703   return false;
4704 }
4705 
4706 bool MipsAsmParser::expandMulImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4707                                  const MCSubtargetInfo *STI) {
4708   MipsTargetStreamer &TOut = getTargetStreamer();
4709   unsigned ATReg = Mips::NoRegister;
4710   unsigned DstReg = Inst.getOperand(0).getReg();
4711   unsigned SrcReg = Inst.getOperand(1).getReg();
4712   int32_t ImmValue = Inst.getOperand(2).getImm();
4713 
4714   ATReg = getATReg(IDLoc);
4715   if (!ATReg)
4716     return true;
4717 
4718   loadImmediate(ImmValue, ATReg, Mips::NoRegister, true, false, IDLoc, Out,
4719                 STI);
4720 
4721   TOut.emitRR(Inst.getOpcode() == Mips::MULImmMacro ? Mips::MULT : Mips::DMULT,
4722               SrcReg, ATReg, IDLoc, STI);
4723 
4724   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
4725 
4726   return false;
4727 }
4728 
4729 bool MipsAsmParser::expandMulO(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4730                                const MCSubtargetInfo *STI) {
4731   MipsTargetStreamer &TOut = getTargetStreamer();
4732   unsigned ATReg = Mips::NoRegister;
4733   unsigned DstReg = Inst.getOperand(0).getReg();
4734   unsigned SrcReg = Inst.getOperand(1).getReg();
4735   unsigned TmpReg = Inst.getOperand(2).getReg();
4736 
4737   ATReg = getATReg(Inst.getLoc());
4738   if (!ATReg)
4739     return true;
4740 
4741   TOut.emitRR(Inst.getOpcode() == Mips::MULOMacro ? Mips::MULT : Mips::DMULT,
4742               SrcReg, TmpReg, IDLoc, STI);
4743 
4744   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
4745 
4746   TOut.emitRRI(Inst.getOpcode() == Mips::MULOMacro ? Mips::SRA : Mips::DSRA32,
4747                DstReg, DstReg, 0x1F, IDLoc, STI);
4748 
4749   TOut.emitR(Mips::MFHI, ATReg, IDLoc, STI);
4750 
4751   if (useTraps()) {
4752     TOut.emitRRI(Mips::TNE, DstReg, ATReg, 6, IDLoc, STI);
4753   } else {
4754     MCContext & Context = TOut.getStreamer().getContext();
4755     MCSymbol * BrTarget = Context.createTempSymbol();
4756     MCOperand LabelOp =
4757         MCOperand::createExpr(MCSymbolRefExpr::create(BrTarget, Context));
4758 
4759     TOut.emitRRX(Mips::BEQ, DstReg, ATReg, LabelOp, IDLoc, STI);
4760     if (AssemblerOptions.back()->isReorder())
4761       TOut.emitNop(IDLoc, STI);
4762     TOut.emitII(Mips::BREAK, 6, 0, IDLoc, STI);
4763 
4764     TOut.getStreamer().EmitLabel(BrTarget);
4765   }
4766   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
4767 
4768   return false;
4769 }
4770 
4771 bool MipsAsmParser::expandMulOU(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4772                                 const MCSubtargetInfo *STI) {
4773   MipsTargetStreamer &TOut = getTargetStreamer();
4774   unsigned ATReg = Mips::NoRegister;
4775   unsigned DstReg = Inst.getOperand(0).getReg();
4776   unsigned SrcReg = Inst.getOperand(1).getReg();
4777   unsigned TmpReg = Inst.getOperand(2).getReg();
4778 
4779   ATReg = getATReg(IDLoc);
4780   if (!ATReg)
4781     return true;
4782 
4783   TOut.emitRR(Inst.getOpcode() == Mips::MULOUMacro ? Mips::MULTu : Mips::DMULTu,
4784               SrcReg, TmpReg, IDLoc, STI);
4785 
4786   TOut.emitR(Mips::MFHI, ATReg, IDLoc, STI);
4787   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
4788   if (useTraps()) {
4789     TOut.emitRRI(Mips::TNE, ATReg, Mips::ZERO, 6, IDLoc, STI);
4790   } else {
4791     MCContext & Context = TOut.getStreamer().getContext();
4792     MCSymbol * BrTarget = Context.createTempSymbol();
4793     MCOperand LabelOp =
4794         MCOperand::createExpr(MCSymbolRefExpr::create(BrTarget, Context));
4795 
4796     TOut.emitRRX(Mips::BEQ, ATReg, Mips::ZERO, LabelOp, IDLoc, STI);
4797     if (AssemblerOptions.back()->isReorder())
4798       TOut.emitNop(IDLoc, STI);
4799     TOut.emitII(Mips::BREAK, 6, 0, IDLoc, STI);
4800 
4801     TOut.getStreamer().EmitLabel(BrTarget);
4802   }
4803 
4804   return false;
4805 }
4806 
4807 bool MipsAsmParser::expandDMULMacro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4808                                     const MCSubtargetInfo *STI) {
4809   MipsTargetStreamer &TOut = getTargetStreamer();
4810   unsigned DstReg = Inst.getOperand(0).getReg();
4811   unsigned SrcReg = Inst.getOperand(1).getReg();
4812   unsigned TmpReg = Inst.getOperand(2).getReg();
4813 
4814   TOut.emitRR(Mips::DMULTu, SrcReg, TmpReg, IDLoc, STI);
4815   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
4816 
4817   return false;
4818 }
4819 
4820 // Expand 'ld $<reg> offset($reg2)' to 'lw $<reg>, offset($reg2);
4821 //                                      lw $<reg+1>>, offset+4($reg2)'
4822 // or expand 'sd $<reg> offset($reg2)' to 'sw $<reg>, offset($reg2);
4823 //                                         sw $<reg+1>>, offset+4($reg2)'
4824 // for O32.
4825 bool MipsAsmParser::expandLoadStoreDMacro(MCInst &Inst, SMLoc IDLoc,
4826                                           MCStreamer &Out,
4827                                           const MCSubtargetInfo *STI,
4828                                           bool IsLoad) {
4829   if (!isABI_O32())
4830     return true;
4831 
4832   warnIfNoMacro(IDLoc);
4833 
4834   MipsTargetStreamer &TOut = getTargetStreamer();
4835   unsigned Opcode = IsLoad ? Mips::LW : Mips::SW;
4836   unsigned FirstReg = Inst.getOperand(0).getReg();
4837   unsigned SecondReg = nextReg(FirstReg);
4838   unsigned BaseReg = Inst.getOperand(1).getReg();
4839   if (!SecondReg)
4840     return true;
4841 
4842   warnIfRegIndexIsAT(FirstReg, IDLoc);
4843 
4844   assert(Inst.getOperand(2).isImm() &&
4845          "Offset for load macro is not immediate!");
4846 
4847   MCOperand &FirstOffset = Inst.getOperand(2);
4848   signed NextOffset = FirstOffset.getImm() + 4;
4849   MCOperand SecondOffset = MCOperand::createImm(NextOffset);
4850 
4851   if (!isInt<16>(FirstOffset.getImm()) || !isInt<16>(NextOffset))
4852     return true;
4853 
4854   // For loads, clobber the base register with the second load instead of the
4855   // first if the BaseReg == FirstReg.
4856   if (FirstReg != BaseReg || !IsLoad) {
4857     TOut.emitRRX(Opcode, FirstReg, BaseReg, FirstOffset, IDLoc, STI);
4858     TOut.emitRRX(Opcode, SecondReg, BaseReg, SecondOffset, IDLoc, STI);
4859   } else {
4860     TOut.emitRRX(Opcode, SecondReg, BaseReg, SecondOffset, IDLoc, STI);
4861     TOut.emitRRX(Opcode, FirstReg, BaseReg, FirstOffset, IDLoc, STI);
4862   }
4863 
4864   return false;
4865 }
4866 
4867 bool MipsAsmParser::expandSeq(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4868                               const MCSubtargetInfo *STI) {
4869 
4870   warnIfNoMacro(IDLoc);
4871   MipsTargetStreamer &TOut = getTargetStreamer();
4872 
4873   if (Inst.getOperand(1).getReg() != Mips::ZERO &&
4874       Inst.getOperand(2).getReg() != Mips::ZERO) {
4875     TOut.emitRRR(Mips::XOR, Inst.getOperand(0).getReg(),
4876                  Inst.getOperand(1).getReg(), Inst.getOperand(2).getReg(),
4877                  IDLoc, STI);
4878     TOut.emitRRI(Mips::SLTiu, Inst.getOperand(0).getReg(),
4879                  Inst.getOperand(0).getReg(), 1, IDLoc, STI);
4880     return false;
4881   }
4882 
4883   unsigned Reg = 0;
4884   if (Inst.getOperand(1).getReg() == Mips::ZERO) {
4885     Reg = Inst.getOperand(2).getReg();
4886   } else {
4887     Reg = Inst.getOperand(1).getReg();
4888   }
4889   TOut.emitRRI(Mips::SLTiu, Inst.getOperand(0).getReg(), Reg, 1, IDLoc, STI);
4890   return false;
4891 }
4892 
4893 bool MipsAsmParser::expandSeqI(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4894                                const MCSubtargetInfo *STI) {
4895   warnIfNoMacro(IDLoc);
4896   MipsTargetStreamer &TOut = getTargetStreamer();
4897 
4898   unsigned Opc;
4899   int64_t Imm = Inst.getOperand(2).getImm();
4900   unsigned Reg = Inst.getOperand(1).getReg();
4901 
4902   if (Imm == 0) {
4903     TOut.emitRRI(Mips::SLTiu, Inst.getOperand(0).getReg(),
4904                  Inst.getOperand(1).getReg(), 1, IDLoc, STI);
4905     return false;
4906   } else {
4907 
4908     if (Reg == Mips::ZERO) {
4909       Warning(IDLoc, "comparison is always false");
4910       TOut.emitRRR(isGP64bit() ? Mips::DADDu : Mips::ADDu,
4911                    Inst.getOperand(0).getReg(), Reg, Reg, IDLoc, STI);
4912       return false;
4913     }
4914 
4915     if (Imm > -0x8000 && Imm < 0) {
4916       Imm = -Imm;
4917       Opc = isGP64bit() ? Mips::DADDiu : Mips::ADDiu;
4918     } else {
4919       Opc = Mips::XORi;
4920     }
4921   }
4922   if (!isUInt<16>(Imm)) {
4923     unsigned ATReg = getATReg(IDLoc);
4924     if (!ATReg)
4925       return true;
4926 
4927     if (loadImmediate(Imm, ATReg, Mips::NoRegister, true, isGP64bit(), IDLoc,
4928                       Out, STI))
4929       return true;
4930 
4931     TOut.emitRRR(Mips::XOR, Inst.getOperand(0).getReg(),
4932                  Inst.getOperand(1).getReg(), ATReg, IDLoc, STI);
4933     TOut.emitRRI(Mips::SLTiu, Inst.getOperand(0).getReg(),
4934                  Inst.getOperand(0).getReg(), 1, IDLoc, STI);
4935     return false;
4936   }
4937 
4938   TOut.emitRRI(Opc, Inst.getOperand(0).getReg(), Inst.getOperand(1).getReg(),
4939                Imm, IDLoc, STI);
4940   TOut.emitRRI(Mips::SLTiu, Inst.getOperand(0).getReg(),
4941                Inst.getOperand(0).getReg(), 1, IDLoc, STI);
4942   return false;
4943 }
4944 
4945 // Map the DSP accumulator and control register to the corresponding gpr
4946 // operand. Unlike the other alias, the m(f|t)t(lo|hi|acx) instructions
4947 // do not map the DSP registers contigously to gpr registers.
4948 static unsigned getRegisterForMxtrDSP(MCInst &Inst, bool IsMFDSP) {
4949   switch (Inst.getOpcode()) {
4950     case Mips::MFTLO:
4951     case Mips::MTTLO:
4952       switch (Inst.getOperand(IsMFDSP ? 1 : 0).getReg()) {
4953         case Mips::AC0:
4954           return Mips::ZERO;
4955         case Mips::AC1:
4956           return Mips::A0;
4957         case Mips::AC2:
4958           return Mips::T0;
4959         case Mips::AC3:
4960           return Mips::T4;
4961         default:
4962           llvm_unreachable("Unknown register for 'mttr' alias!");
4963     }
4964     case Mips::MFTHI:
4965     case Mips::MTTHI:
4966       switch (Inst.getOperand(IsMFDSP ? 1 : 0).getReg()) {
4967         case Mips::AC0:
4968           return Mips::AT;
4969         case Mips::AC1:
4970           return Mips::A1;
4971         case Mips::AC2:
4972           return Mips::T1;
4973         case Mips::AC3:
4974           return Mips::T5;
4975         default:
4976           llvm_unreachable("Unknown register for 'mttr' alias!");
4977     }
4978     case Mips::MFTACX:
4979     case Mips::MTTACX:
4980       switch (Inst.getOperand(IsMFDSP ? 1 : 0).getReg()) {
4981         case Mips::AC0:
4982           return Mips::V0;
4983         case Mips::AC1:
4984           return Mips::A2;
4985         case Mips::AC2:
4986           return Mips::T2;
4987         case Mips::AC3:
4988           return Mips::T6;
4989         default:
4990           llvm_unreachable("Unknown register for 'mttr' alias!");
4991     }
4992     case Mips::MFTDSP:
4993     case Mips::MTTDSP:
4994       return Mips::S0;
4995     default:
4996       llvm_unreachable("Unknown instruction for 'mttr' dsp alias!");
4997   }
4998 }
4999 
5000 // Map the floating point register operand to the corresponding register
5001 // operand.
5002 static unsigned getRegisterForMxtrFP(MCInst &Inst, bool IsMFTC1) {
5003   switch (Inst.getOperand(IsMFTC1 ? 1 : 0).getReg()) {
5004     case Mips::F0:  return Mips::ZERO;
5005     case Mips::F1:  return Mips::AT;
5006     case Mips::F2:  return Mips::V0;
5007     case Mips::F3:  return Mips::V1;
5008     case Mips::F4:  return Mips::A0;
5009     case Mips::F5:  return Mips::A1;
5010     case Mips::F6:  return Mips::A2;
5011     case Mips::F7:  return Mips::A3;
5012     case Mips::F8:  return Mips::T0;
5013     case Mips::F9:  return Mips::T1;
5014     case Mips::F10: return Mips::T2;
5015     case Mips::F11: return Mips::T3;
5016     case Mips::F12: return Mips::T4;
5017     case Mips::F13: return Mips::T5;
5018     case Mips::F14: return Mips::T6;
5019     case Mips::F15: return Mips::T7;
5020     case Mips::F16: return Mips::S0;
5021     case Mips::F17: return Mips::S1;
5022     case Mips::F18: return Mips::S2;
5023     case Mips::F19: return Mips::S3;
5024     case Mips::F20: return Mips::S4;
5025     case Mips::F21: return Mips::S5;
5026     case Mips::F22: return Mips::S6;
5027     case Mips::F23: return Mips::S7;
5028     case Mips::F24: return Mips::T8;
5029     case Mips::F25: return Mips::T9;
5030     case Mips::F26: return Mips::K0;
5031     case Mips::F27: return Mips::K1;
5032     case Mips::F28: return Mips::GP;
5033     case Mips::F29: return Mips::SP;
5034     case Mips::F30: return Mips::FP;
5035     case Mips::F31: return Mips::RA;
5036     default: llvm_unreachable("Unknown register for mttc1 alias!");
5037   }
5038 }
5039 
5040 // Map the coprocessor operand the corresponding gpr register operand.
5041 static unsigned getRegisterForMxtrC0(MCInst &Inst, bool IsMFTC0) {
5042   switch (Inst.getOperand(IsMFTC0 ? 1 : 0).getReg()) {
5043     case Mips::COP00:  return Mips::ZERO;
5044     case Mips::COP01:  return Mips::AT;
5045     case Mips::COP02:  return Mips::V0;
5046     case Mips::COP03:  return Mips::V1;
5047     case Mips::COP04:  return Mips::A0;
5048     case Mips::COP05:  return Mips::A1;
5049     case Mips::COP06:  return Mips::A2;
5050     case Mips::COP07:  return Mips::A3;
5051     case Mips::COP08:  return Mips::T0;
5052     case Mips::COP09:  return Mips::T1;
5053     case Mips::COP010: return Mips::T2;
5054     case Mips::COP011: return Mips::T3;
5055     case Mips::COP012: return Mips::T4;
5056     case Mips::COP013: return Mips::T5;
5057     case Mips::COP014: return Mips::T6;
5058     case Mips::COP015: return Mips::T7;
5059     case Mips::COP016: return Mips::S0;
5060     case Mips::COP017: return Mips::S1;
5061     case Mips::COP018: return Mips::S2;
5062     case Mips::COP019: return Mips::S3;
5063     case Mips::COP020: return Mips::S4;
5064     case Mips::COP021: return Mips::S5;
5065     case Mips::COP022: return Mips::S6;
5066     case Mips::COP023: return Mips::S7;
5067     case Mips::COP024: return Mips::T8;
5068     case Mips::COP025: return Mips::T9;
5069     case Mips::COP026: return Mips::K0;
5070     case Mips::COP027: return Mips::K1;
5071     case Mips::COP028: return Mips::GP;
5072     case Mips::COP029: return Mips::SP;
5073     case Mips::COP030: return Mips::FP;
5074     case Mips::COP031: return Mips::RA;
5075     default: llvm_unreachable("Unknown register for mttc0 alias!");
5076   }
5077 }
5078 
5079 /// Expand an alias of 'mftr' or 'mttr' into the full instruction, by producing
5080 /// an mftr or mttr with the correctly mapped gpr register, u, sel and h bits.
5081 bool MipsAsmParser::expandMXTRAlias(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5082                                     const MCSubtargetInfo *STI) {
5083   MipsTargetStreamer &TOut = getTargetStreamer();
5084   unsigned rd = 0;
5085   unsigned u = 1;
5086   unsigned sel = 0;
5087   unsigned h = 0;
5088   bool IsMFTR = false;
5089   switch (Inst.getOpcode()) {
5090     case Mips::MFTC0:
5091       IsMFTR = true;
5092       LLVM_FALLTHROUGH;
5093     case Mips::MTTC0:
5094       u = 0;
5095       rd = getRegisterForMxtrC0(Inst, IsMFTR);
5096       sel = Inst.getOperand(2).getImm();
5097       break;
5098     case Mips::MFTGPR:
5099       IsMFTR = true;
5100       LLVM_FALLTHROUGH;
5101     case Mips::MTTGPR:
5102       rd = Inst.getOperand(IsMFTR ? 1 : 0).getReg();
5103       break;
5104     case Mips::MFTLO:
5105     case Mips::MFTHI:
5106     case Mips::MFTACX:
5107     case Mips::MFTDSP:
5108       IsMFTR = true;
5109       LLVM_FALLTHROUGH;
5110     case Mips::MTTLO:
5111     case Mips::MTTHI:
5112     case Mips::MTTACX:
5113     case Mips::MTTDSP:
5114       rd = getRegisterForMxtrDSP(Inst, IsMFTR);
5115       sel = 1;
5116       break;
5117     case Mips::MFTHC1:
5118       h = 1;
5119       LLVM_FALLTHROUGH;
5120     case Mips::MFTC1:
5121       IsMFTR = true;
5122       rd = getRegisterForMxtrFP(Inst, IsMFTR);
5123       sel = 2;
5124       break;
5125     case Mips::MTTHC1:
5126       h = 1;
5127       LLVM_FALLTHROUGH;
5128     case Mips::MTTC1:
5129       rd = getRegisterForMxtrFP(Inst, IsMFTR);
5130       sel = 2;
5131       break;
5132     case Mips::CFTC1:
5133       IsMFTR = true;
5134       LLVM_FALLTHROUGH;
5135     case Mips::CTTC1:
5136       rd = getRegisterForMxtrFP(Inst, IsMFTR);
5137       sel = 3;
5138       break;
5139   }
5140   unsigned Op0 = IsMFTR ? Inst.getOperand(0).getReg() : rd;
5141   unsigned Op1 =
5142       IsMFTR ? rd
5143              : (Inst.getOpcode() != Mips::MTTDSP ? Inst.getOperand(1).getReg()
5144                                                  : Inst.getOperand(0).getReg());
5145 
5146   TOut.emitRRIII(IsMFTR ? Mips::MFTR : Mips::MTTR, Op0, Op1, u, sel, h, IDLoc,
5147                  STI);
5148   return false;
5149 }
5150 
5151 unsigned
5152 MipsAsmParser::checkEarlyTargetMatchPredicate(MCInst &Inst,
5153                                               const OperandVector &Operands) {
5154   switch (Inst.getOpcode()) {
5155   default:
5156     return Match_Success;
5157   case Mips::DATI:
5158   case Mips::DAHI:
5159     if (static_cast<MipsOperand &>(*Operands[1])
5160             .isValidForTie(static_cast<MipsOperand &>(*Operands[2])))
5161       return Match_Success;
5162     return Match_RequiresSameSrcAndDst;
5163   }
5164 }
5165 
5166 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
5167   switch (Inst.getOpcode()) {
5168   // As described by the MIPSR6 spec, daui must not use the zero operand for
5169   // its source operand.
5170   case Mips::DAUI:
5171     if (Inst.getOperand(1).getReg() == Mips::ZERO ||
5172         Inst.getOperand(1).getReg() == Mips::ZERO_64)
5173       return Match_RequiresNoZeroRegister;
5174     return Match_Success;
5175   // As described by the Mips32r2 spec, the registers Rd and Rs for
5176   // jalr.hb must be different.
5177   // It also applies for registers Rt and Rs of microMIPSr6 jalrc.hb instruction
5178   // and registers Rd and Base for microMIPS lwp instruction
5179   case Mips::JALR_HB:
5180   case Mips::JALR_HB64:
5181   case Mips::JALRC_HB_MMR6:
5182   case Mips::JALRC_MMR6:
5183     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
5184       return Match_RequiresDifferentSrcAndDst;
5185     return Match_Success;
5186   case Mips::LWP_MM:
5187     if (Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg())
5188       return Match_RequiresDifferentSrcAndDst;
5189     return Match_Success;
5190   case Mips::SYNC:
5191     if (Inst.getOperand(0).getImm() != 0 && !hasMips32())
5192       return Match_NonZeroOperandForSync;
5193     return Match_Success;
5194   case Mips::MFC0:
5195   case Mips::MTC0:
5196   case Mips::MTC2:
5197   case Mips::MFC2:
5198     if (Inst.getOperand(2).getImm() != 0 && !hasMips32())
5199       return Match_NonZeroOperandForMTCX;
5200     return Match_Success;
5201   // As described the MIPSR6 spec, the compact branches that compare registers
5202   // must:
5203   // a) Not use the zero register.
5204   // b) Not use the same register twice.
5205   // c) rs < rt for bnec, beqc.
5206   //    NB: For this case, the encoding will swap the operands as their
5207   //    ordering doesn't matter. GAS performs this transformation  too.
5208   //    Hence, that constraint does not have to be enforced.
5209   //
5210   // The compact branches that branch iff the signed addition of two registers
5211   // would overflow must have rs >= rt. That can be handled like beqc/bnec with
5212   // operand swapping. They do not have restriction of using the zero register.
5213   case Mips::BLEZC:   case Mips::BLEZC_MMR6:
5214   case Mips::BGEZC:   case Mips::BGEZC_MMR6:
5215   case Mips::BGTZC:   case Mips::BGTZC_MMR6:
5216   case Mips::BLTZC:   case Mips::BLTZC_MMR6:
5217   case Mips::BEQZC:   case Mips::BEQZC_MMR6:
5218   case Mips::BNEZC:   case Mips::BNEZC_MMR6:
5219   case Mips::BLEZC64:
5220   case Mips::BGEZC64:
5221   case Mips::BGTZC64:
5222   case Mips::BLTZC64:
5223   case Mips::BEQZC64:
5224   case Mips::BNEZC64:
5225     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
5226         Inst.getOperand(0).getReg() == Mips::ZERO_64)
5227       return Match_RequiresNoZeroRegister;
5228     return Match_Success;
5229   case Mips::BGEC:    case Mips::BGEC_MMR6:
5230   case Mips::BLTC:    case Mips::BLTC_MMR6:
5231   case Mips::BGEUC:   case Mips::BGEUC_MMR6:
5232   case Mips::BLTUC:   case Mips::BLTUC_MMR6:
5233   case Mips::BEQC:    case Mips::BEQC_MMR6:
5234   case Mips::BNEC:    case Mips::BNEC_MMR6:
5235   case Mips::BGEC64:
5236   case Mips::BLTC64:
5237   case Mips::BGEUC64:
5238   case Mips::BLTUC64:
5239   case Mips::BEQC64:
5240   case Mips::BNEC64:
5241     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
5242         Inst.getOperand(0).getReg() == Mips::ZERO_64)
5243       return Match_RequiresNoZeroRegister;
5244     if (Inst.getOperand(1).getReg() == Mips::ZERO ||
5245         Inst.getOperand(1).getReg() == Mips::ZERO_64)
5246       return Match_RequiresNoZeroRegister;
5247     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
5248       return Match_RequiresDifferentOperands;
5249     return Match_Success;
5250   case Mips::DINS: {
5251     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5252            "Operands must be immediates for dins!");
5253     const signed Pos = Inst.getOperand(2).getImm();
5254     const signed Size = Inst.getOperand(3).getImm();
5255     if ((0 > (Pos + Size)) || ((Pos + Size) > 32))
5256       return Match_RequiresPosSizeRange0_32;
5257     return Match_Success;
5258   }
5259   case Mips::DINSM:
5260   case Mips::DINSU: {
5261     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5262            "Operands must be immediates for dinsm/dinsu!");
5263     const signed Pos = Inst.getOperand(2).getImm();
5264     const signed Size = Inst.getOperand(3).getImm();
5265     if ((32 >= (Pos + Size)) || ((Pos + Size) > 64))
5266       return Match_RequiresPosSizeRange33_64;
5267     return Match_Success;
5268   }
5269   case Mips::DEXT: {
5270     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5271            "Operands must be immediates for DEXTM!");
5272     const signed Pos = Inst.getOperand(2).getImm();
5273     const signed Size = Inst.getOperand(3).getImm();
5274     if ((1 > (Pos + Size)) || ((Pos + Size) > 63))
5275       return Match_RequiresPosSizeUImm6;
5276     return Match_Success;
5277   }
5278   case Mips::DEXTM:
5279   case Mips::DEXTU: {
5280     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5281            "Operands must be immediates for dextm/dextu!");
5282     const signed Pos = Inst.getOperand(2).getImm();
5283     const signed Size = Inst.getOperand(3).getImm();
5284     if ((32 > (Pos + Size)) || ((Pos + Size) > 64))
5285       return Match_RequiresPosSizeRange33_64;
5286     return Match_Success;
5287   }
5288   case Mips::CRC32B: case Mips::CRC32CB:
5289   case Mips::CRC32H: case Mips::CRC32CH:
5290   case Mips::CRC32W: case Mips::CRC32CW:
5291   case Mips::CRC32D: case Mips::CRC32CD:
5292     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg())
5293       return Match_RequiresSameSrcAndDst;
5294     return Match_Success;
5295   }
5296 
5297   uint64_t TSFlags = getInstDesc(Inst.getOpcode()).TSFlags;
5298   if ((TSFlags & MipsII::HasFCCRegOperand) &&
5299       (Inst.getOperand(0).getReg() != Mips::FCC0) && !hasEightFccRegisters())
5300     return Match_NoFCCRegisterForCurrentISA;
5301 
5302   return Match_Success;
5303 
5304 }
5305 
5306 static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands,
5307                             uint64_t ErrorInfo) {
5308   if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) {
5309     SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc();
5310     if (ErrorLoc == SMLoc())
5311       return Loc;
5312     return ErrorLoc;
5313   }
5314   return Loc;
5315 }
5316 
5317 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
5318                                             OperandVector &Operands,
5319                                             MCStreamer &Out,
5320                                             uint64_t &ErrorInfo,
5321                                             bool MatchingInlineAsm) {
5322   MCInst Inst;
5323   unsigned MatchResult =
5324       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
5325 
5326   switch (MatchResult) {
5327   case Match_Success:
5328     if (processInstruction(Inst, IDLoc, Out, STI))
5329       return true;
5330     return false;
5331   case Match_MissingFeature:
5332     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
5333     return true;
5334   case Match_InvalidOperand: {
5335     SMLoc ErrorLoc = IDLoc;
5336     if (ErrorInfo != ~0ULL) {
5337       if (ErrorInfo >= Operands.size())
5338         return Error(IDLoc, "too few operands for instruction");
5339 
5340       ErrorLoc = Operands[ErrorInfo]->getStartLoc();
5341       if (ErrorLoc == SMLoc())
5342         ErrorLoc = IDLoc;
5343     }
5344 
5345     return Error(ErrorLoc, "invalid operand for instruction");
5346   }
5347   case Match_NonZeroOperandForSync:
5348     return Error(IDLoc,
5349                  "s-type must be zero or unspecified for pre-MIPS32 ISAs");
5350   case Match_NonZeroOperandForMTCX:
5351     return Error(IDLoc, "selector must be zero for pre-MIPS32 ISAs");
5352   case Match_MnemonicFail:
5353     return Error(IDLoc, "invalid instruction");
5354   case Match_RequiresDifferentSrcAndDst:
5355     return Error(IDLoc, "source and destination must be different");
5356   case Match_RequiresDifferentOperands:
5357     return Error(IDLoc, "registers must be different");
5358   case Match_RequiresNoZeroRegister:
5359     return Error(IDLoc, "invalid operand ($zero) for instruction");
5360   case Match_RequiresSameSrcAndDst:
5361     return Error(IDLoc, "source and destination must match");
5362   case Match_NoFCCRegisterForCurrentISA:
5363     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5364                  "non-zero fcc register doesn't exist in current ISA level");
5365   case Match_Immz:
5366     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'");
5367   case Match_UImm1_0:
5368     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5369                  "expected 1-bit unsigned immediate");
5370   case Match_UImm2_0:
5371     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5372                  "expected 2-bit unsigned immediate");
5373   case Match_UImm2_1:
5374     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5375                  "expected immediate in range 1 .. 4");
5376   case Match_UImm3_0:
5377     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5378                  "expected 3-bit unsigned immediate");
5379   case Match_UImm4_0:
5380     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5381                  "expected 4-bit unsigned immediate");
5382   case Match_SImm4_0:
5383     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5384                  "expected 4-bit signed immediate");
5385   case Match_UImm5_0:
5386     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5387                  "expected 5-bit unsigned immediate");
5388   case Match_SImm5_0:
5389     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5390                  "expected 5-bit signed immediate");
5391   case Match_UImm5_1:
5392     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5393                  "expected immediate in range 1 .. 32");
5394   case Match_UImm5_32:
5395     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5396                  "expected immediate in range 32 .. 63");
5397   case Match_UImm5_33:
5398     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5399                  "expected immediate in range 33 .. 64");
5400   case Match_UImm5_0_Report_UImm6:
5401     // This is used on UImm5 operands that have a corresponding UImm5_32
5402     // operand to avoid confusing the user.
5403     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5404                  "expected 6-bit unsigned immediate");
5405   case Match_UImm5_Lsl2:
5406     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5407                  "expected both 7-bit unsigned immediate and multiple of 4");
5408   case Match_UImmRange2_64:
5409     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5410                  "expected immediate in range 2 .. 64");
5411   case Match_UImm6_0:
5412     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5413                  "expected 6-bit unsigned immediate");
5414   case Match_UImm6_Lsl2:
5415     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5416                  "expected both 8-bit unsigned immediate and multiple of 4");
5417   case Match_SImm6_0:
5418     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5419                  "expected 6-bit signed immediate");
5420   case Match_UImm7_0:
5421     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5422                  "expected 7-bit unsigned immediate");
5423   case Match_UImm7_N1:
5424     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5425                  "expected immediate in range -1 .. 126");
5426   case Match_SImm7_Lsl2:
5427     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5428                  "expected both 9-bit signed immediate and multiple of 4");
5429   case Match_UImm8_0:
5430     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5431                  "expected 8-bit unsigned immediate");
5432   case Match_UImm10_0:
5433     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5434                  "expected 10-bit unsigned immediate");
5435   case Match_SImm10_0:
5436     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5437                  "expected 10-bit signed immediate");
5438   case Match_SImm11_0:
5439     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5440                  "expected 11-bit signed immediate");
5441   case Match_UImm16:
5442   case Match_UImm16_Relaxed:
5443   case Match_UImm16_AltRelaxed:
5444     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5445                  "expected 16-bit unsigned immediate");
5446   case Match_SImm16:
5447   case Match_SImm16_Relaxed:
5448     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5449                  "expected 16-bit signed immediate");
5450   case Match_SImm19_Lsl2:
5451     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5452                  "expected both 19-bit signed immediate and multiple of 4");
5453   case Match_UImm20_0:
5454     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5455                  "expected 20-bit unsigned immediate");
5456   case Match_UImm26_0:
5457     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5458                  "expected 26-bit unsigned immediate");
5459   case Match_SImm32:
5460   case Match_SImm32_Relaxed:
5461     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5462                  "expected 32-bit signed immediate");
5463   case Match_UImm32_Coerced:
5464     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5465                  "expected 32-bit immediate");
5466   case Match_MemSImm9:
5467     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5468                  "expected memory with 9-bit signed offset");
5469   case Match_MemSImm10:
5470     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5471                  "expected memory with 10-bit signed offset");
5472   case Match_MemSImm10Lsl1:
5473     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5474                  "expected memory with 11-bit signed offset and multiple of 2");
5475   case Match_MemSImm10Lsl2:
5476     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5477                  "expected memory with 12-bit signed offset and multiple of 4");
5478   case Match_MemSImm10Lsl3:
5479     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5480                  "expected memory with 13-bit signed offset and multiple of 8");
5481   case Match_MemSImm11:
5482     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5483                  "expected memory with 11-bit signed offset");
5484   case Match_MemSImm12:
5485     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5486                  "expected memory with 12-bit signed offset");
5487   case Match_MemSImm16:
5488     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5489                  "expected memory with 16-bit signed offset");
5490   case Match_MemSImmPtr:
5491     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5492                  "expected memory with 32-bit signed offset");
5493   case Match_RequiresPosSizeRange0_32: {
5494     SMLoc ErrorStart = Operands[3]->getStartLoc();
5495     SMLoc ErrorEnd = Operands[4]->getEndLoc();
5496     return Error(ErrorStart, "size plus position are not in the range 0 .. 32",
5497                  SMRange(ErrorStart, ErrorEnd));
5498     }
5499   case Match_RequiresPosSizeUImm6: {
5500     SMLoc ErrorStart = Operands[3]->getStartLoc();
5501     SMLoc ErrorEnd = Operands[4]->getEndLoc();
5502     return Error(ErrorStart, "size plus position are not in the range 1 .. 63",
5503                  SMRange(ErrorStart, ErrorEnd));
5504     }
5505   case Match_RequiresPosSizeRange33_64: {
5506     SMLoc ErrorStart = Operands[3]->getStartLoc();
5507     SMLoc ErrorEnd = Operands[4]->getEndLoc();
5508     return Error(ErrorStart, "size plus position are not in the range 33 .. 64",
5509                  SMRange(ErrorStart, ErrorEnd));
5510     }
5511   }
5512 
5513   llvm_unreachable("Implement any new match types added!");
5514 }
5515 
5516 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
5517   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
5518     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
5519                      ") without \".set noat\"");
5520 }
5521 
5522 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
5523   if (!AssemblerOptions.back()->isMacro())
5524     Warning(Loc, "macro instruction expanded into multiple instructions");
5525 }
5526 
5527 void MipsAsmParser::ConvertXWPOperands(MCInst &Inst,
5528                                        const OperandVector &Operands) {
5529   assert(
5530       (Inst.getOpcode() == Mips::LWP_MM || Inst.getOpcode() == Mips::SWP_MM) &&
5531       "Unexpected instruction!");
5532   ((MipsOperand &)*Operands[1]).addGPR32ZeroAsmRegOperands(Inst, 1);
5533   int NextReg = nextReg(((MipsOperand &)*Operands[1]).getGPR32Reg());
5534   Inst.addOperand(MCOperand::createReg(NextReg));
5535   ((MipsOperand &)*Operands[2]).addMemOperands(Inst, 2);
5536 }
5537 
5538 void
5539 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
5540                                      SMRange Range, bool ShowColors) {
5541   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
5542                                   Range, SMFixIt(Range, FixMsg),
5543                                   ShowColors);
5544 }
5545 
5546 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
5547   int CC;
5548 
5549   CC = StringSwitch<unsigned>(Name)
5550            .Case("zero", 0)
5551            .Cases("at", "AT", 1)
5552            .Case("a0", 4)
5553            .Case("a1", 5)
5554            .Case("a2", 6)
5555            .Case("a3", 7)
5556            .Case("v0", 2)
5557            .Case("v1", 3)
5558            .Case("s0", 16)
5559            .Case("s1", 17)
5560            .Case("s2", 18)
5561            .Case("s3", 19)
5562            .Case("s4", 20)
5563            .Case("s5", 21)
5564            .Case("s6", 22)
5565            .Case("s7", 23)
5566            .Case("k0", 26)
5567            .Case("k1", 27)
5568            .Case("gp", 28)
5569            .Case("sp", 29)
5570            .Case("fp", 30)
5571            .Case("s8", 30)
5572            .Case("ra", 31)
5573            .Case("t0", 8)
5574            .Case("t1", 9)
5575            .Case("t2", 10)
5576            .Case("t3", 11)
5577            .Case("t4", 12)
5578            .Case("t5", 13)
5579            .Case("t6", 14)
5580            .Case("t7", 15)
5581            .Case("t8", 24)
5582            .Case("t9", 25)
5583            .Default(-1);
5584 
5585   if (!(isABI_N32() || isABI_N64()))
5586     return CC;
5587 
5588   if (12 <= CC && CC <= 15) {
5589     // Name is one of t4-t7
5590     AsmToken RegTok = getLexer().peekTok();
5591     SMRange RegRange = RegTok.getLocRange();
5592 
5593     StringRef FixedName = StringSwitch<StringRef>(Name)
5594                               .Case("t4", "t0")
5595                               .Case("t5", "t1")
5596                               .Case("t6", "t2")
5597                               .Case("t7", "t3")
5598                               .Default("");
5599     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
5600 
5601     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
5602                           "Did you mean $" + FixedName + "?", RegRange);
5603   }
5604 
5605   // Although SGI documentation just cuts out t0-t3 for n32/n64,
5606   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
5607   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
5608   if (8 <= CC && CC <= 11)
5609     CC += 4;
5610 
5611   if (CC == -1)
5612     CC = StringSwitch<unsigned>(Name)
5613              .Case("a4", 8)
5614              .Case("a5", 9)
5615              .Case("a6", 10)
5616              .Case("a7", 11)
5617              .Case("kt0", 26)
5618              .Case("kt1", 27)
5619              .Default(-1);
5620 
5621   return CC;
5622 }
5623 
5624 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
5625   int CC;
5626 
5627   CC = StringSwitch<unsigned>(Name)
5628             .Case("hwr_cpunum", 0)
5629             .Case("hwr_synci_step", 1)
5630             .Case("hwr_cc", 2)
5631             .Case("hwr_ccres", 3)
5632             .Case("hwr_ulr", 29)
5633             .Default(-1);
5634 
5635   return CC;
5636 }
5637 
5638 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
5639   if (Name[0] == 'f') {
5640     StringRef NumString = Name.substr(1);
5641     unsigned IntVal;
5642     if (NumString.getAsInteger(10, IntVal))
5643       return -1;     // This is not an integer.
5644     if (IntVal > 31) // Maximum index for fpu register.
5645       return -1;
5646     return IntVal;
5647   }
5648   return -1;
5649 }
5650 
5651 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
5652   if (Name.startswith("fcc")) {
5653     StringRef NumString = Name.substr(3);
5654     unsigned IntVal;
5655     if (NumString.getAsInteger(10, IntVal))
5656       return -1;    // This is not an integer.
5657     if (IntVal > 7) // There are only 8 fcc registers.
5658       return -1;
5659     return IntVal;
5660   }
5661   return -1;
5662 }
5663 
5664 int MipsAsmParser::matchACRegisterName(StringRef Name) {
5665   if (Name.startswith("ac")) {
5666     StringRef NumString = Name.substr(2);
5667     unsigned IntVal;
5668     if (NumString.getAsInteger(10, IntVal))
5669       return -1;    // This is not an integer.
5670     if (IntVal > 3) // There are only 3 acc registers.
5671       return -1;
5672     return IntVal;
5673   }
5674   return -1;
5675 }
5676 
5677 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
5678   unsigned IntVal;
5679 
5680   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
5681     return -1;
5682 
5683   if (IntVal > 31)
5684     return -1;
5685 
5686   return IntVal;
5687 }
5688 
5689 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
5690   int CC;
5691 
5692   CC = StringSwitch<unsigned>(Name)
5693            .Case("msair", 0)
5694            .Case("msacsr", 1)
5695            .Case("msaaccess", 2)
5696            .Case("msasave", 3)
5697            .Case("msamodify", 4)
5698            .Case("msarequest", 5)
5699            .Case("msamap", 6)
5700            .Case("msaunmap", 7)
5701            .Default(-1);
5702 
5703   return CC;
5704 }
5705 
5706 bool MipsAsmParser::canUseATReg() {
5707   return AssemblerOptions.back()->getATRegIndex() != 0;
5708 }
5709 
5710 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
5711   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
5712   if (ATIndex == 0) {
5713     reportParseError(Loc,
5714                      "pseudo-instruction requires $at, which is not available");
5715     return 0;
5716   }
5717   unsigned AT = getReg(
5718       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
5719   return AT;
5720 }
5721 
5722 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
5723   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
5724 }
5725 
5726 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5727   MCAsmParser &Parser = getParser();
5728   LLVM_DEBUG(dbgs() << "parseOperand\n");
5729 
5730   // Check if the current operand has a custom associated parser, if so, try to
5731   // custom parse the operand, or fallback to the general approach.
5732   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5733   if (ResTy == MatchOperand_Success)
5734     return false;
5735   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5736   // there was a match, but an error occurred, in which case, just return that
5737   // the operand parsing failed.
5738   if (ResTy == MatchOperand_ParseFail)
5739     return true;
5740 
5741   LLVM_DEBUG(dbgs() << ".. Generic Parser\n");
5742 
5743   switch (getLexer().getKind()) {
5744   case AsmToken::Dollar: {
5745     // Parse the register.
5746     SMLoc S = Parser.getTok().getLoc();
5747 
5748     // Almost all registers have been parsed by custom parsers. There is only
5749     // one exception to this. $zero (and it's alias $0) will reach this point
5750     // for div, divu, and similar instructions because it is not an operand
5751     // to the instruction definition but an explicit register. Special case
5752     // this situation for now.
5753     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
5754       return false;
5755 
5756     // Maybe it is a symbol reference.
5757     StringRef Identifier;
5758     if (Parser.parseIdentifier(Identifier))
5759       return true;
5760 
5761     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5762     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
5763     // Otherwise create a symbol reference.
5764     const MCExpr *Res =
5765         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
5766 
5767     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
5768     return false;
5769   }
5770   default: {
5771     LLVM_DEBUG(dbgs() << ".. generic integer expression\n");
5772 
5773     const MCExpr *Expr;
5774     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
5775     if (getParser().parseExpression(Expr))
5776       return true;
5777 
5778     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5779 
5780     Operands.push_back(MipsOperand::CreateImm(Expr, S, E, *this));
5781     return false;
5782   }
5783   } // switch(getLexer().getKind())
5784   return true;
5785 }
5786 
5787 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
5788   switch (Expr->getKind()) {
5789   case MCExpr::Constant:
5790     return true;
5791   case MCExpr::SymbolRef:
5792     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
5793   case MCExpr::Binary: {
5794     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
5795     if (!isEvaluated(BE->getLHS()))
5796       return false;
5797     return isEvaluated(BE->getRHS());
5798   }
5799   case MCExpr::Unary:
5800     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
5801   case MCExpr::Target:
5802     return true;
5803   }
5804   return false;
5805 }
5806 
5807 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
5808                                   SMLoc &EndLoc) {
5809   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
5810   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
5811   if (ResTy == MatchOperand_Success) {
5812     assert(Operands.size() == 1);
5813     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
5814     StartLoc = Operand.getStartLoc();
5815     EndLoc = Operand.getEndLoc();
5816 
5817     // AFAIK, we only support numeric registers and named GPR's in CFI
5818     // directives.
5819     // Don't worry about eating tokens before failing. Using an unrecognised
5820     // register is a parse error.
5821     if (Operand.isGPRAsmReg()) {
5822       // Resolve to GPR32 or GPR64 appropriately.
5823       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
5824     }
5825 
5826     return (RegNo == (unsigned)-1);
5827   }
5828 
5829   assert(Operands.size() == 0);
5830   return (RegNo == (unsigned)-1);
5831 }
5832 
5833 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
5834   SMLoc S;
5835 
5836   if (isParenExpr)
5837     return getParser().parseParenExprOfDepth(0, Res, S);
5838   return getParser().parseExpression(Res);
5839 }
5840 
5841 OperandMatchResultTy
5842 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
5843   MCAsmParser &Parser = getParser();
5844   LLVM_DEBUG(dbgs() << "parseMemOperand\n");
5845   const MCExpr *IdVal = nullptr;
5846   SMLoc S;
5847   bool isParenExpr = false;
5848   OperandMatchResultTy Res = MatchOperand_NoMatch;
5849   // First operand is the offset.
5850   S = Parser.getTok().getLoc();
5851 
5852   if (getLexer().getKind() == AsmToken::LParen) {
5853     Parser.Lex();
5854     isParenExpr = true;
5855   }
5856 
5857   if (getLexer().getKind() != AsmToken::Dollar) {
5858     if (parseMemOffset(IdVal, isParenExpr))
5859       return MatchOperand_ParseFail;
5860 
5861     const AsmToken &Tok = Parser.getTok(); // Get the next token.
5862     if (Tok.isNot(AsmToken::LParen)) {
5863       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
5864       if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") {
5865         SMLoc E =
5866             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5867         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
5868         return MatchOperand_Success;
5869       }
5870       if (Tok.is(AsmToken::EndOfStatement)) {
5871         SMLoc E =
5872             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5873 
5874         // Zero register assumed, add a memory operand with ZERO as its base.
5875         // "Base" will be managed by k_Memory.
5876         auto Base = MipsOperand::createGPRReg(
5877             0, "0", getContext().getRegisterInfo(), S, E, *this);
5878         Operands.push_back(
5879             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
5880         return MatchOperand_Success;
5881       }
5882       MCBinaryExpr::Opcode Opcode;
5883       // GAS and LLVM treat comparison operators different. GAS will generate -1
5884       // or 0, while LLVM will generate 0 or 1. Since a comparsion operator is
5885       // highly unlikely to be found in a memory offset expression, we don't
5886       // handle them.
5887       switch (Tok.getKind()) {
5888       case AsmToken::Plus:
5889         Opcode = MCBinaryExpr::Add;
5890         Parser.Lex();
5891         break;
5892       case AsmToken::Minus:
5893         Opcode = MCBinaryExpr::Sub;
5894         Parser.Lex();
5895         break;
5896       case AsmToken::Star:
5897         Opcode = MCBinaryExpr::Mul;
5898         Parser.Lex();
5899         break;
5900       case AsmToken::Pipe:
5901         Opcode = MCBinaryExpr::Or;
5902         Parser.Lex();
5903         break;
5904       case AsmToken::Amp:
5905         Opcode = MCBinaryExpr::And;
5906         Parser.Lex();
5907         break;
5908       case AsmToken::LessLess:
5909         Opcode = MCBinaryExpr::Shl;
5910         Parser.Lex();
5911         break;
5912       case AsmToken::GreaterGreater:
5913         Opcode = MCBinaryExpr::LShr;
5914         Parser.Lex();
5915         break;
5916       case AsmToken::Caret:
5917         Opcode = MCBinaryExpr::Xor;
5918         Parser.Lex();
5919         break;
5920       case AsmToken::Slash:
5921         Opcode = MCBinaryExpr::Div;
5922         Parser.Lex();
5923         break;
5924       case AsmToken::Percent:
5925         Opcode = MCBinaryExpr::Mod;
5926         Parser.Lex();
5927         break;
5928       default:
5929         Error(Parser.getTok().getLoc(), "'(' or expression expected");
5930         return MatchOperand_ParseFail;
5931       }
5932       const MCExpr * NextExpr;
5933       if (getParser().parseExpression(NextExpr))
5934         return MatchOperand_ParseFail;
5935       IdVal = MCBinaryExpr::create(Opcode, IdVal, NextExpr, getContext());
5936     }
5937 
5938     Parser.Lex(); // Eat the '(' token.
5939   }
5940 
5941   Res = parseAnyRegister(Operands);
5942   if (Res != MatchOperand_Success)
5943     return Res;
5944 
5945   if (Parser.getTok().isNot(AsmToken::RParen)) {
5946     Error(Parser.getTok().getLoc(), "')' expected");
5947     return MatchOperand_ParseFail;
5948   }
5949 
5950   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5951 
5952   Parser.Lex(); // Eat the ')' token.
5953 
5954   if (!IdVal)
5955     IdVal = MCConstantExpr::create(0, getContext());
5956 
5957   // Replace the register operand with the memory operand.
5958   std::unique_ptr<MipsOperand> op(
5959       static_cast<MipsOperand *>(Operands.back().release()));
5960   // Remove the register from the operands.
5961   // "op" will be managed by k_Memory.
5962   Operands.pop_back();
5963   // Add the memory operand.
5964   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
5965     int64_t Imm;
5966     if (IdVal->evaluateAsAbsolute(Imm))
5967       IdVal = MCConstantExpr::create(Imm, getContext());
5968     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
5969       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
5970                                    getContext());
5971   }
5972 
5973   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
5974   return MatchOperand_Success;
5975 }
5976 
5977 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
5978   MCAsmParser &Parser = getParser();
5979   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
5980   if (!Sym)
5981     return false;
5982 
5983   SMLoc S = Parser.getTok().getLoc();
5984   if (Sym->isVariable()) {
5985     const MCExpr *Expr = Sym->getVariableValue();
5986     if (Expr->getKind() == MCExpr::SymbolRef) {
5987       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
5988       StringRef DefSymbol = Ref->getSymbol().getName();
5989       if (DefSymbol.startswith("$")) {
5990         OperandMatchResultTy ResTy =
5991             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
5992         if (ResTy == MatchOperand_Success) {
5993           Parser.Lex();
5994           return true;
5995         }
5996         if (ResTy == MatchOperand_ParseFail)
5997           llvm_unreachable("Should never ParseFail");
5998       }
5999     }
6000   } else if (Sym->isUnset()) {
6001     // If symbol is unset, it might be created in the `parseSetAssignment`
6002     // routine as an alias for a numeric register name.
6003     // Lookup in the aliases list.
6004     auto Entry = RegisterSets.find(Sym->getName());
6005     if (Entry != RegisterSets.end()) {
6006       OperandMatchResultTy ResTy =
6007           matchAnyRegisterWithoutDollar(Operands, Entry->getValue(), S);
6008       if (ResTy == MatchOperand_Success) {
6009         Parser.Lex();
6010         return true;
6011       }
6012     }
6013   }
6014 
6015   return false;
6016 }
6017 
6018 OperandMatchResultTy
6019 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
6020                                                  StringRef Identifier,
6021                                                  SMLoc S) {
6022   int Index = matchCPURegisterName(Identifier);
6023   if (Index != -1) {
6024     Operands.push_back(MipsOperand::createGPRReg(
6025         Index, Identifier, getContext().getRegisterInfo(), S,
6026         getLexer().getLoc(), *this));
6027     return MatchOperand_Success;
6028   }
6029 
6030   Index = matchHWRegsRegisterName(Identifier);
6031   if (Index != -1) {
6032     Operands.push_back(MipsOperand::createHWRegsReg(
6033         Index, Identifier, getContext().getRegisterInfo(), S,
6034         getLexer().getLoc(), *this));
6035     return MatchOperand_Success;
6036   }
6037 
6038   Index = matchFPURegisterName(Identifier);
6039   if (Index != -1) {
6040     Operands.push_back(MipsOperand::createFGRReg(
6041         Index, Identifier, getContext().getRegisterInfo(), S,
6042         getLexer().getLoc(), *this));
6043     return MatchOperand_Success;
6044   }
6045 
6046   Index = matchFCCRegisterName(Identifier);
6047   if (Index != -1) {
6048     Operands.push_back(MipsOperand::createFCCReg(
6049         Index, Identifier, getContext().getRegisterInfo(), S,
6050         getLexer().getLoc(), *this));
6051     return MatchOperand_Success;
6052   }
6053 
6054   Index = matchACRegisterName(Identifier);
6055   if (Index != -1) {
6056     Operands.push_back(MipsOperand::createACCReg(
6057         Index, Identifier, getContext().getRegisterInfo(), S,
6058         getLexer().getLoc(), *this));
6059     return MatchOperand_Success;
6060   }
6061 
6062   Index = matchMSA128RegisterName(Identifier);
6063   if (Index != -1) {
6064     Operands.push_back(MipsOperand::createMSA128Reg(
6065         Index, Identifier, getContext().getRegisterInfo(), S,
6066         getLexer().getLoc(), *this));
6067     return MatchOperand_Success;
6068   }
6069 
6070   Index = matchMSA128CtrlRegisterName(Identifier);
6071   if (Index != -1) {
6072     Operands.push_back(MipsOperand::createMSACtrlReg(
6073         Index, Identifier, getContext().getRegisterInfo(), S,
6074         getLexer().getLoc(), *this));
6075     return MatchOperand_Success;
6076   }
6077 
6078   return MatchOperand_NoMatch;
6079 }
6080 
6081 OperandMatchResultTy
6082 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands,
6083                                              const AsmToken &Token, SMLoc S) {
6084   if (Token.is(AsmToken::Identifier)) {
6085     LLVM_DEBUG(dbgs() << ".. identifier\n");
6086     StringRef Identifier = Token.getIdentifier();
6087     OperandMatchResultTy ResTy =
6088         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
6089     return ResTy;
6090   } else if (Token.is(AsmToken::Integer)) {
6091     LLVM_DEBUG(dbgs() << ".. integer\n");
6092     int64_t RegNum = Token.getIntVal();
6093     if (RegNum < 0 || RegNum > 31) {
6094       // Show the error, but treat invalid register
6095       // number as a normal one to continue parsing
6096       // and catch other possible errors.
6097       Error(getLexer().getLoc(), "invalid register number");
6098     }
6099     Operands.push_back(MipsOperand::createNumericReg(
6100         RegNum, Token.getString(), getContext().getRegisterInfo(), S,
6101         Token.getLoc(), *this));
6102     return MatchOperand_Success;
6103   }
6104 
6105   LLVM_DEBUG(dbgs() << Token.getKind() << "\n");
6106 
6107   return MatchOperand_NoMatch;
6108 }
6109 
6110 OperandMatchResultTy
6111 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
6112   auto Token = getLexer().peekTok(false);
6113   return matchAnyRegisterWithoutDollar(Operands, Token, S);
6114 }
6115 
6116 OperandMatchResultTy
6117 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
6118   MCAsmParser &Parser = getParser();
6119   LLVM_DEBUG(dbgs() << "parseAnyRegister\n");
6120 
6121   auto Token = Parser.getTok();
6122 
6123   SMLoc S = Token.getLoc();
6124 
6125   if (Token.isNot(AsmToken::Dollar)) {
6126     LLVM_DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
6127     if (Token.is(AsmToken::Identifier)) {
6128       if (searchSymbolAlias(Operands))
6129         return MatchOperand_Success;
6130     }
6131     LLVM_DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
6132     return MatchOperand_NoMatch;
6133   }
6134   LLVM_DEBUG(dbgs() << ".. $\n");
6135 
6136   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
6137   if (ResTy == MatchOperand_Success) {
6138     Parser.Lex(); // $
6139     Parser.Lex(); // identifier
6140   }
6141   return ResTy;
6142 }
6143 
6144 OperandMatchResultTy
6145 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
6146   MCAsmParser &Parser = getParser();
6147   LLVM_DEBUG(dbgs() << "parseJumpTarget\n");
6148 
6149   SMLoc S = getLexer().getLoc();
6150 
6151   // Registers are a valid target and have priority over symbols.
6152   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
6153   if (ResTy != MatchOperand_NoMatch)
6154     return ResTy;
6155 
6156   // Integers and expressions are acceptable
6157   const MCExpr *Expr = nullptr;
6158   if (Parser.parseExpression(Expr)) {
6159     // We have no way of knowing if a symbol was consumed so we must ParseFail
6160     return MatchOperand_ParseFail;
6161   }
6162   Operands.push_back(
6163       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
6164   return MatchOperand_Success;
6165 }
6166 
6167 OperandMatchResultTy
6168 MipsAsmParser::parseInvNum(OperandVector &Operands) {
6169   MCAsmParser &Parser = getParser();
6170   const MCExpr *IdVal;
6171   // If the first token is '$' we may have register operand. We have to reject
6172   // cases where it is not a register. Complicating the matter is that
6173   // register names are not reserved across all ABIs.
6174   // Peek past the dollar to see if it's a register name for this ABI.
6175   SMLoc S = Parser.getTok().getLoc();
6176   if (Parser.getTok().is(AsmToken::Dollar)) {
6177     return matchCPURegisterName(Parser.getLexer().peekTok().getString()) == -1
6178                ? MatchOperand_ParseFail
6179                : MatchOperand_NoMatch;
6180   }
6181   if (getParser().parseExpression(IdVal))
6182     return MatchOperand_ParseFail;
6183   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
6184   if (!MCE)
6185     return MatchOperand_NoMatch;
6186   int64_t Val = MCE->getValue();
6187   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6188   Operands.push_back(MipsOperand::CreateImm(
6189       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
6190   return MatchOperand_Success;
6191 }
6192 
6193 OperandMatchResultTy
6194 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
6195   MCAsmParser &Parser = getParser();
6196   SmallVector<unsigned, 10> Regs;
6197   unsigned RegNo;
6198   unsigned PrevReg = Mips::NoRegister;
6199   bool RegRange = false;
6200   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
6201 
6202   if (Parser.getTok().isNot(AsmToken::Dollar))
6203     return MatchOperand_ParseFail;
6204 
6205   SMLoc S = Parser.getTok().getLoc();
6206   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
6207     SMLoc E = getLexer().getLoc();
6208     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
6209     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
6210     if (RegRange) {
6211       // Remove last register operand because registers from register range
6212       // should be inserted first.
6213       if ((isGP64bit() && RegNo == Mips::RA_64) ||
6214           (!isGP64bit() && RegNo == Mips::RA)) {
6215         Regs.push_back(RegNo);
6216       } else {
6217         unsigned TmpReg = PrevReg + 1;
6218         while (TmpReg <= RegNo) {
6219           if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) ||
6220               (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) &&
6221                isGP64bit())) {
6222             Error(E, "invalid register operand");
6223             return MatchOperand_ParseFail;
6224           }
6225 
6226           PrevReg = TmpReg;
6227           Regs.push_back(TmpReg++);
6228         }
6229       }
6230 
6231       RegRange = false;
6232     } else {
6233       if ((PrevReg == Mips::NoRegister) &&
6234           ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) ||
6235           (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) {
6236         Error(E, "$16 or $31 expected");
6237         return MatchOperand_ParseFail;
6238       } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA ||
6239                     (RegNo >= Mips::S0 && RegNo <= Mips::S7)) &&
6240                     !isGP64bit()) ||
6241                    ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 ||
6242                     (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) &&
6243                     isGP64bit()))) {
6244         Error(E, "invalid register operand");
6245         return MatchOperand_ParseFail;
6246       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
6247                  ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) ||
6248                   (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 &&
6249                    isGP64bit()))) {
6250         Error(E, "consecutive register numbers expected");
6251         return MatchOperand_ParseFail;
6252       }
6253 
6254       Regs.push_back(RegNo);
6255     }
6256 
6257     if (Parser.getTok().is(AsmToken::Minus))
6258       RegRange = true;
6259 
6260     if (!Parser.getTok().isNot(AsmToken::Minus) &&
6261         !Parser.getTok().isNot(AsmToken::Comma)) {
6262       Error(E, "',' or '-' expected");
6263       return MatchOperand_ParseFail;
6264     }
6265 
6266     Lex(); // Consume comma or minus
6267     if (Parser.getTok().isNot(AsmToken::Dollar))
6268       break;
6269 
6270     PrevReg = RegNo;
6271   }
6272 
6273   SMLoc E = Parser.getTok().getLoc();
6274   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
6275   parseMemOperand(Operands);
6276   return MatchOperand_Success;
6277 }
6278 
6279 OperandMatchResultTy
6280 MipsAsmParser::parseMovePRegPair(OperandVector &Operands) {
6281   MCAsmParser &Parser = getParser();
6282   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
6283   SmallVector<unsigned, 10> Regs;
6284 
6285   if (Parser.getTok().isNot(AsmToken::Dollar))
6286     return MatchOperand_ParseFail;
6287 
6288   SMLoc S = Parser.getTok().getLoc();
6289 
6290   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
6291     return MatchOperand_ParseFail;
6292 
6293   MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
6294   unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
6295   Regs.push_back(RegNo);
6296 
6297   SMLoc E = Parser.getTok().getLoc();
6298   if (Parser.getTok().isNot(AsmToken::Comma)) {
6299     Error(E, "',' expected");
6300     return MatchOperand_ParseFail;
6301   }
6302 
6303   // Remove comma.
6304   Parser.Lex();
6305 
6306   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
6307     return MatchOperand_ParseFail;
6308 
6309   Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
6310   RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
6311   Regs.push_back(RegNo);
6312 
6313   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
6314 
6315   return MatchOperand_Success;
6316 }
6317 
6318 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
6319 /// either this.
6320 /// ::= '(', register, ')'
6321 /// handle it before we iterate so we don't get tripped up by the lack of
6322 /// a comma.
6323 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
6324   MCAsmParser &Parser = getParser();
6325   if (getLexer().is(AsmToken::LParen)) {
6326     Operands.push_back(
6327         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
6328     Parser.Lex();
6329     if (parseOperand(Operands, Name)) {
6330       SMLoc Loc = getLexer().getLoc();
6331       return Error(Loc, "unexpected token in argument list");
6332     }
6333     if (Parser.getTok().isNot(AsmToken::RParen)) {
6334       SMLoc Loc = getLexer().getLoc();
6335       return Error(Loc, "unexpected token, expected ')'");
6336     }
6337     Operands.push_back(
6338         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
6339     Parser.Lex();
6340   }
6341   return false;
6342 }
6343 
6344 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
6345 /// either one of these.
6346 /// ::= '[', register, ']'
6347 /// ::= '[', integer, ']'
6348 /// handle it before we iterate so we don't get tripped up by the lack of
6349 /// a comma.
6350 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
6351                                        OperandVector &Operands) {
6352   MCAsmParser &Parser = getParser();
6353   if (getLexer().is(AsmToken::LBrac)) {
6354     Operands.push_back(
6355         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
6356     Parser.Lex();
6357     if (parseOperand(Operands, Name)) {
6358       SMLoc Loc = getLexer().getLoc();
6359       return Error(Loc, "unexpected token in argument list");
6360     }
6361     if (Parser.getTok().isNot(AsmToken::RBrac)) {
6362       SMLoc Loc = getLexer().getLoc();
6363       return Error(Loc, "unexpected token, expected ']'");
6364     }
6365     Operands.push_back(
6366         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
6367     Parser.Lex();
6368   }
6369   return false;
6370 }
6371 
6372 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6373                                      SMLoc NameLoc, OperandVector &Operands) {
6374   MCAsmParser &Parser = getParser();
6375   LLVM_DEBUG(dbgs() << "ParseInstruction\n");
6376 
6377   // We have reached first instruction, module directive are now forbidden.
6378   getTargetStreamer().forbidModuleDirective();
6379 
6380   // Check if we have valid mnemonic
6381   if (!mnemonicIsValid(Name, 0)) {
6382     return Error(NameLoc, "unknown instruction");
6383   }
6384   // First operand in MCInst is instruction mnemonic.
6385   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
6386 
6387   // Read the remaining operands.
6388   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6389     // Read the first operand.
6390     if (parseOperand(Operands, Name)) {
6391       SMLoc Loc = getLexer().getLoc();
6392       return Error(Loc, "unexpected token in argument list");
6393     }
6394     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
6395       return true;
6396     // AFAIK, parenthesis suffixes are never on the first operand
6397 
6398     while (getLexer().is(AsmToken::Comma)) {
6399       Parser.Lex(); // Eat the comma.
6400       // Parse and remember the operand.
6401       if (parseOperand(Operands, Name)) {
6402         SMLoc Loc = getLexer().getLoc();
6403         return Error(Loc, "unexpected token in argument list");
6404       }
6405       // Parse bracket and parenthesis suffixes before we iterate
6406       if (getLexer().is(AsmToken::LBrac)) {
6407         if (parseBracketSuffix(Name, Operands))
6408           return true;
6409       } else if (getLexer().is(AsmToken::LParen) &&
6410                  parseParenSuffix(Name, Operands))
6411         return true;
6412     }
6413   }
6414   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6415     SMLoc Loc = getLexer().getLoc();
6416     return Error(Loc, "unexpected token in argument list");
6417   }
6418   Parser.Lex(); // Consume the EndOfStatement.
6419   return false;
6420 }
6421 
6422 // FIXME: Given that these have the same name, these should both be
6423 // consistent on affecting the Parser.
6424 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
6425   SMLoc Loc = getLexer().getLoc();
6426   return Error(Loc, ErrorMsg);
6427 }
6428 
6429 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
6430   return Error(Loc, ErrorMsg);
6431 }
6432 
6433 bool MipsAsmParser::parseSetNoAtDirective() {
6434   MCAsmParser &Parser = getParser();
6435   // Line should look like: ".set noat".
6436 
6437   // Set the $at register to $0.
6438   AssemblerOptions.back()->setATRegIndex(0);
6439 
6440   Parser.Lex(); // Eat "noat".
6441 
6442   // If this is not the end of the statement, report an error.
6443   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6444     reportParseError("unexpected token, expected end of statement");
6445     return false;
6446   }
6447 
6448   getTargetStreamer().emitDirectiveSetNoAt();
6449   Parser.Lex(); // Consume the EndOfStatement.
6450   return false;
6451 }
6452 
6453 bool MipsAsmParser::parseSetAtDirective() {
6454   // Line can be: ".set at", which sets $at to $1
6455   //          or  ".set at=$reg", which sets $at to $reg.
6456   MCAsmParser &Parser = getParser();
6457   Parser.Lex(); // Eat "at".
6458 
6459   if (getLexer().is(AsmToken::EndOfStatement)) {
6460     // No register was specified, so we set $at to $1.
6461     AssemblerOptions.back()->setATRegIndex(1);
6462 
6463     getTargetStreamer().emitDirectiveSetAt();
6464     Parser.Lex(); // Consume the EndOfStatement.
6465     return false;
6466   }
6467 
6468   if (getLexer().isNot(AsmToken::Equal)) {
6469     reportParseError("unexpected token, expected equals sign");
6470     return false;
6471   }
6472   Parser.Lex(); // Eat "=".
6473 
6474   if (getLexer().isNot(AsmToken::Dollar)) {
6475     if (getLexer().is(AsmToken::EndOfStatement)) {
6476       reportParseError("no register specified");
6477       return false;
6478     } else {
6479       reportParseError("unexpected token, expected dollar sign '$'");
6480       return false;
6481     }
6482   }
6483   Parser.Lex(); // Eat "$".
6484 
6485   // Find out what "reg" is.
6486   unsigned AtRegNo;
6487   const AsmToken &Reg = Parser.getTok();
6488   if (Reg.is(AsmToken::Identifier)) {
6489     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
6490   } else if (Reg.is(AsmToken::Integer)) {
6491     AtRegNo = Reg.getIntVal();
6492   } else {
6493     reportParseError("unexpected token, expected identifier or integer");
6494     return false;
6495   }
6496 
6497   // Check if $reg is a valid register. If it is, set $at to $reg.
6498   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
6499     reportParseError("invalid register");
6500     return false;
6501   }
6502   Parser.Lex(); // Eat "reg".
6503 
6504   // If this is not the end of the statement, report an error.
6505   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6506     reportParseError("unexpected token, expected end of statement");
6507     return false;
6508   }
6509 
6510   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
6511 
6512   Parser.Lex(); // Consume the EndOfStatement.
6513   return false;
6514 }
6515 
6516 bool MipsAsmParser::parseSetReorderDirective() {
6517   MCAsmParser &Parser = getParser();
6518   Parser.Lex();
6519   // If this is not the end of the statement, report an error.
6520   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6521     reportParseError("unexpected token, expected end of statement");
6522     return false;
6523   }
6524   AssemblerOptions.back()->setReorder();
6525   getTargetStreamer().emitDirectiveSetReorder();
6526   Parser.Lex(); // Consume the EndOfStatement.
6527   return false;
6528 }
6529 
6530 bool MipsAsmParser::parseSetNoReorderDirective() {
6531   MCAsmParser &Parser = getParser();
6532   Parser.Lex();
6533   // If this is not the end of the statement, report an error.
6534   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6535     reportParseError("unexpected token, expected end of statement");
6536     return false;
6537   }
6538   AssemblerOptions.back()->setNoReorder();
6539   getTargetStreamer().emitDirectiveSetNoReorder();
6540   Parser.Lex(); // Consume the EndOfStatement.
6541   return false;
6542 }
6543 
6544 bool MipsAsmParser::parseSetMacroDirective() {
6545   MCAsmParser &Parser = getParser();
6546   Parser.Lex();
6547   // If this is not the end of the statement, report an error.
6548   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6549     reportParseError("unexpected token, expected end of statement");
6550     return false;
6551   }
6552   AssemblerOptions.back()->setMacro();
6553   getTargetStreamer().emitDirectiveSetMacro();
6554   Parser.Lex(); // Consume the EndOfStatement.
6555   return false;
6556 }
6557 
6558 bool MipsAsmParser::parseSetNoMacroDirective() {
6559   MCAsmParser &Parser = getParser();
6560   Parser.Lex();
6561   // If this is not the end of the statement, report an error.
6562   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6563     reportParseError("unexpected token, expected end of statement");
6564     return false;
6565   }
6566   if (AssemblerOptions.back()->isReorder()) {
6567     reportParseError("`noreorder' must be set before `nomacro'");
6568     return false;
6569   }
6570   AssemblerOptions.back()->setNoMacro();
6571   getTargetStreamer().emitDirectiveSetNoMacro();
6572   Parser.Lex(); // Consume the EndOfStatement.
6573   return false;
6574 }
6575 
6576 bool MipsAsmParser::parseSetMsaDirective() {
6577   MCAsmParser &Parser = getParser();
6578   Parser.Lex();
6579 
6580   // If this is not the end of the statement, report an error.
6581   if (getLexer().isNot(AsmToken::EndOfStatement))
6582     return reportParseError("unexpected token, expected end of statement");
6583 
6584   setFeatureBits(Mips::FeatureMSA, "msa");
6585   getTargetStreamer().emitDirectiveSetMsa();
6586   return false;
6587 }
6588 
6589 bool MipsAsmParser::parseSetNoMsaDirective() {
6590   MCAsmParser &Parser = getParser();
6591   Parser.Lex();
6592 
6593   // If this is not the end of the statement, report an error.
6594   if (getLexer().isNot(AsmToken::EndOfStatement))
6595     return reportParseError("unexpected token, expected end of statement");
6596 
6597   clearFeatureBits(Mips::FeatureMSA, "msa");
6598   getTargetStreamer().emitDirectiveSetNoMsa();
6599   return false;
6600 }
6601 
6602 bool MipsAsmParser::parseSetNoDspDirective() {
6603   MCAsmParser &Parser = getParser();
6604   Parser.Lex(); // Eat "nodsp".
6605 
6606   // If this is not the end of the statement, report an error.
6607   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6608     reportParseError("unexpected token, expected end of statement");
6609     return false;
6610   }
6611 
6612   clearFeatureBits(Mips::FeatureDSP, "dsp");
6613   getTargetStreamer().emitDirectiveSetNoDsp();
6614   return false;
6615 }
6616 
6617 bool MipsAsmParser::parseSetMips16Directive() {
6618   MCAsmParser &Parser = getParser();
6619   Parser.Lex(); // Eat "mips16".
6620 
6621   // If this is not the end of the statement, report an error.
6622   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6623     reportParseError("unexpected token, expected end of statement");
6624     return false;
6625   }
6626 
6627   setFeatureBits(Mips::FeatureMips16, "mips16");
6628   getTargetStreamer().emitDirectiveSetMips16();
6629   Parser.Lex(); // Consume the EndOfStatement.
6630   return false;
6631 }
6632 
6633 bool MipsAsmParser::parseSetNoMips16Directive() {
6634   MCAsmParser &Parser = getParser();
6635   Parser.Lex(); // Eat "nomips16".
6636 
6637   // If this is not the end of the statement, report an error.
6638   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6639     reportParseError("unexpected token, expected end of statement");
6640     return false;
6641   }
6642 
6643   clearFeatureBits(Mips::FeatureMips16, "mips16");
6644   getTargetStreamer().emitDirectiveSetNoMips16();
6645   Parser.Lex(); // Consume the EndOfStatement.
6646   return false;
6647 }
6648 
6649 bool MipsAsmParser::parseSetFpDirective() {
6650   MCAsmParser &Parser = getParser();
6651   MipsABIFlagsSection::FpABIKind FpAbiVal;
6652   // Line can be: .set fp=32
6653   //              .set fp=xx
6654   //              .set fp=64
6655   Parser.Lex(); // Eat fp token
6656   AsmToken Tok = Parser.getTok();
6657   if (Tok.isNot(AsmToken::Equal)) {
6658     reportParseError("unexpected token, expected equals sign '='");
6659     return false;
6660   }
6661   Parser.Lex(); // Eat '=' token.
6662   Tok = Parser.getTok();
6663 
6664   if (!parseFpABIValue(FpAbiVal, ".set"))
6665     return false;
6666 
6667   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6668     reportParseError("unexpected token, expected end of statement");
6669     return false;
6670   }
6671   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
6672   Parser.Lex(); // Consume the EndOfStatement.
6673   return false;
6674 }
6675 
6676 bool MipsAsmParser::parseSetOddSPRegDirective() {
6677   MCAsmParser &Parser = getParser();
6678 
6679   Parser.Lex(); // Eat "oddspreg".
6680   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6681     reportParseError("unexpected token, expected end of statement");
6682     return false;
6683   }
6684 
6685   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
6686   getTargetStreamer().emitDirectiveSetOddSPReg();
6687   return false;
6688 }
6689 
6690 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
6691   MCAsmParser &Parser = getParser();
6692 
6693   Parser.Lex(); // Eat "nooddspreg".
6694   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6695     reportParseError("unexpected token, expected end of statement");
6696     return false;
6697   }
6698 
6699   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
6700   getTargetStreamer().emitDirectiveSetNoOddSPReg();
6701   return false;
6702 }
6703 
6704 bool MipsAsmParser::parseSetMtDirective() {
6705   MCAsmParser &Parser = getParser();
6706   Parser.Lex(); // Eat "mt".
6707 
6708   // If this is not the end of the statement, report an error.
6709   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6710     reportParseError("unexpected token, expected end of statement");
6711     return false;
6712   }
6713 
6714   setFeatureBits(Mips::FeatureMT, "mt");
6715   getTargetStreamer().emitDirectiveSetMt();
6716   Parser.Lex(); // Consume the EndOfStatement.
6717   return false;
6718 }
6719 
6720 bool MipsAsmParser::parseSetNoMtDirective() {
6721   MCAsmParser &Parser = getParser();
6722   Parser.Lex(); // Eat "nomt".
6723 
6724   // If this is not the end of the statement, report an error.
6725   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6726     reportParseError("unexpected token, expected end of statement");
6727     return false;
6728   }
6729 
6730   clearFeatureBits(Mips::FeatureMT, "mt");
6731 
6732   getTargetStreamer().emitDirectiveSetNoMt();
6733   Parser.Lex(); // Consume the EndOfStatement.
6734   return false;
6735 }
6736 
6737 bool MipsAsmParser::parseSetNoCRCDirective() {
6738   MCAsmParser &Parser = getParser();
6739   Parser.Lex(); // Eat "nocrc".
6740 
6741   // If this is not the end of the statement, report an error.
6742   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6743     reportParseError("unexpected token, expected end of statement");
6744     return false;
6745   }
6746 
6747   clearFeatureBits(Mips::FeatureCRC, "crc");
6748 
6749   getTargetStreamer().emitDirectiveSetNoCRC();
6750   Parser.Lex(); // Consume the EndOfStatement.
6751   return false;
6752 }
6753 
6754 bool MipsAsmParser::parseSetNoVirtDirective() {
6755   MCAsmParser &Parser = getParser();
6756   Parser.Lex(); // Eat "novirt".
6757 
6758   // If this is not the end of the statement, report an error.
6759   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6760     reportParseError("unexpected token, expected end of statement");
6761     return false;
6762   }
6763 
6764   clearFeatureBits(Mips::FeatureVirt, "virt");
6765 
6766   getTargetStreamer().emitDirectiveSetNoVirt();
6767   Parser.Lex(); // Consume the EndOfStatement.
6768   return false;
6769 }
6770 
6771 bool MipsAsmParser::parseSetNoGINVDirective() {
6772   MCAsmParser &Parser = getParser();
6773   Parser.Lex(); // Eat "noginv".
6774 
6775   // If this is not the end of the statement, report an error.
6776   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6777     reportParseError("unexpected token, expected end of statement");
6778     return false;
6779   }
6780 
6781   clearFeatureBits(Mips::FeatureGINV, "ginv");
6782 
6783   getTargetStreamer().emitDirectiveSetNoGINV();
6784   Parser.Lex(); // Consume the EndOfStatement.
6785   return false;
6786 }
6787 
6788 bool MipsAsmParser::parseSetPopDirective() {
6789   MCAsmParser &Parser = getParser();
6790   SMLoc Loc = getLexer().getLoc();
6791 
6792   Parser.Lex();
6793   if (getLexer().isNot(AsmToken::EndOfStatement))
6794     return reportParseError("unexpected token, expected end of statement");
6795 
6796   // Always keep an element on the options "stack" to prevent the user
6797   // from changing the initial options. This is how we remember them.
6798   if (AssemblerOptions.size() == 2)
6799     return reportParseError(Loc, ".set pop with no .set push");
6800 
6801   MCSubtargetInfo &STI = copySTI();
6802   AssemblerOptions.pop_back();
6803   setAvailableFeatures(
6804       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
6805   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
6806 
6807   getTargetStreamer().emitDirectiveSetPop();
6808   return false;
6809 }
6810 
6811 bool MipsAsmParser::parseSetPushDirective() {
6812   MCAsmParser &Parser = getParser();
6813   Parser.Lex();
6814   if (getLexer().isNot(AsmToken::EndOfStatement))
6815     return reportParseError("unexpected token, expected end of statement");
6816 
6817   // Create a copy of the current assembler options environment and push it.
6818   AssemblerOptions.push_back(
6819         llvm::make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
6820 
6821   getTargetStreamer().emitDirectiveSetPush();
6822   return false;
6823 }
6824 
6825 bool MipsAsmParser::parseSetSoftFloatDirective() {
6826   MCAsmParser &Parser = getParser();
6827   Parser.Lex();
6828   if (getLexer().isNot(AsmToken::EndOfStatement))
6829     return reportParseError("unexpected token, expected end of statement");
6830 
6831   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
6832   getTargetStreamer().emitDirectiveSetSoftFloat();
6833   return false;
6834 }
6835 
6836 bool MipsAsmParser::parseSetHardFloatDirective() {
6837   MCAsmParser &Parser = getParser();
6838   Parser.Lex();
6839   if (getLexer().isNot(AsmToken::EndOfStatement))
6840     return reportParseError("unexpected token, expected end of statement");
6841 
6842   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
6843   getTargetStreamer().emitDirectiveSetHardFloat();
6844   return false;
6845 }
6846 
6847 bool MipsAsmParser::parseSetAssignment() {
6848   StringRef Name;
6849   const MCExpr *Value;
6850   MCAsmParser &Parser = getParser();
6851 
6852   if (Parser.parseIdentifier(Name))
6853     return reportParseError("expected identifier after .set");
6854 
6855   if (getLexer().isNot(AsmToken::Comma))
6856     return reportParseError("unexpected token, expected comma");
6857   Lex(); // Eat comma
6858 
6859   if (getLexer().is(AsmToken::Dollar) &&
6860       getLexer().peekTok().is(AsmToken::Integer)) {
6861     // Parse assignment of a numeric register:
6862     //   .set r1,$1
6863     Parser.Lex(); // Eat $.
6864     RegisterSets[Name] = Parser.getTok();
6865     Parser.Lex(); // Eat identifier.
6866     getContext().getOrCreateSymbol(Name);
6867   } else if (!Parser.parseExpression(Value)) {
6868     // Parse assignment of an expression including
6869     // symbolic registers:
6870     //   .set  $tmp, $BB0-$BB1
6871     //   .set  r2, $f2
6872     MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
6873     Sym->setVariableValue(Value);
6874   } else {
6875     return reportParseError("expected valid expression after comma");
6876   }
6877 
6878   return false;
6879 }
6880 
6881 bool MipsAsmParser::parseSetMips0Directive() {
6882   MCAsmParser &Parser = getParser();
6883   Parser.Lex();
6884   if (getLexer().isNot(AsmToken::EndOfStatement))
6885     return reportParseError("unexpected token, expected end of statement");
6886 
6887   // Reset assembler options to their initial values.
6888   MCSubtargetInfo &STI = copySTI();
6889   setAvailableFeatures(
6890       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
6891   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
6892   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
6893 
6894   getTargetStreamer().emitDirectiveSetMips0();
6895   return false;
6896 }
6897 
6898 bool MipsAsmParser::parseSetArchDirective() {
6899   MCAsmParser &Parser = getParser();
6900   Parser.Lex();
6901   if (getLexer().isNot(AsmToken::Equal))
6902     return reportParseError("unexpected token, expected equals sign");
6903 
6904   Parser.Lex();
6905   StringRef Arch;
6906   if (Parser.parseIdentifier(Arch))
6907     return reportParseError("expected arch identifier");
6908 
6909   StringRef ArchFeatureName =
6910       StringSwitch<StringRef>(Arch)
6911           .Case("mips1", "mips1")
6912           .Case("mips2", "mips2")
6913           .Case("mips3", "mips3")
6914           .Case("mips4", "mips4")
6915           .Case("mips5", "mips5")
6916           .Case("mips32", "mips32")
6917           .Case("mips32r2", "mips32r2")
6918           .Case("mips32r3", "mips32r3")
6919           .Case("mips32r5", "mips32r5")
6920           .Case("mips32r6", "mips32r6")
6921           .Case("mips64", "mips64")
6922           .Case("mips64r2", "mips64r2")
6923           .Case("mips64r3", "mips64r3")
6924           .Case("mips64r5", "mips64r5")
6925           .Case("mips64r6", "mips64r6")
6926           .Case("octeon", "cnmips")
6927           .Case("r4000", "mips3") // This is an implementation of Mips3.
6928           .Default("");
6929 
6930   if (ArchFeatureName.empty())
6931     return reportParseError("unsupported architecture");
6932 
6933   if (ArchFeatureName == "mips64r6" && inMicroMipsMode())
6934     return reportParseError("mips64r6 does not support microMIPS");
6935 
6936   selectArch(ArchFeatureName);
6937   getTargetStreamer().emitDirectiveSetArch(Arch);
6938   return false;
6939 }
6940 
6941 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
6942   MCAsmParser &Parser = getParser();
6943   Parser.Lex();
6944   if (getLexer().isNot(AsmToken::EndOfStatement))
6945     return reportParseError("unexpected token, expected end of statement");
6946 
6947   switch (Feature) {
6948   default:
6949     llvm_unreachable("Unimplemented feature");
6950   case Mips::FeatureDSP:
6951     setFeatureBits(Mips::FeatureDSP, "dsp");
6952     getTargetStreamer().emitDirectiveSetDsp();
6953     break;
6954   case Mips::FeatureDSPR2:
6955     setFeatureBits(Mips::FeatureDSPR2, "dspr2");
6956     getTargetStreamer().emitDirectiveSetDspr2();
6957     break;
6958   case Mips::FeatureMicroMips:
6959     setFeatureBits(Mips::FeatureMicroMips, "micromips");
6960     getTargetStreamer().emitDirectiveSetMicroMips();
6961     break;
6962   case Mips::FeatureMips1:
6963     selectArch("mips1");
6964     getTargetStreamer().emitDirectiveSetMips1();
6965     break;
6966   case Mips::FeatureMips2:
6967     selectArch("mips2");
6968     getTargetStreamer().emitDirectiveSetMips2();
6969     break;
6970   case Mips::FeatureMips3:
6971     selectArch("mips3");
6972     getTargetStreamer().emitDirectiveSetMips3();
6973     break;
6974   case Mips::FeatureMips4:
6975     selectArch("mips4");
6976     getTargetStreamer().emitDirectiveSetMips4();
6977     break;
6978   case Mips::FeatureMips5:
6979     selectArch("mips5");
6980     getTargetStreamer().emitDirectiveSetMips5();
6981     break;
6982   case Mips::FeatureMips32:
6983     selectArch("mips32");
6984     getTargetStreamer().emitDirectiveSetMips32();
6985     break;
6986   case Mips::FeatureMips32r2:
6987     selectArch("mips32r2");
6988     getTargetStreamer().emitDirectiveSetMips32R2();
6989     break;
6990   case Mips::FeatureMips32r3:
6991     selectArch("mips32r3");
6992     getTargetStreamer().emitDirectiveSetMips32R3();
6993     break;
6994   case Mips::FeatureMips32r5:
6995     selectArch("mips32r5");
6996     getTargetStreamer().emitDirectiveSetMips32R5();
6997     break;
6998   case Mips::FeatureMips32r6:
6999     selectArch("mips32r6");
7000     getTargetStreamer().emitDirectiveSetMips32R6();
7001     break;
7002   case Mips::FeatureMips64:
7003     selectArch("mips64");
7004     getTargetStreamer().emitDirectiveSetMips64();
7005     break;
7006   case Mips::FeatureMips64r2:
7007     selectArch("mips64r2");
7008     getTargetStreamer().emitDirectiveSetMips64R2();
7009     break;
7010   case Mips::FeatureMips64r3:
7011     selectArch("mips64r3");
7012     getTargetStreamer().emitDirectiveSetMips64R3();
7013     break;
7014   case Mips::FeatureMips64r5:
7015     selectArch("mips64r5");
7016     getTargetStreamer().emitDirectiveSetMips64R5();
7017     break;
7018   case Mips::FeatureMips64r6:
7019     selectArch("mips64r6");
7020     getTargetStreamer().emitDirectiveSetMips64R6();
7021     break;
7022   case Mips::FeatureCRC:
7023     setFeatureBits(Mips::FeatureCRC, "crc");
7024     getTargetStreamer().emitDirectiveSetCRC();
7025     break;
7026   case Mips::FeatureVirt:
7027     setFeatureBits(Mips::FeatureVirt, "virt");
7028     getTargetStreamer().emitDirectiveSetVirt();
7029     break;
7030   case Mips::FeatureGINV:
7031     setFeatureBits(Mips::FeatureGINV, "ginv");
7032     getTargetStreamer().emitDirectiveSetGINV();
7033     break;
7034   }
7035   return false;
7036 }
7037 
7038 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
7039   MCAsmParser &Parser = getParser();
7040   if (getLexer().isNot(AsmToken::Comma)) {
7041     SMLoc Loc = getLexer().getLoc();
7042     return Error(Loc, ErrorStr);
7043   }
7044 
7045   Parser.Lex(); // Eat the comma.
7046   return true;
7047 }
7048 
7049 // Used to determine if .cpload, .cprestore, and .cpsetup have any effect.
7050 // In this class, it is only used for .cprestore.
7051 // FIXME: Only keep track of IsPicEnabled in one place, instead of in both
7052 // MipsTargetELFStreamer and MipsAsmParser.
7053 bool MipsAsmParser::isPicAndNotNxxAbi() {
7054   return inPicMode() && !(isABI_N32() || isABI_N64());
7055 }
7056 
7057 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
7058   if (AssemblerOptions.back()->isReorder())
7059     Warning(Loc, ".cpload should be inside a noreorder section");
7060 
7061   if (inMips16Mode()) {
7062     reportParseError(".cpload is not supported in Mips16 mode");
7063     return false;
7064   }
7065 
7066   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
7067   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
7068   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
7069     reportParseError("expected register containing function address");
7070     return false;
7071   }
7072 
7073   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
7074   if (!RegOpnd.isGPRAsmReg()) {
7075     reportParseError(RegOpnd.getStartLoc(), "invalid register");
7076     return false;
7077   }
7078 
7079   // If this is not the end of the statement, report an error.
7080   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7081     reportParseError("unexpected token, expected end of statement");
7082     return false;
7083   }
7084 
7085   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
7086   return false;
7087 }
7088 
7089 bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) {
7090   MCAsmParser &Parser = getParser();
7091 
7092   // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
7093   // is used in non-PIC mode.
7094 
7095   if (inMips16Mode()) {
7096     reportParseError(".cprestore is not supported in Mips16 mode");
7097     return false;
7098   }
7099 
7100   // Get the stack offset value.
7101   const MCExpr *StackOffset;
7102   int64_t StackOffsetVal;
7103   if (Parser.parseExpression(StackOffset)) {
7104     reportParseError("expected stack offset value");
7105     return false;
7106   }
7107 
7108   if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) {
7109     reportParseError("stack offset is not an absolute expression");
7110     return false;
7111   }
7112 
7113   if (StackOffsetVal < 0) {
7114     Warning(Loc, ".cprestore with negative stack offset has no effect");
7115     IsCpRestoreSet = false;
7116   } else {
7117     IsCpRestoreSet = true;
7118     CpRestoreOffset = StackOffsetVal;
7119   }
7120 
7121   // If this is not the end of the statement, report an error.
7122   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7123     reportParseError("unexpected token, expected end of statement");
7124     return false;
7125   }
7126 
7127   if (!getTargetStreamer().emitDirectiveCpRestore(
7128           CpRestoreOffset, [&]() { return getATReg(Loc); }, Loc, STI))
7129     return true;
7130   Parser.Lex(); // Consume the EndOfStatement.
7131   return false;
7132 }
7133 
7134 bool MipsAsmParser::parseDirectiveCPSetup() {
7135   MCAsmParser &Parser = getParser();
7136   unsigned FuncReg;
7137   unsigned Save;
7138   bool SaveIsReg = true;
7139 
7140   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
7141   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
7142   if (ResTy == MatchOperand_NoMatch) {
7143     reportParseError("expected register containing function address");
7144     return false;
7145   }
7146 
7147   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
7148   if (!FuncRegOpnd.isGPRAsmReg()) {
7149     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
7150     return false;
7151   }
7152 
7153   FuncReg = FuncRegOpnd.getGPR32Reg();
7154   TmpReg.clear();
7155 
7156   if (!eatComma("unexpected token, expected comma"))
7157     return true;
7158 
7159   ResTy = parseAnyRegister(TmpReg);
7160   if (ResTy == MatchOperand_NoMatch) {
7161     const MCExpr *OffsetExpr;
7162     int64_t OffsetVal;
7163     SMLoc ExprLoc = getLexer().getLoc();
7164 
7165     if (Parser.parseExpression(OffsetExpr) ||
7166         !OffsetExpr->evaluateAsAbsolute(OffsetVal)) {
7167       reportParseError(ExprLoc, "expected save register or stack offset");
7168       return false;
7169     }
7170 
7171     Save = OffsetVal;
7172     SaveIsReg = false;
7173   } else {
7174     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
7175     if (!SaveOpnd.isGPRAsmReg()) {
7176       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
7177       return false;
7178     }
7179     Save = SaveOpnd.getGPR32Reg();
7180   }
7181 
7182   if (!eatComma("unexpected token, expected comma"))
7183     return true;
7184 
7185   const MCExpr *Expr;
7186   if (Parser.parseExpression(Expr)) {
7187     reportParseError("expected expression");
7188     return false;
7189   }
7190 
7191   if (Expr->getKind() != MCExpr::SymbolRef) {
7192     reportParseError("expected symbol");
7193     return false;
7194   }
7195   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
7196 
7197   CpSaveLocation = Save;
7198   CpSaveLocationIsRegister = SaveIsReg;
7199 
7200   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
7201                                            SaveIsReg);
7202   return false;
7203 }
7204 
7205 bool MipsAsmParser::parseDirectiveCPReturn() {
7206   getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation,
7207                                             CpSaveLocationIsRegister);
7208   return false;
7209 }
7210 
7211 bool MipsAsmParser::parseDirectiveNaN() {
7212   MCAsmParser &Parser = getParser();
7213   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7214     const AsmToken &Tok = Parser.getTok();
7215 
7216     if (Tok.getString() == "2008") {
7217       Parser.Lex();
7218       getTargetStreamer().emitDirectiveNaN2008();
7219       return false;
7220     } else if (Tok.getString() == "legacy") {
7221       Parser.Lex();
7222       getTargetStreamer().emitDirectiveNaNLegacy();
7223       return false;
7224     }
7225   }
7226   // If we don't recognize the option passed to the .nan
7227   // directive (e.g. no option or unknown option), emit an error.
7228   reportParseError("invalid option in .nan directive");
7229   return false;
7230 }
7231 
7232 bool MipsAsmParser::parseDirectiveSet() {
7233   const AsmToken &Tok = getParser().getTok();
7234   StringRef IdVal = Tok.getString();
7235   SMLoc Loc = Tok.getLoc();
7236 
7237   if (IdVal == "noat")
7238     return parseSetNoAtDirective();
7239   if (IdVal == "at")
7240     return parseSetAtDirective();
7241   if (IdVal == "arch")
7242     return parseSetArchDirective();
7243   if (IdVal == "bopt") {
7244     Warning(Loc, "'bopt' feature is unsupported");
7245     getParser().Lex();
7246     return false;
7247   }
7248   if (IdVal == "nobopt") {
7249     // We're already running in nobopt mode, so nothing to do.
7250     getParser().Lex();
7251     return false;
7252   }
7253   if (IdVal == "fp")
7254     return parseSetFpDirective();
7255   if (IdVal == "oddspreg")
7256     return parseSetOddSPRegDirective();
7257   if (IdVal == "nooddspreg")
7258     return parseSetNoOddSPRegDirective();
7259   if (IdVal == "pop")
7260     return parseSetPopDirective();
7261   if (IdVal == "push")
7262     return parseSetPushDirective();
7263   if (IdVal == "reorder")
7264     return parseSetReorderDirective();
7265   if (IdVal == "noreorder")
7266     return parseSetNoReorderDirective();
7267   if (IdVal == "macro")
7268     return parseSetMacroDirective();
7269   if (IdVal == "nomacro")
7270     return parseSetNoMacroDirective();
7271   if (IdVal == "mips16")
7272     return parseSetMips16Directive();
7273   if (IdVal == "nomips16")
7274     return parseSetNoMips16Directive();
7275   if (IdVal == "nomicromips") {
7276     clearFeatureBits(Mips::FeatureMicroMips, "micromips");
7277     getTargetStreamer().emitDirectiveSetNoMicroMips();
7278     getParser().eatToEndOfStatement();
7279     return false;
7280   }
7281   if (IdVal == "micromips") {
7282     if (hasMips64r6()) {
7283       Error(Loc, ".set micromips directive is not supported with MIPS64R6");
7284       return false;
7285     }
7286     return parseSetFeature(Mips::FeatureMicroMips);
7287   }
7288   if (IdVal == "mips0")
7289     return parseSetMips0Directive();
7290   if (IdVal == "mips1")
7291     return parseSetFeature(Mips::FeatureMips1);
7292   if (IdVal == "mips2")
7293     return parseSetFeature(Mips::FeatureMips2);
7294   if (IdVal == "mips3")
7295     return parseSetFeature(Mips::FeatureMips3);
7296   if (IdVal == "mips4")
7297     return parseSetFeature(Mips::FeatureMips4);
7298   if (IdVal == "mips5")
7299     return parseSetFeature(Mips::FeatureMips5);
7300   if (IdVal == "mips32")
7301     return parseSetFeature(Mips::FeatureMips32);
7302   if (IdVal == "mips32r2")
7303     return parseSetFeature(Mips::FeatureMips32r2);
7304   if (IdVal == "mips32r3")
7305     return parseSetFeature(Mips::FeatureMips32r3);
7306   if (IdVal == "mips32r5")
7307     return parseSetFeature(Mips::FeatureMips32r5);
7308   if (IdVal == "mips32r6")
7309     return parseSetFeature(Mips::FeatureMips32r6);
7310   if (IdVal == "mips64")
7311     return parseSetFeature(Mips::FeatureMips64);
7312   if (IdVal == "mips64r2")
7313     return parseSetFeature(Mips::FeatureMips64r2);
7314   if (IdVal == "mips64r3")
7315     return parseSetFeature(Mips::FeatureMips64r3);
7316   if (IdVal == "mips64r5")
7317     return parseSetFeature(Mips::FeatureMips64r5);
7318   if (IdVal == "mips64r6") {
7319     if (inMicroMipsMode()) {
7320       Error(Loc, "MIPS64R6 is not supported with microMIPS");
7321       return false;
7322     }
7323     return parseSetFeature(Mips::FeatureMips64r6);
7324   }
7325   if (IdVal == "dsp")
7326     return parseSetFeature(Mips::FeatureDSP);
7327   if (IdVal == "dspr2")
7328     return parseSetFeature(Mips::FeatureDSPR2);
7329   if (IdVal == "nodsp")
7330     return parseSetNoDspDirective();
7331   if (IdVal == "msa")
7332     return parseSetMsaDirective();
7333   if (IdVal == "nomsa")
7334     return parseSetNoMsaDirective();
7335   if (IdVal == "mt")
7336     return parseSetMtDirective();
7337   if (IdVal == "nomt")
7338     return parseSetNoMtDirective();
7339   if (IdVal == "softfloat")
7340     return parseSetSoftFloatDirective();
7341   if (IdVal == "hardfloat")
7342     return parseSetHardFloatDirective();
7343   if (IdVal == "crc")
7344     return parseSetFeature(Mips::FeatureCRC);
7345   if (IdVal == "nocrc")
7346     return parseSetNoCRCDirective();
7347   if (IdVal == "virt")
7348     return parseSetFeature(Mips::FeatureVirt);
7349   if (IdVal == "novirt")
7350     return parseSetNoVirtDirective();
7351   if (IdVal == "ginv")
7352     return parseSetFeature(Mips::FeatureGINV);
7353   if (IdVal == "noginv")
7354     return parseSetNoGINVDirective();
7355 
7356   // It is just an identifier, look for an assignment.
7357   return parseSetAssignment();
7358 }
7359 
7360 /// parseDataDirective
7361 ///  ::= .word [ expression (, expression)* ]
7362 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
7363   MCAsmParser &Parser = getParser();
7364   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7365     while (true) {
7366       const MCExpr *Value;
7367       if (getParser().parseExpression(Value))
7368         return true;
7369 
7370       getParser().getStreamer().EmitValue(Value, Size);
7371 
7372       if (getLexer().is(AsmToken::EndOfStatement))
7373         break;
7374 
7375       if (getLexer().isNot(AsmToken::Comma))
7376         return Error(L, "unexpected token, expected comma");
7377       Parser.Lex();
7378     }
7379   }
7380 
7381   Parser.Lex();
7382   return false;
7383 }
7384 
7385 /// parseDirectiveGpWord
7386 ///  ::= .gpword local_sym
7387 bool MipsAsmParser::parseDirectiveGpWord() {
7388   MCAsmParser &Parser = getParser();
7389   const MCExpr *Value;
7390   // EmitGPRel32Value requires an expression, so we are using base class
7391   // method to evaluate the expression.
7392   if (getParser().parseExpression(Value))
7393     return true;
7394   getParser().getStreamer().EmitGPRel32Value(Value);
7395 
7396   if (getLexer().isNot(AsmToken::EndOfStatement))
7397     return Error(getLexer().getLoc(),
7398                 "unexpected token, expected end of statement");
7399   Parser.Lex(); // Eat EndOfStatement token.
7400   return false;
7401 }
7402 
7403 /// parseDirectiveGpDWord
7404 ///  ::= .gpdword local_sym
7405 bool MipsAsmParser::parseDirectiveGpDWord() {
7406   MCAsmParser &Parser = getParser();
7407   const MCExpr *Value;
7408   // EmitGPRel64Value requires an expression, so we are using base class
7409   // method to evaluate the expression.
7410   if (getParser().parseExpression(Value))
7411     return true;
7412   getParser().getStreamer().EmitGPRel64Value(Value);
7413 
7414   if (getLexer().isNot(AsmToken::EndOfStatement))
7415     return Error(getLexer().getLoc(),
7416                 "unexpected token, expected end of statement");
7417   Parser.Lex(); // Eat EndOfStatement token.
7418   return false;
7419 }
7420 
7421 /// parseDirectiveDtpRelWord
7422 ///  ::= .dtprelword tls_sym
7423 bool MipsAsmParser::parseDirectiveDtpRelWord() {
7424   MCAsmParser &Parser = getParser();
7425   const MCExpr *Value;
7426   // EmitDTPRel32Value requires an expression, so we are using base class
7427   // method to evaluate the expression.
7428   if (getParser().parseExpression(Value))
7429     return true;
7430   getParser().getStreamer().EmitDTPRel32Value(Value);
7431 
7432   if (getLexer().isNot(AsmToken::EndOfStatement))
7433     return Error(getLexer().getLoc(),
7434                 "unexpected token, expected end of statement");
7435   Parser.Lex(); // Eat EndOfStatement token.
7436   return false;
7437 }
7438 
7439 /// parseDirectiveDtpRelDWord
7440 ///  ::= .dtpreldword tls_sym
7441 bool MipsAsmParser::parseDirectiveDtpRelDWord() {
7442   MCAsmParser &Parser = getParser();
7443   const MCExpr *Value;
7444   // EmitDTPRel64Value requires an expression, so we are using base class
7445   // method to evaluate the expression.
7446   if (getParser().parseExpression(Value))
7447     return true;
7448   getParser().getStreamer().EmitDTPRel64Value(Value);
7449 
7450   if (getLexer().isNot(AsmToken::EndOfStatement))
7451     return Error(getLexer().getLoc(),
7452                 "unexpected token, expected end of statement");
7453   Parser.Lex(); // Eat EndOfStatement token.
7454   return false;
7455 }
7456 
7457 /// parseDirectiveTpRelWord
7458 ///  ::= .tprelword tls_sym
7459 bool MipsAsmParser::parseDirectiveTpRelWord() {
7460   MCAsmParser &Parser = getParser();
7461   const MCExpr *Value;
7462   // EmitTPRel32Value requires an expression, so we are using base class
7463   // method to evaluate the expression.
7464   if (getParser().parseExpression(Value))
7465     return true;
7466   getParser().getStreamer().EmitTPRel32Value(Value);
7467 
7468   if (getLexer().isNot(AsmToken::EndOfStatement))
7469     return Error(getLexer().getLoc(),
7470                 "unexpected token, expected end of statement");
7471   Parser.Lex(); // Eat EndOfStatement token.
7472   return false;
7473 }
7474 
7475 /// parseDirectiveTpRelDWord
7476 ///  ::= .tpreldword tls_sym
7477 bool MipsAsmParser::parseDirectiveTpRelDWord() {
7478   MCAsmParser &Parser = getParser();
7479   const MCExpr *Value;
7480   // EmitTPRel64Value requires an expression, so we are using base class
7481   // method to evaluate the expression.
7482   if (getParser().parseExpression(Value))
7483     return true;
7484   getParser().getStreamer().EmitTPRel64Value(Value);
7485 
7486   if (getLexer().isNot(AsmToken::EndOfStatement))
7487     return Error(getLexer().getLoc(),
7488                 "unexpected token, expected end of statement");
7489   Parser.Lex(); // Eat EndOfStatement token.
7490   return false;
7491 }
7492 
7493 bool MipsAsmParser::parseDirectiveOption() {
7494   MCAsmParser &Parser = getParser();
7495   // Get the option token.
7496   AsmToken Tok = Parser.getTok();
7497   // At the moment only identifiers are supported.
7498   if (Tok.isNot(AsmToken::Identifier)) {
7499     return Error(Parser.getTok().getLoc(),
7500                  "unexpected token, expected identifier");
7501   }
7502 
7503   StringRef Option = Tok.getIdentifier();
7504 
7505   if (Option == "pic0") {
7506     // MipsAsmParser needs to know if the current PIC mode changes.
7507     IsPicEnabled = false;
7508 
7509     getTargetStreamer().emitDirectiveOptionPic0();
7510     Parser.Lex();
7511     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
7512       return Error(Parser.getTok().getLoc(),
7513                    "unexpected token, expected end of statement");
7514     }
7515     return false;
7516   }
7517 
7518   if (Option == "pic2") {
7519     // MipsAsmParser needs to know if the current PIC mode changes.
7520     IsPicEnabled = true;
7521 
7522     getTargetStreamer().emitDirectiveOptionPic2();
7523     Parser.Lex();
7524     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
7525       return Error(Parser.getTok().getLoc(),
7526                    "unexpected token, expected end of statement");
7527     }
7528     return false;
7529   }
7530 
7531   // Unknown option.
7532   Warning(Parser.getTok().getLoc(),
7533           "unknown option, expected 'pic0' or 'pic2'");
7534   Parser.eatToEndOfStatement();
7535   return false;
7536 }
7537 
7538 /// parseInsnDirective
7539 ///  ::= .insn
7540 bool MipsAsmParser::parseInsnDirective() {
7541   // If this is not the end of the statement, report an error.
7542   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7543     reportParseError("unexpected token, expected end of statement");
7544     return false;
7545   }
7546 
7547   // The actual label marking happens in
7548   // MipsELFStreamer::createPendingLabelRelocs().
7549   getTargetStreamer().emitDirectiveInsn();
7550 
7551   getParser().Lex(); // Eat EndOfStatement token.
7552   return false;
7553 }
7554 
7555 /// parseRSectionDirective
7556 ///  ::= .rdata
7557 bool MipsAsmParser::parseRSectionDirective(StringRef Section) {
7558   // If this is not the end of the statement, report an error.
7559   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7560     reportParseError("unexpected token, expected end of statement");
7561     return false;
7562   }
7563 
7564   MCSection *ELFSection = getContext().getELFSection(
7565       Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
7566   getParser().getStreamer().SwitchSection(ELFSection);
7567 
7568   getParser().Lex(); // Eat EndOfStatement token.
7569   return false;
7570 }
7571 
7572 /// parseSSectionDirective
7573 ///  ::= .sbss
7574 ///  ::= .sdata
7575 bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) {
7576   // If this is not the end of the statement, report an error.
7577   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7578     reportParseError("unexpected token, expected end of statement");
7579     return false;
7580   }
7581 
7582   MCSection *ELFSection = getContext().getELFSection(
7583       Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
7584   getParser().getStreamer().SwitchSection(ELFSection);
7585 
7586   getParser().Lex(); // Eat EndOfStatement token.
7587   return false;
7588 }
7589 
7590 /// parseDirectiveModule
7591 ///  ::= .module oddspreg
7592 ///  ::= .module nooddspreg
7593 ///  ::= .module fp=value
7594 ///  ::= .module softfloat
7595 ///  ::= .module hardfloat
7596 ///  ::= .module mt
7597 ///  ::= .module crc
7598 ///  ::= .module nocrc
7599 ///  ::= .module virt
7600 ///  ::= .module novirt
7601 ///  ::= .module ginv
7602 ///  ::= .module noginv
7603 bool MipsAsmParser::parseDirectiveModule() {
7604   MCAsmParser &Parser = getParser();
7605   MCAsmLexer &Lexer = getLexer();
7606   SMLoc L = Lexer.getLoc();
7607 
7608   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
7609     // TODO : get a better message.
7610     reportParseError(".module directive must appear before any code");
7611     return false;
7612   }
7613 
7614   StringRef Option;
7615   if (Parser.parseIdentifier(Option)) {
7616     reportParseError("expected .module option identifier");
7617     return false;
7618   }
7619 
7620   if (Option == "oddspreg") {
7621     clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
7622 
7623     // Synchronize the abiflags information with the FeatureBits information we
7624     // changed above.
7625     getTargetStreamer().updateABIInfo(*this);
7626 
7627     // If printing assembly, use the recently updated abiflags information.
7628     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7629     // emitted at the end).
7630     getTargetStreamer().emitDirectiveModuleOddSPReg();
7631 
7632     // If this is not the end of the statement, report an error.
7633     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7634       reportParseError("unexpected token, expected end of statement");
7635       return false;
7636     }
7637 
7638     return false; // parseDirectiveModule has finished successfully.
7639   } else if (Option == "nooddspreg") {
7640     if (!isABI_O32()) {
7641       return Error(L, "'.module nooddspreg' requires the O32 ABI");
7642     }
7643 
7644     setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
7645 
7646     // Synchronize the abiflags information with the FeatureBits information we
7647     // changed above.
7648     getTargetStreamer().updateABIInfo(*this);
7649 
7650     // If printing assembly, use the recently updated abiflags information.
7651     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7652     // emitted at the end).
7653     getTargetStreamer().emitDirectiveModuleOddSPReg();
7654 
7655     // If this is not the end of the statement, report an error.
7656     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7657       reportParseError("unexpected token, expected end of statement");
7658       return false;
7659     }
7660 
7661     return false; // parseDirectiveModule has finished successfully.
7662   } else if (Option == "fp") {
7663     return parseDirectiveModuleFP();
7664   } else if (Option == "softfloat") {
7665     setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
7666 
7667     // Synchronize the ABI Flags information with the FeatureBits information we
7668     // updated above.
7669     getTargetStreamer().updateABIInfo(*this);
7670 
7671     // If printing assembly, use the recently updated ABI Flags information.
7672     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7673     // emitted later).
7674     getTargetStreamer().emitDirectiveModuleSoftFloat();
7675 
7676     // If this is not the end of the statement, report an error.
7677     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7678       reportParseError("unexpected token, expected end of statement");
7679       return false;
7680     }
7681 
7682     return false; // parseDirectiveModule has finished successfully.
7683   } else if (Option == "hardfloat") {
7684     clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
7685 
7686     // Synchronize the ABI Flags information with the FeatureBits information we
7687     // updated above.
7688     getTargetStreamer().updateABIInfo(*this);
7689 
7690     // If printing assembly, use the recently updated ABI Flags information.
7691     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7692     // emitted later).
7693     getTargetStreamer().emitDirectiveModuleHardFloat();
7694 
7695     // If this is not the end of the statement, report an error.
7696     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7697       reportParseError("unexpected token, expected end of statement");
7698       return false;
7699     }
7700 
7701     return false; // parseDirectiveModule has finished successfully.
7702   } else if (Option == "mt") {
7703     setModuleFeatureBits(Mips::FeatureMT, "mt");
7704 
7705     // Synchronize the ABI Flags information with the FeatureBits information we
7706     // updated above.
7707     getTargetStreamer().updateABIInfo(*this);
7708 
7709     // If printing assembly, use the recently updated ABI Flags information.
7710     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7711     // emitted later).
7712     getTargetStreamer().emitDirectiveModuleMT();
7713 
7714     // If this is not the end of the statement, report an error.
7715     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7716       reportParseError("unexpected token, expected end of statement");
7717       return false;
7718     }
7719 
7720     return false; // parseDirectiveModule has finished successfully.
7721   } else if (Option == "crc") {
7722     setModuleFeatureBits(Mips::FeatureCRC, "crc");
7723 
7724     // Synchronize the ABI Flags information with the FeatureBits information we
7725     // updated above.
7726     getTargetStreamer().updateABIInfo(*this);
7727 
7728     // If printing assembly, use the recently updated ABI Flags information.
7729     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7730     // emitted later).
7731     getTargetStreamer().emitDirectiveModuleCRC();
7732 
7733     // If this is not the end of the statement, report an error.
7734     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7735       reportParseError("unexpected token, expected end of statement");
7736       return false;
7737     }
7738 
7739     return false; // parseDirectiveModule has finished successfully.
7740   } else if (Option == "nocrc") {
7741     clearModuleFeatureBits(Mips::FeatureCRC, "crc");
7742 
7743     // Synchronize the ABI Flags information with the FeatureBits information we
7744     // updated above.
7745     getTargetStreamer().updateABIInfo(*this);
7746 
7747     // If printing assembly, use the recently updated ABI Flags information.
7748     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7749     // emitted later).
7750     getTargetStreamer().emitDirectiveModuleNoCRC();
7751 
7752     // If this is not the end of the statement, report an error.
7753     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7754       reportParseError("unexpected token, expected end of statement");
7755       return false;
7756     }
7757 
7758     return false; // parseDirectiveModule has finished successfully.
7759   } else if (Option == "virt") {
7760     setModuleFeatureBits(Mips::FeatureVirt, "virt");
7761 
7762     // Synchronize the ABI Flags information with the FeatureBits information we
7763     // updated above.
7764     getTargetStreamer().updateABIInfo(*this);
7765 
7766     // If printing assembly, use the recently updated ABI Flags information.
7767     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7768     // emitted later).
7769     getTargetStreamer().emitDirectiveModuleVirt();
7770 
7771     // If this is not the end of the statement, report an error.
7772     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7773       reportParseError("unexpected token, expected end of statement");
7774       return false;
7775     }
7776 
7777     return false; // parseDirectiveModule has finished successfully.
7778   } else if (Option == "novirt") {
7779     clearModuleFeatureBits(Mips::FeatureVirt, "virt");
7780 
7781     // Synchronize the ABI Flags information with the FeatureBits information we
7782     // updated above.
7783     getTargetStreamer().updateABIInfo(*this);
7784 
7785     // If printing assembly, use the recently updated ABI Flags information.
7786     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7787     // emitted later).
7788     getTargetStreamer().emitDirectiveModuleNoVirt();
7789 
7790     // If this is not the end of the statement, report an error.
7791     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7792       reportParseError("unexpected token, expected end of statement");
7793       return false;
7794     }
7795 
7796     return false; // parseDirectiveModule has finished successfully.
7797   } else if (Option == "ginv") {
7798     setModuleFeatureBits(Mips::FeatureGINV, "ginv");
7799 
7800     // Synchronize the ABI Flags information with the FeatureBits information we
7801     // updated above.
7802     getTargetStreamer().updateABIInfo(*this);
7803 
7804     // If printing assembly, use the recently updated ABI Flags information.
7805     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7806     // emitted later).
7807     getTargetStreamer().emitDirectiveModuleGINV();
7808 
7809     // If this is not the end of the statement, report an error.
7810     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7811       reportParseError("unexpected token, expected end of statement");
7812       return false;
7813     }
7814 
7815     return false; // parseDirectiveModule has finished successfully.
7816   } else if (Option == "noginv") {
7817     clearModuleFeatureBits(Mips::FeatureGINV, "ginv");
7818 
7819     // Synchronize the ABI Flags information with the FeatureBits information we
7820     // updated above.
7821     getTargetStreamer().updateABIInfo(*this);
7822 
7823     // If printing assembly, use the recently updated ABI Flags information.
7824     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7825     // emitted later).
7826     getTargetStreamer().emitDirectiveModuleNoGINV();
7827 
7828     // If this is not the end of the statement, report an error.
7829     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7830       reportParseError("unexpected token, expected end of statement");
7831       return false;
7832     }
7833 
7834     return false; // parseDirectiveModule has finished successfully.
7835   } else {
7836     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
7837   }
7838 }
7839 
7840 /// parseDirectiveModuleFP
7841 ///  ::= =32
7842 ///  ::= =xx
7843 ///  ::= =64
7844 bool MipsAsmParser::parseDirectiveModuleFP() {
7845   MCAsmParser &Parser = getParser();
7846   MCAsmLexer &Lexer = getLexer();
7847 
7848   if (Lexer.isNot(AsmToken::Equal)) {
7849     reportParseError("unexpected token, expected equals sign '='");
7850     return false;
7851   }
7852   Parser.Lex(); // Eat '=' token.
7853 
7854   MipsABIFlagsSection::FpABIKind FpABI;
7855   if (!parseFpABIValue(FpABI, ".module"))
7856     return false;
7857 
7858   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7859     reportParseError("unexpected token, expected end of statement");
7860     return false;
7861   }
7862 
7863   // Synchronize the abiflags information with the FeatureBits information we
7864   // changed above.
7865   getTargetStreamer().updateABIInfo(*this);
7866 
7867   // If printing assembly, use the recently updated abiflags information.
7868   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7869   // emitted at the end).
7870   getTargetStreamer().emitDirectiveModuleFP();
7871 
7872   Parser.Lex(); // Consume the EndOfStatement.
7873   return false;
7874 }
7875 
7876 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
7877                                     StringRef Directive) {
7878   MCAsmParser &Parser = getParser();
7879   MCAsmLexer &Lexer = getLexer();
7880   bool ModuleLevelOptions = Directive == ".module";
7881 
7882   if (Lexer.is(AsmToken::Identifier)) {
7883     StringRef Value = Parser.getTok().getString();
7884     Parser.Lex();
7885 
7886     if (Value != "xx") {
7887       reportParseError("unsupported value, expected 'xx', '32' or '64'");
7888       return false;
7889     }
7890 
7891     if (!isABI_O32()) {
7892       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
7893       return false;
7894     }
7895 
7896     FpABI = MipsABIFlagsSection::FpABIKind::XX;
7897     if (ModuleLevelOptions) {
7898       setModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
7899       clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
7900     } else {
7901       setFeatureBits(Mips::FeatureFPXX, "fpxx");
7902       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
7903     }
7904     return true;
7905   }
7906 
7907   if (Lexer.is(AsmToken::Integer)) {
7908     unsigned Value = Parser.getTok().getIntVal();
7909     Parser.Lex();
7910 
7911     if (Value != 32 && Value != 64) {
7912       reportParseError("unsupported value, expected 'xx', '32' or '64'");
7913       return false;
7914     }
7915 
7916     if (Value == 32) {
7917       if (!isABI_O32()) {
7918         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
7919         return false;
7920       }
7921 
7922       FpABI = MipsABIFlagsSection::FpABIKind::S32;
7923       if (ModuleLevelOptions) {
7924         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
7925         clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
7926       } else {
7927         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
7928         clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
7929       }
7930     } else {
7931       FpABI = MipsABIFlagsSection::FpABIKind::S64;
7932       if (ModuleLevelOptions) {
7933         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
7934         setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
7935       } else {
7936         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
7937         setFeatureBits(Mips::FeatureFP64Bit, "fp64");
7938       }
7939     }
7940 
7941     return true;
7942   }
7943 
7944   return false;
7945 }
7946 
7947 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
7948   // This returns false if this function recognizes the directive
7949   // regardless of whether it is successfully handles or reports an
7950   // error. Otherwise it returns true to give the generic parser a
7951   // chance at recognizing it.
7952 
7953   MCAsmParser &Parser = getParser();
7954   StringRef IDVal = DirectiveID.getString();
7955 
7956   if (IDVal == ".cpload") {
7957     parseDirectiveCpLoad(DirectiveID.getLoc());
7958     return false;
7959   }
7960   if (IDVal == ".cprestore") {
7961     parseDirectiveCpRestore(DirectiveID.getLoc());
7962     return false;
7963   }
7964   if (IDVal == ".dword") {
7965     parseDataDirective(8, DirectiveID.getLoc());
7966     return false;
7967   }
7968   if (IDVal == ".ent") {
7969     StringRef SymbolName;
7970 
7971     if (Parser.parseIdentifier(SymbolName)) {
7972       reportParseError("expected identifier after .ent");
7973       return false;
7974     }
7975 
7976     // There's an undocumented extension that allows an integer to
7977     // follow the name of the procedure which AFAICS is ignored by GAS.
7978     // Example: .ent foo,2
7979     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7980       if (getLexer().isNot(AsmToken::Comma)) {
7981         // Even though we accept this undocumented extension for compatibility
7982         // reasons, the additional integer argument does not actually change
7983         // the behaviour of the '.ent' directive, so we would like to discourage
7984         // its use. We do this by not referring to the extended version in
7985         // error messages which are not directly related to its use.
7986         reportParseError("unexpected token, expected end of statement");
7987         return false;
7988       }
7989       Parser.Lex(); // Eat the comma.
7990       const MCExpr *DummyNumber;
7991       int64_t DummyNumberVal;
7992       // If the user was explicitly trying to use the extended version,
7993       // we still give helpful extension-related error messages.
7994       if (Parser.parseExpression(DummyNumber)) {
7995         reportParseError("expected number after comma");
7996         return false;
7997       }
7998       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
7999         reportParseError("expected an absolute expression after comma");
8000         return false;
8001       }
8002     }
8003 
8004     // If this is not the end of the statement, report an error.
8005     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8006       reportParseError("unexpected token, expected end of statement");
8007       return false;
8008     }
8009 
8010     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
8011 
8012     getTargetStreamer().emitDirectiveEnt(*Sym);
8013     CurrentFn = Sym;
8014     IsCpRestoreSet = false;
8015     return false;
8016   }
8017 
8018   if (IDVal == ".end") {
8019     StringRef SymbolName;
8020 
8021     if (Parser.parseIdentifier(SymbolName)) {
8022       reportParseError("expected identifier after .end");
8023       return false;
8024     }
8025 
8026     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8027       reportParseError("unexpected token, expected end of statement");
8028       return false;
8029     }
8030 
8031     if (CurrentFn == nullptr) {
8032       reportParseError(".end used without .ent");
8033       return false;
8034     }
8035 
8036     if ((SymbolName != CurrentFn->getName())) {
8037       reportParseError(".end symbol does not match .ent symbol");
8038       return false;
8039     }
8040 
8041     getTargetStreamer().emitDirectiveEnd(SymbolName);
8042     CurrentFn = nullptr;
8043     IsCpRestoreSet = false;
8044     return false;
8045   }
8046 
8047   if (IDVal == ".frame") {
8048     // .frame $stack_reg, frame_size_in_bytes, $return_reg
8049     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
8050     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
8051     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
8052       reportParseError("expected stack register");
8053       return false;
8054     }
8055 
8056     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
8057     if (!StackRegOpnd.isGPRAsmReg()) {
8058       reportParseError(StackRegOpnd.getStartLoc(),
8059                        "expected general purpose register");
8060       return false;
8061     }
8062     unsigned StackReg = StackRegOpnd.getGPR32Reg();
8063 
8064     if (Parser.getTok().is(AsmToken::Comma))
8065       Parser.Lex();
8066     else {
8067       reportParseError("unexpected token, expected comma");
8068       return false;
8069     }
8070 
8071     // Parse the frame size.
8072     const MCExpr *FrameSize;
8073     int64_t FrameSizeVal;
8074 
8075     if (Parser.parseExpression(FrameSize)) {
8076       reportParseError("expected frame size value");
8077       return false;
8078     }
8079 
8080     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
8081       reportParseError("frame size not an absolute expression");
8082       return false;
8083     }
8084 
8085     if (Parser.getTok().is(AsmToken::Comma))
8086       Parser.Lex();
8087     else {
8088       reportParseError("unexpected token, expected comma");
8089       return false;
8090     }
8091 
8092     // Parse the return register.
8093     TmpReg.clear();
8094     ResTy = parseAnyRegister(TmpReg);
8095     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
8096       reportParseError("expected return register");
8097       return false;
8098     }
8099 
8100     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
8101     if (!ReturnRegOpnd.isGPRAsmReg()) {
8102       reportParseError(ReturnRegOpnd.getStartLoc(),
8103                        "expected general purpose register");
8104       return false;
8105     }
8106 
8107     // If this is not the end of the statement, report an error.
8108     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8109       reportParseError("unexpected token, expected end of statement");
8110       return false;
8111     }
8112 
8113     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
8114                                   ReturnRegOpnd.getGPR32Reg());
8115     IsCpRestoreSet = false;
8116     return false;
8117   }
8118 
8119   if (IDVal == ".set") {
8120     parseDirectiveSet();
8121     return false;
8122   }
8123 
8124   if (IDVal == ".mask" || IDVal == ".fmask") {
8125     // .mask bitmask, frame_offset
8126     // bitmask: One bit for each register used.
8127     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
8128     //               first register is expected to be saved.
8129     // Examples:
8130     //   .mask 0x80000000, -4
8131     //   .fmask 0x80000000, -4
8132     //
8133 
8134     // Parse the bitmask
8135     const MCExpr *BitMask;
8136     int64_t BitMaskVal;
8137 
8138     if (Parser.parseExpression(BitMask)) {
8139       reportParseError("expected bitmask value");
8140       return false;
8141     }
8142 
8143     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
8144       reportParseError("bitmask not an absolute expression");
8145       return false;
8146     }
8147 
8148     if (Parser.getTok().is(AsmToken::Comma))
8149       Parser.Lex();
8150     else {
8151       reportParseError("unexpected token, expected comma");
8152       return false;
8153     }
8154 
8155     // Parse the frame_offset
8156     const MCExpr *FrameOffset;
8157     int64_t FrameOffsetVal;
8158 
8159     if (Parser.parseExpression(FrameOffset)) {
8160       reportParseError("expected frame offset value");
8161       return false;
8162     }
8163 
8164     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
8165       reportParseError("frame offset not an absolute expression");
8166       return false;
8167     }
8168 
8169     // If this is not the end of the statement, report an error.
8170     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8171       reportParseError("unexpected token, expected end of statement");
8172       return false;
8173     }
8174 
8175     if (IDVal == ".mask")
8176       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
8177     else
8178       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
8179     return false;
8180   }
8181 
8182   if (IDVal == ".nan")
8183     return parseDirectiveNaN();
8184 
8185   if (IDVal == ".gpword") {
8186     parseDirectiveGpWord();
8187     return false;
8188   }
8189 
8190   if (IDVal == ".gpdword") {
8191     parseDirectiveGpDWord();
8192     return false;
8193   }
8194 
8195   if (IDVal == ".dtprelword") {
8196     parseDirectiveDtpRelWord();
8197     return false;
8198   }
8199 
8200   if (IDVal == ".dtpreldword") {
8201     parseDirectiveDtpRelDWord();
8202     return false;
8203   }
8204 
8205   if (IDVal == ".tprelword") {
8206     parseDirectiveTpRelWord();
8207     return false;
8208   }
8209 
8210   if (IDVal == ".tpreldword") {
8211     parseDirectiveTpRelDWord();
8212     return false;
8213   }
8214 
8215   if (IDVal == ".word") {
8216     parseDataDirective(4, DirectiveID.getLoc());
8217     return false;
8218   }
8219 
8220   if (IDVal == ".hword") {
8221     parseDataDirective(2, DirectiveID.getLoc());
8222     return false;
8223   }
8224 
8225   if (IDVal == ".option") {
8226     parseDirectiveOption();
8227     return false;
8228   }
8229 
8230   if (IDVal == ".abicalls") {
8231     getTargetStreamer().emitDirectiveAbiCalls();
8232     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8233       Error(Parser.getTok().getLoc(),
8234             "unexpected token, expected end of statement");
8235     }
8236     return false;
8237   }
8238 
8239   if (IDVal == ".cpsetup") {
8240     parseDirectiveCPSetup();
8241     return false;
8242   }
8243   if (IDVal == ".cpreturn") {
8244     parseDirectiveCPReturn();
8245     return false;
8246   }
8247   if (IDVal == ".module") {
8248     parseDirectiveModule();
8249     return false;
8250   }
8251   if (IDVal == ".llvm_internal_mips_reallow_module_directive") {
8252     parseInternalDirectiveReallowModule();
8253     return false;
8254   }
8255   if (IDVal == ".insn") {
8256     parseInsnDirective();
8257     return false;
8258   }
8259   if (IDVal == ".rdata") {
8260     parseRSectionDirective(".rodata");
8261     return false;
8262   }
8263   if (IDVal == ".sbss") {
8264     parseSSectionDirective(IDVal, ELF::SHT_NOBITS);
8265     return false;
8266   }
8267   if (IDVal == ".sdata") {
8268     parseSSectionDirective(IDVal, ELF::SHT_PROGBITS);
8269     return false;
8270   }
8271 
8272   return true;
8273 }
8274 
8275 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
8276   // If this is not the end of the statement, report an error.
8277   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8278     reportParseError("unexpected token, expected end of statement");
8279     return false;
8280   }
8281 
8282   getTargetStreamer().reallowModuleDirective();
8283 
8284   getParser().Lex(); // Eat EndOfStatement token.
8285   return false;
8286 }
8287 
8288 extern "C" void LLVMInitializeMipsAsmParser() {
8289   RegisterMCAsmParser<MipsAsmParser> X(getTheMipsTarget());
8290   RegisterMCAsmParser<MipsAsmParser> Y(getTheMipselTarget());
8291   RegisterMCAsmParser<MipsAsmParser> A(getTheMips64Target());
8292   RegisterMCAsmParser<MipsAsmParser> B(getTheMips64elTarget());
8293 }
8294 
8295 #define GET_REGISTER_MATCHER
8296 #define GET_MATCHER_IMPLEMENTATION
8297 #include "MipsGenAsmMatcher.inc"
8298 
8299 bool MipsAsmParser::mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {
8300   // Find the appropriate table for this asm variant.
8301   const MatchEntry *Start, *End;
8302   switch (VariantID) {
8303   default: llvm_unreachable("invalid variant!");
8304   case 0: Start = std::begin(MatchTable0); End = std::end(MatchTable0); break;
8305   }
8306   // Search the table.
8307   auto MnemonicRange = std::equal_range(Start, End, Mnemonic, LessOpcode());
8308   return MnemonicRange.first != MnemonicRange.second;
8309 }
8310