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