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