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