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