1 //===-- MipsAsmParser.cpp - Parse Mips assembly to MCInst instructions ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MCTargetDesc/MipsABIInfo.h"
11 #include "MCTargetDesc/MipsMCExpr.h"
12 #include "MCTargetDesc/MipsMCTargetDesc.h"
13 #include "MipsRegisterInfo.h"
14 #include "MipsTargetObjectFile.h"
15 #include "MipsTargetStreamer.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstBuilder.h"
22 #include "llvm/MC/MCParser/MCAsmLexer.h"
23 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
24 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <memory>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "mips-asm-parser"
40 
41 namespace llvm {
42 class MCInstrInfo;
43 }
44 
45 namespace {
46 class MipsAssemblerOptions {
47 public:
48   MipsAssemblerOptions(const FeatureBitset &Features_) :
49     ATReg(1), Reorder(true), Macro(true), Features(Features_) {}
50 
51   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
52     ATReg = Opts->getATRegIndex();
53     Reorder = Opts->isReorder();
54     Macro = Opts->isMacro();
55     Features = Opts->getFeatures();
56   }
57 
58   unsigned getATRegIndex() const { return ATReg; }
59   bool setATRegIndex(unsigned Reg) {
60     if (Reg > 31)
61       return false;
62 
63     ATReg = Reg;
64     return true;
65   }
66 
67   bool isReorder() const { return Reorder; }
68   void setReorder() { Reorder = true; }
69   void setNoReorder() { Reorder = false; }
70 
71   bool isMacro() const { return Macro; }
72   void setMacro() { Macro = true; }
73   void setNoMacro() { Macro = false; }
74 
75   const FeatureBitset &getFeatures() const { return Features; }
76   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
77 
78   // Set of features that are either architecture features or referenced
79   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
80   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
81   // The reason we need this mask is explained in the selectArch function.
82   // FIXME: Ideally we would like TableGen to generate this information.
83   static const FeatureBitset AllArchRelatedMask;
84 
85 private:
86   unsigned ATReg;
87   bool Reorder;
88   bool Macro;
89   FeatureBitset Features;
90 };
91 }
92 
93 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
94     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
95     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
96     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
97     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
98     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
99     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
100     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
101     Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008
102 };
103 
104 namespace {
105 class MipsAsmParser : public MCTargetAsmParser {
106   MipsTargetStreamer &getTargetStreamer() {
107     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
108     return static_cast<MipsTargetStreamer &>(TS);
109   }
110 
111   MipsABIInfo ABI;
112   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
113   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
114                        // nullptr, which indicates that no function is currently
115                        // selected. This usually happens after an '.end func'
116                        // directive.
117   bool IsLittleEndian;
118   bool IsPicEnabled;
119   bool IsCpRestoreSet;
120   int CpRestoreOffset;
121   unsigned CpSaveLocation;
122   /// If true, then CpSaveLocation is a register, otherwise it's an offset.
123   bool     CpSaveLocationIsRegister;
124 
125   // Print a warning along with its fix-it message at the given range.
126   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
127                              SMRange Range, bool ShowColors = true);
128 
129 #define GET_ASSEMBLER_HEADER
130 #include "MipsGenAsmMatcher.inc"
131 
132   unsigned
133   checkEarlyTargetMatchPredicate(MCInst &Inst,
134                                  const OperandVector &Operands) override;
135   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
136 
137   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
138                                OperandVector &Operands, MCStreamer &Out,
139                                uint64_t &ErrorInfo,
140                                bool MatchingInlineAsm) override;
141 
142   /// Parse a register as used in CFI directives
143   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
144 
145   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
146 
147   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
148 
149   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
150                         SMLoc NameLoc, OperandVector &Operands) override;
151 
152   bool ParseDirective(AsmToken DirectiveID) override;
153 
154   OperandMatchResultTy parseMemOperand(OperandVector &Operands);
155   OperandMatchResultTy
156   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
157                                     StringRef Identifier, SMLoc S);
158   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
159                                                      SMLoc S);
160   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
161   OperandMatchResultTy parseImm(OperandVector &Operands);
162   OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
163   OperandMatchResultTy parseInvNum(OperandVector &Operands);
164   OperandMatchResultTy parseRegisterPair(OperandVector &Operands);
165   OperandMatchResultTy parseMovePRegPair(OperandVector &Operands);
166   OperandMatchResultTy parseRegisterList(OperandVector &Operands);
167 
168   bool searchSymbolAlias(OperandVector &Operands);
169 
170   bool parseOperand(OperandVector &, StringRef Mnemonic);
171 
172   enum MacroExpanderResultTy {
173     MER_NotAMacro,
174     MER_Success,
175     MER_Fail,
176   };
177 
178   // Expands assembly pseudo instructions.
179   MacroExpanderResultTy tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
180                                              MCStreamer &Out,
181                                              const MCSubtargetInfo *STI);
182 
183   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
184                          const MCSubtargetInfo *STI);
185 
186   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
187                      bool Is32BitImm, bool IsAddress, SMLoc IDLoc,
188                      MCStreamer &Out, const MCSubtargetInfo *STI);
189 
190   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
191                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
192                                MCStreamer &Out, const MCSubtargetInfo *STI);
193 
194   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
195                      MCStreamer &Out, const MCSubtargetInfo *STI);
196 
197   bool expandLoadAddress(unsigned DstReg, unsigned BaseReg,
198                          const MCOperand &Offset, bool Is32BitAddress,
199                          SMLoc IDLoc, MCStreamer &Out,
200                          const MCSubtargetInfo *STI);
201 
202   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
203                                   const MCSubtargetInfo *STI);
204 
205   void expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
206                      const MCSubtargetInfo *STI, bool IsLoad, bool IsImmOpnd);
207 
208   void expandLoadInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
209                       const MCSubtargetInfo *STI, bool IsImmOpnd);
210 
211   void expandStoreInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
212                        const MCSubtargetInfo *STI, bool IsImmOpnd);
213 
214   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
215                                const MCSubtargetInfo *STI);
216 
217   bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
218                             const MCSubtargetInfo *STI);
219 
220   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
221                        const MCSubtargetInfo *STI);
222 
223   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
224                           const MCSubtargetInfo *STI);
225 
226   bool expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
227                  const MCSubtargetInfo *STI, const bool IsMips64,
228                  const bool Signed);
229 
230   bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc,
231                    MCStreamer &Out, const MCSubtargetInfo *STI);
232 
233   bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out,
234                  const MCSubtargetInfo *STI);
235 
236   bool expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
237                  const MCSubtargetInfo *STI);
238 
239   bool expandRotation(MCInst &Inst, SMLoc IDLoc,
240                       MCStreamer &Out, const MCSubtargetInfo *STI);
241   bool expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
242                          const MCSubtargetInfo *STI);
243   bool expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
244                        const MCSubtargetInfo *STI);
245   bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
246                           const MCSubtargetInfo *STI);
247 
248   bool expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
249                  const MCSubtargetInfo *STI);
250 
251   bool reportParseError(Twine ErrorMsg);
252   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
253 
254   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
255 
256   bool isEvaluated(const MCExpr *Expr);
257   bool parseSetMips0Directive();
258   bool parseSetArchDirective();
259   bool parseSetFeature(uint64_t Feature);
260   bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup.
261   bool parseDirectiveCpLoad(SMLoc Loc);
262   bool parseDirectiveCpRestore(SMLoc Loc);
263   bool parseDirectiveCPSetup();
264   bool parseDirectiveCPReturn();
265   bool parseDirectiveNaN();
266   bool parseDirectiveSet();
267   bool parseDirectiveOption();
268   bool parseInsnDirective();
269   bool parseSSectionDirective(StringRef Section, unsigned Type);
270 
271   bool parseSetAtDirective();
272   bool parseSetNoAtDirective();
273   bool parseSetMacroDirective();
274   bool parseSetNoMacroDirective();
275   bool parseSetMsaDirective();
276   bool parseSetNoMsaDirective();
277   bool parseSetNoDspDirective();
278   bool parseSetReorderDirective();
279   bool parseSetNoReorderDirective();
280   bool parseSetMips16Directive();
281   bool parseSetNoMips16Directive();
282   bool parseSetFpDirective();
283   bool parseSetOddSPRegDirective();
284   bool parseSetNoOddSPRegDirective();
285   bool parseSetPopDirective();
286   bool parseSetPushDirective();
287   bool parseSetSoftFloatDirective();
288   bool parseSetHardFloatDirective();
289 
290   bool parseSetAssignment();
291 
292   bool parseDataDirective(unsigned Size, SMLoc L);
293   bool parseDirectiveGpWord();
294   bool parseDirectiveGpDWord();
295   bool parseDirectiveModule();
296   bool parseDirectiveModuleFP();
297   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
298                        StringRef Directive);
299 
300   bool parseInternalDirectiveReallowModule();
301 
302   bool eatComma(StringRef ErrorStr);
303 
304   int matchCPURegisterName(StringRef Symbol);
305 
306   int matchHWRegsRegisterName(StringRef Symbol);
307 
308   int matchFPURegisterName(StringRef Name);
309 
310   int matchFCCRegisterName(StringRef Name);
311 
312   int matchACRegisterName(StringRef Name);
313 
314   int matchMSA128RegisterName(StringRef Name);
315 
316   int matchMSA128CtrlRegisterName(StringRef Name);
317 
318   unsigned getReg(int RC, int RegNo);
319 
320   /// Returns the internal register number for the current AT. Also checks if
321   /// the current AT is unavailable (set to $0) and gives an error if it is.
322   /// This should be used in pseudo-instruction expansions which need AT.
323   unsigned getATReg(SMLoc Loc);
324 
325   bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
326                           const MCSubtargetInfo *STI);
327 
328   // Helper function that checks if the value of a vector index is within the
329   // boundaries of accepted values for each RegisterKind
330   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
331   bool validateMSAIndex(int Val, int RegKind);
332 
333   // Selects a new architecture by updating the FeatureBits with the necessary
334   // info including implied dependencies.
335   // Internally, it clears all the feature bits related to *any* architecture
336   // and selects the new one using the ToggleFeature functionality of the
337   // MCSubtargetInfo object that handles implied dependencies. The reason we
338   // clear all the arch related bits manually is because ToggleFeature only
339   // clears the features that imply the feature being cleared and not the
340   // features implied by the feature being cleared. This is easier to see
341   // with an example:
342   //  --------------------------------------------------
343   // | Feature         | Implies                        |
344   // | -------------------------------------------------|
345   // | FeatureMips1    | None                           |
346   // | FeatureMips2    | FeatureMips1                   |
347   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
348   // | FeatureMips4    | FeatureMips3                   |
349   // | ...             |                                |
350   //  --------------------------------------------------
351   //
352   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
353   // FeatureMipsGP64 | FeatureMips1)
354   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
355   void selectArch(StringRef ArchFeature) {
356     MCSubtargetInfo &STI = copySTI();
357     FeatureBitset FeatureBits = STI.getFeatureBits();
358     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
359     STI.setFeatureBits(FeatureBits);
360     setAvailableFeatures(
361         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
362     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
363   }
364 
365   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
366     if (!(getSTI().getFeatureBits()[Feature])) {
367       MCSubtargetInfo &STI = copySTI();
368       setAvailableFeatures(
369           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
370       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
371     }
372   }
373 
374   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
375     if (getSTI().getFeatureBits()[Feature]) {
376       MCSubtargetInfo &STI = copySTI();
377       setAvailableFeatures(
378           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
379       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
380     }
381   }
382 
383   void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
384     setFeatureBits(Feature, FeatureString);
385     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
386   }
387 
388   void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
389     clearFeatureBits(Feature, FeatureString);
390     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
391   }
392 
393 public:
394   enum MipsMatchResultTy {
395     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY,
396     Match_RequiresDifferentOperands,
397     Match_RequiresNoZeroRegister,
398     Match_RequiresSameSrcAndDst,
399 #define GET_OPERAND_DIAGNOSTIC_TYPES
400 #include "MipsGenAsmMatcher.inc"
401 #undef GET_OPERAND_DIAGNOSTIC_TYPES
402   };
403 
404   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
405                 const MCInstrInfo &MII, const MCTargetOptions &Options)
406     : MCTargetAsmParser(Options, sti),
407         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
408                                           sti.getCPU(), Options)) {
409     MCAsmParserExtension::Initialize(parser);
410 
411     parser.addAliasForDirective(".asciiz", ".asciz");
412 
413     // Initialize the set of available features.
414     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
415 
416     // Remember the initial assembler options. The user can not modify these.
417     AssemblerOptions.push_back(
418         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
419 
420     // Create an assembler options environment for the user to modify.
421     AssemblerOptions.push_back(
422         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
423 
424     getTargetStreamer().updateABIInfo(*this);
425 
426     if (!isABI_O32() && !useOddSPReg() != 0)
427       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
428 
429     CurrentFn = nullptr;
430 
431     IsPicEnabled = getContext().getObjectFileInfo()->isPositionIndependent();
432 
433     IsCpRestoreSet = false;
434     CpRestoreOffset = -1;
435 
436     const Triple &TheTriple = sti.getTargetTriple();
437     if ((TheTriple.getArch() == Triple::mips) ||
438         (TheTriple.getArch() == Triple::mips64))
439       IsLittleEndian = false;
440     else
441       IsLittleEndian = true;
442   }
443 
444   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
445   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
446 
447   bool isGP64bit() const {
448     return getSTI().getFeatureBits()[Mips::FeatureGP64Bit];
449   }
450   bool isFP64bit() const {
451     return getSTI().getFeatureBits()[Mips::FeatureFP64Bit];
452   }
453   const MipsABIInfo &getABI() const { return ABI; }
454   bool isABI_N32() const { return ABI.IsN32(); }
455   bool isABI_N64() const { return ABI.IsN64(); }
456   bool isABI_O32() const { return ABI.IsO32(); }
457   bool isABI_FPXX() const {
458     return getSTI().getFeatureBits()[Mips::FeatureFPXX];
459   }
460 
461   bool useOddSPReg() const {
462     return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]);
463   }
464 
465   bool inMicroMipsMode() const {
466     return getSTI().getFeatureBits()[Mips::FeatureMicroMips];
467   }
468   bool hasMips1() const {
469     return getSTI().getFeatureBits()[Mips::FeatureMips1];
470   }
471   bool hasMips2() const {
472     return getSTI().getFeatureBits()[Mips::FeatureMips2];
473   }
474   bool hasMips3() const {
475     return getSTI().getFeatureBits()[Mips::FeatureMips3];
476   }
477   bool hasMips4() const {
478     return getSTI().getFeatureBits()[Mips::FeatureMips4];
479   }
480   bool hasMips5() const {
481     return getSTI().getFeatureBits()[Mips::FeatureMips5];
482   }
483   bool hasMips32() const {
484     return getSTI().getFeatureBits()[Mips::FeatureMips32];
485   }
486   bool hasMips64() const {
487     return getSTI().getFeatureBits()[Mips::FeatureMips64];
488   }
489   bool hasMips32r2() const {
490     return getSTI().getFeatureBits()[Mips::FeatureMips32r2];
491   }
492   bool hasMips64r2() const {
493     return getSTI().getFeatureBits()[Mips::FeatureMips64r2];
494   }
495   bool hasMips32r3() const {
496     return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]);
497   }
498   bool hasMips64r3() const {
499     return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]);
500   }
501   bool hasMips32r5() const {
502     return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]);
503   }
504   bool hasMips64r5() const {
505     return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]);
506   }
507   bool hasMips32r6() const {
508     return getSTI().getFeatureBits()[Mips::FeatureMips32r6];
509   }
510   bool hasMips64r6() const {
511     return getSTI().getFeatureBits()[Mips::FeatureMips64r6];
512   }
513 
514   bool hasDSP() const {
515     return getSTI().getFeatureBits()[Mips::FeatureDSP];
516   }
517   bool hasDSPR2() const {
518     return getSTI().getFeatureBits()[Mips::FeatureDSPR2];
519   }
520   bool hasDSPR3() const {
521     return getSTI().getFeatureBits()[Mips::FeatureDSPR3];
522   }
523   bool hasMSA() const {
524     return getSTI().getFeatureBits()[Mips::FeatureMSA];
525   }
526   bool hasCnMips() const {
527     return (getSTI().getFeatureBits()[Mips::FeatureCnMips]);
528   }
529 
530   bool inPicMode() {
531     return IsPicEnabled;
532   }
533 
534   bool inMips16Mode() const {
535     return getSTI().getFeatureBits()[Mips::FeatureMips16];
536   }
537 
538   bool useTraps() const {
539     return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV];
540   }
541 
542   bool useSoftFloat() const {
543     return getSTI().getFeatureBits()[Mips::FeatureSoftFloat];
544   }
545 
546   /// Warn if RegIndex is the same as the current AT.
547   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
548 
549   void warnIfNoMacro(SMLoc Loc);
550 
551   bool isLittle() const { return IsLittleEndian; }
552 
553   const MCExpr *createTargetUnaryExpr(const MCExpr *E,
554                                       AsmToken::TokenKind OperatorToken,
555                                       MCContext &Ctx) override {
556     switch(OperatorToken) {
557     default:
558       llvm_unreachable("Unknown token");
559       return nullptr;
560     case AsmToken::PercentCall16:
561       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, E, Ctx);
562     case AsmToken::PercentCall_Hi:
563       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_HI16, E, Ctx);
564     case AsmToken::PercentCall_Lo:
565       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_LO16, E, Ctx);
566     case AsmToken::PercentDtprel_Hi:
567       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_HI, E, Ctx);
568     case AsmToken::PercentDtprel_Lo:
569       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_LO, E, Ctx);
570     case AsmToken::PercentGot:
571       return MipsMCExpr::create(MipsMCExpr::MEK_GOT, E, Ctx);
572     case AsmToken::PercentGot_Disp:
573       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, E, Ctx);
574     case AsmToken::PercentGot_Hi:
575       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_HI16, E, Ctx);
576     case AsmToken::PercentGot_Lo:
577       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_LO16, E, Ctx);
578     case AsmToken::PercentGot_Ofst:
579       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_OFST, E, Ctx);
580     case AsmToken::PercentGot_Page:
581       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_PAGE, E, Ctx);
582     case AsmToken::PercentGottprel:
583       return MipsMCExpr::create(MipsMCExpr::MEK_GOTTPREL, E, Ctx);
584     case AsmToken::PercentGp_Rel:
585       return MipsMCExpr::create(MipsMCExpr::MEK_GPREL, E, Ctx);
586     case AsmToken::PercentHi:
587       return MipsMCExpr::create(MipsMCExpr::MEK_HI, E, Ctx);
588     case AsmToken::PercentHigher:
589       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, E, Ctx);
590     case AsmToken::PercentHighest:
591       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, E, Ctx);
592     case AsmToken::PercentLo:
593       return MipsMCExpr::create(MipsMCExpr::MEK_LO, E, Ctx);
594     case AsmToken::PercentNeg:
595       return MipsMCExpr::create(MipsMCExpr::MEK_NEG, E, Ctx);
596     case AsmToken::PercentPcrel_Hi:
597       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_HI16, E, Ctx);
598     case AsmToken::PercentPcrel_Lo:
599       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_LO16, E, Ctx);
600     case AsmToken::PercentTlsgd:
601       return MipsMCExpr::create(MipsMCExpr::MEK_TLSGD, E, Ctx);
602     case AsmToken::PercentTlsldm:
603       return MipsMCExpr::create(MipsMCExpr::MEK_TLSLDM, E, Ctx);
604     case AsmToken::PercentTprel_Hi:
605       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_HI, E, Ctx);
606     case AsmToken::PercentTprel_Lo:
607       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_LO, E, Ctx);
608     }
609   }
610 };
611 }
612 
613 namespace {
614 
615 /// MipsOperand - Instances of this class represent a parsed Mips machine
616 /// instruction.
617 class MipsOperand : public MCParsedAsmOperand {
618 public:
619   /// Broad categories of register classes
620   /// The exact class is finalized by the render method.
621   enum RegKind {
622     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
623     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
624                           /// isFP64bit())
625     RegKind_FCC = 4,      /// FCC
626     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
627     RegKind_MSACtrl = 16, /// MSA control registers
628     RegKind_COP2 = 32,    /// COP2
629     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
630                           /// context).
631     RegKind_CCR = 128,    /// CCR
632     RegKind_HWRegs = 256, /// HWRegs
633     RegKind_COP3 = 512,   /// COP3
634     RegKind_COP0 = 1024,  /// COP0
635     /// Potentially any (e.g. $1)
636     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
637                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
638                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
639   };
640 
641 private:
642   enum KindTy {
643     k_Immediate,     /// An immediate (possibly involving symbol references)
644     k_Memory,        /// Base + Offset Memory Address
645     k_RegisterIndex, /// A register index in one or more RegKind.
646     k_Token,         /// A simple token
647     k_RegList,       /// A physical register list
648     k_RegPair        /// A pair of physical register
649   } Kind;
650 
651 public:
652   MipsOperand(KindTy K, MipsAsmParser &Parser)
653       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
654 
655 private:
656   /// For diagnostics, and checking the assembler temporary
657   MipsAsmParser &AsmParser;
658 
659   struct Token {
660     const char *Data;
661     unsigned Length;
662   };
663 
664   struct RegIdxOp {
665     unsigned Index; /// Index into the register class
666     RegKind Kind;   /// Bitfield of the kinds it could possibly be
667     struct Token Tok; /// The input token this operand originated from.
668     const MCRegisterInfo *RegInfo;
669   };
670 
671   struct ImmOp {
672     const MCExpr *Val;
673   };
674 
675   struct MemOp {
676     MipsOperand *Base;
677     const MCExpr *Off;
678   };
679 
680   struct RegListOp {
681     SmallVector<unsigned, 10> *List;
682   };
683 
684   union {
685     struct Token Tok;
686     struct RegIdxOp RegIdx;
687     struct ImmOp Imm;
688     struct MemOp Mem;
689     struct RegListOp RegList;
690   };
691 
692   SMLoc StartLoc, EndLoc;
693 
694   /// Internal constructor for register kinds
695   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, StringRef Str,
696                                                 RegKind RegKind,
697                                                 const MCRegisterInfo *RegInfo,
698                                                 SMLoc S, SMLoc E,
699                                                 MipsAsmParser &Parser) {
700     auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
701     Op->RegIdx.Index = Index;
702     Op->RegIdx.RegInfo = RegInfo;
703     Op->RegIdx.Kind = RegKind;
704     Op->RegIdx.Tok.Data = Str.data();
705     Op->RegIdx.Tok.Length = Str.size();
706     Op->StartLoc = S;
707     Op->EndLoc = E;
708     return Op;
709   }
710 
711 public:
712   /// Coerce the register to GPR32 and return the real register for the current
713   /// target.
714   unsigned getGPR32Reg() const {
715     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
716     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
717     unsigned ClassID = Mips::GPR32RegClassID;
718     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
719   }
720 
721   /// Coerce the register to GPR32 and return the real register for the current
722   /// target.
723   unsigned getGPRMM16Reg() const {
724     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
725     unsigned ClassID = Mips::GPR32RegClassID;
726     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
727   }
728 
729   /// Coerce the register to GPR64 and return the real register for the current
730   /// target.
731   unsigned getGPR64Reg() const {
732     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
733     unsigned ClassID = Mips::GPR64RegClassID;
734     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
735   }
736 
737 private:
738   /// Coerce the register to AFGR64 and return the real register for the current
739   /// target.
740   unsigned getAFGR64Reg() const {
741     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
742     if (RegIdx.Index % 2 != 0)
743       AsmParser.Warning(StartLoc, "Float register should be even.");
744     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
745         .getRegister(RegIdx.Index / 2);
746   }
747 
748   /// Coerce the register to FGR64 and return the real register for the current
749   /// target.
750   unsigned getFGR64Reg() const {
751     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
752     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
753         .getRegister(RegIdx.Index);
754   }
755 
756   /// Coerce the register to FGR32 and return the real register for the current
757   /// target.
758   unsigned getFGR32Reg() const {
759     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
760     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
761         .getRegister(RegIdx.Index);
762   }
763 
764   /// Coerce the register to FGRH32 and return the real register for the current
765   /// target.
766   unsigned getFGRH32Reg() const {
767     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
768     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
769         .getRegister(RegIdx.Index);
770   }
771 
772   /// Coerce the register to FCC and return the real register for the current
773   /// target.
774   unsigned getFCCReg() const {
775     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
776     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
777         .getRegister(RegIdx.Index);
778   }
779 
780   /// Coerce the register to MSA128 and return the real register for the current
781   /// target.
782   unsigned getMSA128Reg() const {
783     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
784     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
785     // identical
786     unsigned ClassID = Mips::MSA128BRegClassID;
787     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
788   }
789 
790   /// Coerce the register to MSACtrl and return the real register for the
791   /// current target.
792   unsigned getMSACtrlReg() const {
793     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
794     unsigned ClassID = Mips::MSACtrlRegClassID;
795     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
796   }
797 
798   /// Coerce the register to COP0 and return the real register for the
799   /// current target.
800   unsigned getCOP0Reg() const {
801     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
802     unsigned ClassID = Mips::COP0RegClassID;
803     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
804   }
805 
806   /// Coerce the register to COP2 and return the real register for the
807   /// current target.
808   unsigned getCOP2Reg() const {
809     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
810     unsigned ClassID = Mips::COP2RegClassID;
811     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
812   }
813 
814   /// Coerce the register to COP3 and return the real register for the
815   /// current target.
816   unsigned getCOP3Reg() const {
817     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
818     unsigned ClassID = Mips::COP3RegClassID;
819     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
820   }
821 
822   /// Coerce the register to ACC64DSP and return the real register for the
823   /// current target.
824   unsigned getACC64DSPReg() const {
825     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
826     unsigned ClassID = Mips::ACC64DSPRegClassID;
827     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
828   }
829 
830   /// Coerce the register to HI32DSP and return the real register for the
831   /// current target.
832   unsigned getHI32DSPReg() const {
833     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
834     unsigned ClassID = Mips::HI32DSPRegClassID;
835     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
836   }
837 
838   /// Coerce the register to LO32DSP and return the real register for the
839   /// current target.
840   unsigned getLO32DSPReg() const {
841     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
842     unsigned ClassID = Mips::LO32DSPRegClassID;
843     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
844   }
845 
846   /// Coerce the register to CCR and return the real register for the
847   /// current target.
848   unsigned getCCRReg() const {
849     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
850     unsigned ClassID = Mips::CCRRegClassID;
851     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
852   }
853 
854   /// Coerce the register to HWRegs and return the real register for the
855   /// current target.
856   unsigned getHWRegsReg() const {
857     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
858     unsigned ClassID = Mips::HWRegsRegClassID;
859     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
860   }
861 
862 public:
863   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
864     // Add as immediate when possible.  Null MCExpr = 0.
865     if (!Expr)
866       Inst.addOperand(MCOperand::createImm(0));
867     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
868       Inst.addOperand(MCOperand::createImm(CE->getValue()));
869     else
870       Inst.addOperand(MCOperand::createExpr(Expr));
871   }
872 
873   void addRegOperands(MCInst &Inst, unsigned N) const {
874     llvm_unreachable("Use a custom parser instead");
875   }
876 
877   /// Render the operand to an MCInst as a GPR32
878   /// Asserts if the wrong number of operands are requested, or the operand
879   /// is not a k_RegisterIndex compatible with RegKind_GPR
880   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
881     assert(N == 1 && "Invalid number of operands!");
882     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
883   }
884 
885   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
886     assert(N == 1 && "Invalid number of operands!");
887     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
888   }
889 
890   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
891     assert(N == 1 && "Invalid number of operands!");
892     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
893   }
894 
895   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
896     assert(N == 1 && "Invalid number of operands!");
897     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
898   }
899 
900   /// Render the operand to an MCInst as a GPR64
901   /// Asserts if the wrong number of operands are requested, or the operand
902   /// is not a k_RegisterIndex compatible with RegKind_GPR
903   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
904     assert(N == 1 && "Invalid number of operands!");
905     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
906   }
907 
908   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
909     assert(N == 1 && "Invalid number of operands!");
910     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
911   }
912 
913   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
914     assert(N == 1 && "Invalid number of operands!");
915     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
916   }
917 
918   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
919     assert(N == 1 && "Invalid number of operands!");
920     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
921     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
922     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
923       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
924                                 "registers");
925   }
926 
927   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
928     assert(N == 1 && "Invalid number of operands!");
929     Inst.addOperand(MCOperand::createReg(getFGRH32Reg()));
930   }
931 
932   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
933     assert(N == 1 && "Invalid number of operands!");
934     Inst.addOperand(MCOperand::createReg(getFCCReg()));
935   }
936 
937   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
938     assert(N == 1 && "Invalid number of operands!");
939     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
940   }
941 
942   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
943     assert(N == 1 && "Invalid number of operands!");
944     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
945   }
946 
947   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
948     assert(N == 1 && "Invalid number of operands!");
949     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
950   }
951 
952   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
953     assert(N == 1 && "Invalid number of operands!");
954     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
955   }
956 
957   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
958     assert(N == 1 && "Invalid number of operands!");
959     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
960   }
961 
962   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
963     assert(N == 1 && "Invalid number of operands!");
964     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
965   }
966 
967   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
968     assert(N == 1 && "Invalid number of operands!");
969     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
970   }
971 
972   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
973     assert(N == 1 && "Invalid number of operands!");
974     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
975   }
976 
977   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
978     assert(N == 1 && "Invalid number of operands!");
979     Inst.addOperand(MCOperand::createReg(getCCRReg()));
980   }
981 
982   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
983     assert(N == 1 && "Invalid number of operands!");
984     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
985   }
986 
987   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
988   void addConstantUImmOperands(MCInst &Inst, unsigned N) const {
989     assert(N == 1 && "Invalid number of operands!");
990     uint64_t Imm = getConstantImm() - Offset;
991     Imm &= (1 << Bits) - 1;
992     Imm += Offset;
993     Imm += AdjustOffset;
994     Inst.addOperand(MCOperand::createImm(Imm));
995   }
996 
997   template <unsigned Bits>
998   void addSImmOperands(MCInst &Inst, unsigned N) const {
999     if (isImm() && !isConstantImm()) {
1000       addExpr(Inst, getImm());
1001       return;
1002     }
1003     addConstantSImmOperands<Bits, 0, 0>(Inst, N);
1004   }
1005 
1006   template <unsigned Bits>
1007   void addUImmOperands(MCInst &Inst, unsigned N) const {
1008     if (isImm() && !isConstantImm()) {
1009       addExpr(Inst, getImm());
1010       return;
1011     }
1012     addConstantUImmOperands<Bits, 0, 0>(Inst, N);
1013   }
1014 
1015   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
1016   void addConstantSImmOperands(MCInst &Inst, unsigned N) const {
1017     assert(N == 1 && "Invalid number of operands!");
1018     int64_t Imm = getConstantImm() - Offset;
1019     Imm = SignExtend64<Bits>(Imm);
1020     Imm += Offset;
1021     Imm += AdjustOffset;
1022     Inst.addOperand(MCOperand::createImm(Imm));
1023   }
1024 
1025   void addImmOperands(MCInst &Inst, unsigned N) const {
1026     assert(N == 1 && "Invalid number of operands!");
1027     const MCExpr *Expr = getImm();
1028     addExpr(Inst, Expr);
1029   }
1030 
1031   void addMemOperands(MCInst &Inst, unsigned N) const {
1032     assert(N == 2 && "Invalid number of operands!");
1033 
1034     Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit()
1035                                              ? getMemBase()->getGPR64Reg()
1036                                              : getMemBase()->getGPR32Reg()));
1037 
1038     const MCExpr *Expr = getMemOff();
1039     addExpr(Inst, Expr);
1040   }
1041 
1042   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
1043     assert(N == 2 && "Invalid number of operands!");
1044 
1045     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
1046 
1047     const MCExpr *Expr = getMemOff();
1048     addExpr(Inst, Expr);
1049   }
1050 
1051   void addRegListOperands(MCInst &Inst, unsigned N) const {
1052     assert(N == 1 && "Invalid number of operands!");
1053 
1054     for (auto RegNo : getRegList())
1055       Inst.addOperand(MCOperand::createReg(RegNo));
1056   }
1057 
1058   void addRegPairOperands(MCInst &Inst, unsigned N) const {
1059     assert(N == 2 && "Invalid number of operands!");
1060     assert((RegIdx.Kind & RegKind_GPR) && "Invalid access!");
1061     unsigned RegNo = getRegPair();
1062     AsmParser.warnIfRegIndexIsAT(RegNo, StartLoc);
1063     Inst.addOperand(MCOperand::createReg(
1064       RegIdx.RegInfo->getRegClass(
1065         AsmParser.getABI().AreGprs64bit()
1066           ? Mips::GPR64RegClassID
1067           : Mips::GPR32RegClassID).getRegister(RegNo++)));
1068     Inst.addOperand(MCOperand::createReg(
1069       RegIdx.RegInfo->getRegClass(
1070         AsmParser.getABI().AreGprs64bit()
1071           ? Mips::GPR64RegClassID
1072           : Mips::GPR32RegClassID).getRegister(RegNo)));
1073   }
1074 
1075   void addMovePRegPairOperands(MCInst &Inst, unsigned N) const {
1076     assert(N == 2 && "Invalid number of operands!");
1077     for (auto RegNo : getRegList())
1078       Inst.addOperand(MCOperand::createReg(RegNo));
1079   }
1080 
1081   bool isReg() const override {
1082     // As a special case until we sort out the definition of div/divu, accept
1083     // $0/$zero here so that MCK_ZERO works correctly.
1084     return isGPRAsmReg() && RegIdx.Index == 0;
1085   }
1086   bool isRegIdx() const { return Kind == k_RegisterIndex; }
1087   bool isImm() const override { return Kind == k_Immediate; }
1088   bool isConstantImm() const {
1089     return isImm() && isa<MCConstantExpr>(getImm());
1090   }
1091   bool isConstantImmz() const {
1092     return isConstantImm() && getConstantImm() == 0;
1093   }
1094   template <unsigned Bits, int Offset = 0> bool isConstantUImm() const {
1095     return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset);
1096   }
1097   template <unsigned Bits> bool isSImm() const {
1098     return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm();
1099   }
1100   template <unsigned Bits> bool isUImm() const {
1101     return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm();
1102   }
1103   template <unsigned Bits> bool isAnyImm() const {
1104     return isConstantImm() ? (isInt<Bits>(getConstantImm()) ||
1105                               isUInt<Bits>(getConstantImm()))
1106                            : isImm();
1107   }
1108   template <unsigned Bits, int Offset = 0> bool isConstantSImm() const {
1109     return isConstantImm() && isInt<Bits>(getConstantImm() - Offset);
1110   }
1111   template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const {
1112     return isConstantImm() && getConstantImm() >= Bottom &&
1113            getConstantImm() <= Top;
1114   }
1115   bool isToken() const override {
1116     // Note: It's not possible to pretend that other operand kinds are tokens.
1117     // The matcher emitter checks tokens first.
1118     return Kind == k_Token;
1119   }
1120   bool isMem() const override { return Kind == k_Memory; }
1121   bool isConstantMemOff() const {
1122     return isMem() && isa<MCConstantExpr>(getMemOff());
1123   }
1124   // Allow relocation operators.
1125   // FIXME: This predicate and others need to look through binary expressions
1126   //        and determine whether a Value is a constant or not.
1127   template <unsigned Bits, unsigned ShiftAmount = 0>
1128   bool isMemWithSimmOffset() const {
1129     if (!isMem())
1130       return false;
1131     if (!getMemBase()->isGPRAsmReg())
1132       return false;
1133     if (isa<MCTargetExpr>(getMemOff()) ||
1134         (isConstantMemOff() &&
1135          isShiftedInt<Bits, ShiftAmount>(getConstantMemOff())))
1136       return true;
1137     MCValue Res;
1138     bool IsReloc = getMemOff()->evaluateAsRelocatable(Res, nullptr, nullptr);
1139     return IsReloc && isShiftedInt<Bits, ShiftAmount>(Res.getConstant());
1140   }
1141   bool isMemWithGRPMM16Base() const {
1142     return isMem() && getMemBase()->isMM16AsmReg();
1143   }
1144   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
1145     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1146       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
1147   }
1148   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
1149     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1150       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1151       && (getMemBase()->getGPR32Reg() == Mips::SP);
1152   }
1153   template <unsigned Bits> bool isMemWithSimmWordAlignedOffsetGP() const {
1154     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff())
1155       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1156       && (getMemBase()->getGPR32Reg() == Mips::GP);
1157   }
1158   template <unsigned Bits, unsigned ShiftLeftAmount>
1159   bool isScaledUImm() const {
1160     return isConstantImm() &&
1161            isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm());
1162   }
1163   template <unsigned Bits, unsigned ShiftLeftAmount>
1164   bool isScaledSImm() const {
1165     return isConstantImm() &&
1166            isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm());
1167   }
1168   bool isRegList16() const {
1169     if (!isRegList())
1170       return false;
1171 
1172     int Size = RegList.List->size();
1173     if (Size < 2 || Size > 5)
1174       return false;
1175 
1176     unsigned R0 = RegList.List->front();
1177     unsigned R1 = RegList.List->back();
1178     if (!((R0 == Mips::S0 && R1 == Mips::RA) ||
1179           (R0 == Mips::S0_64 && R1 == Mips::RA_64)))
1180       return false;
1181 
1182     int PrevReg = *RegList.List->begin();
1183     for (int i = 1; i < Size - 1; i++) {
1184       int Reg = (*(RegList.List))[i];
1185       if ( Reg != PrevReg + 1)
1186         return false;
1187       PrevReg = Reg;
1188     }
1189 
1190     return true;
1191   }
1192   bool isInvNum() const { return Kind == k_Immediate; }
1193   bool isLSAImm() const {
1194     if (!isConstantImm())
1195       return false;
1196     int64_t Val = getConstantImm();
1197     return 1 <= Val && Val <= 4;
1198   }
1199   bool isRegList() const { return Kind == k_RegList; }
1200   bool isMovePRegPair() const {
1201     if (Kind != k_RegList || RegList.List->size() != 2)
1202       return false;
1203 
1204     unsigned R0 = RegList.List->front();
1205     unsigned R1 = RegList.List->back();
1206 
1207     if ((R0 == Mips::A1 && R1 == Mips::A2) ||
1208         (R0 == Mips::A1 && R1 == Mips::A3) ||
1209         (R0 == Mips::A2 && R1 == Mips::A3) ||
1210         (R0 == Mips::A0 && R1 == Mips::S5) ||
1211         (R0 == Mips::A0 && R1 == Mips::S6) ||
1212         (R0 == Mips::A0 && R1 == Mips::A1) ||
1213         (R0 == Mips::A0 && R1 == Mips::A2) ||
1214         (R0 == Mips::A0 && R1 == Mips::A3) ||
1215         (R0 == Mips::A1_64 && R1 == Mips::A2_64) ||
1216         (R0 == Mips::A1_64 && R1 == Mips::A3_64) ||
1217         (R0 == Mips::A2_64 && R1 == Mips::A3_64) ||
1218         (R0 == Mips::A0_64 && R1 == Mips::S5_64) ||
1219         (R0 == Mips::A0_64 && R1 == Mips::S6_64) ||
1220         (R0 == Mips::A0_64 && R1 == Mips::A1_64) ||
1221         (R0 == Mips::A0_64 && R1 == Mips::A2_64) ||
1222         (R0 == Mips::A0_64 && R1 == Mips::A3_64))
1223       return true;
1224 
1225     return false;
1226   }
1227 
1228   StringRef getToken() const {
1229     assert(Kind == k_Token && "Invalid access!");
1230     return StringRef(Tok.Data, Tok.Length);
1231   }
1232   bool isRegPair() const {
1233     return Kind == k_RegPair && RegIdx.Index <= 30;
1234   }
1235 
1236   unsigned getReg() const override {
1237     // As a special case until we sort out the definition of div/divu, accept
1238     // $0/$zero here so that MCK_ZERO works correctly.
1239     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1240         RegIdx.Kind & RegKind_GPR)
1241       return getGPR32Reg(); // FIXME: GPR64 too
1242 
1243     llvm_unreachable("Invalid access!");
1244     return 0;
1245   }
1246 
1247   const MCExpr *getImm() const {
1248     assert((Kind == k_Immediate) && "Invalid access!");
1249     return Imm.Val;
1250   }
1251 
1252   int64_t getConstantImm() const {
1253     const MCExpr *Val = getImm();
1254     return static_cast<const MCConstantExpr *>(Val)->getValue();
1255   }
1256 
1257   MipsOperand *getMemBase() const {
1258     assert((Kind == k_Memory) && "Invalid access!");
1259     return Mem.Base;
1260   }
1261 
1262   const MCExpr *getMemOff() const {
1263     assert((Kind == k_Memory) && "Invalid access!");
1264     return Mem.Off;
1265   }
1266 
1267   int64_t getConstantMemOff() const {
1268     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1269   }
1270 
1271   const SmallVectorImpl<unsigned> &getRegList() const {
1272     assert((Kind == k_RegList) && "Invalid access!");
1273     return *(RegList.List);
1274   }
1275 
1276   unsigned getRegPair() const {
1277     assert((Kind == k_RegPair) && "Invalid access!");
1278     return RegIdx.Index;
1279   }
1280 
1281   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1282                                                   MipsAsmParser &Parser) {
1283     auto Op = make_unique<MipsOperand>(k_Token, Parser);
1284     Op->Tok.Data = Str.data();
1285     Op->Tok.Length = Str.size();
1286     Op->StartLoc = S;
1287     Op->EndLoc = S;
1288     return Op;
1289   }
1290 
1291   /// Create a numeric register (e.g. $1). The exact register remains
1292   /// unresolved until an instruction successfully matches
1293   static std::unique_ptr<MipsOperand>
1294   createNumericReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1295                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1296     DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1297     return CreateReg(Index, Str, RegKind_Numeric, RegInfo, S, E, Parser);
1298   }
1299 
1300   /// Create a register that is definitely a GPR.
1301   /// This is typically only used for named registers such as $gp.
1302   static std::unique_ptr<MipsOperand>
1303   createGPRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1304                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1305     return CreateReg(Index, Str, RegKind_GPR, RegInfo, S, E, Parser);
1306   }
1307 
1308   /// Create a register that is definitely a FGR.
1309   /// This is typically only used for named registers such as $f0.
1310   static std::unique_ptr<MipsOperand>
1311   createFGRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1312                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1313     return CreateReg(Index, Str, RegKind_FGR, RegInfo, S, E, Parser);
1314   }
1315 
1316   /// Create a register that is definitely a HWReg.
1317   /// This is typically only used for named registers such as $hwr_cpunum.
1318   static std::unique_ptr<MipsOperand>
1319   createHWRegsReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1320                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1321     return CreateReg(Index, Str, RegKind_HWRegs, RegInfo, S, E, Parser);
1322   }
1323 
1324   /// Create a register that is definitely an FCC.
1325   /// This is typically only used for named registers such as $fcc0.
1326   static std::unique_ptr<MipsOperand>
1327   createFCCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1328                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1329     return CreateReg(Index, Str, RegKind_FCC, RegInfo, S, E, Parser);
1330   }
1331 
1332   /// Create a register that is definitely an ACC.
1333   /// This is typically only used for named registers such as $ac0.
1334   static std::unique_ptr<MipsOperand>
1335   createACCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1336                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1337     return CreateReg(Index, Str, RegKind_ACC, RegInfo, S, E, Parser);
1338   }
1339 
1340   /// Create a register that is definitely an MSA128.
1341   /// This is typically only used for named registers such as $w0.
1342   static std::unique_ptr<MipsOperand>
1343   createMSA128Reg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1344                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1345     return CreateReg(Index, Str, RegKind_MSA128, RegInfo, S, E, Parser);
1346   }
1347 
1348   /// Create a register that is definitely an MSACtrl.
1349   /// This is typically only used for named registers such as $msaaccess.
1350   static std::unique_ptr<MipsOperand>
1351   createMSACtrlReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1352                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1353     return CreateReg(Index, Str, RegKind_MSACtrl, RegInfo, S, E, Parser);
1354   }
1355 
1356   static std::unique_ptr<MipsOperand>
1357   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1358     auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
1359     Op->Imm.Val = Val;
1360     Op->StartLoc = S;
1361     Op->EndLoc = E;
1362     return Op;
1363   }
1364 
1365   static std::unique_ptr<MipsOperand>
1366   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1367             SMLoc E, MipsAsmParser &Parser) {
1368     auto Op = make_unique<MipsOperand>(k_Memory, Parser);
1369     Op->Mem.Base = Base.release();
1370     Op->Mem.Off = Off;
1371     Op->StartLoc = S;
1372     Op->EndLoc = E;
1373     return Op;
1374   }
1375 
1376   static std::unique_ptr<MipsOperand>
1377   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1378                 MipsAsmParser &Parser) {
1379     assert (Regs.size() > 0 && "Empty list not allowed");
1380 
1381     auto Op = make_unique<MipsOperand>(k_RegList, Parser);
1382     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1383     Op->StartLoc = StartLoc;
1384     Op->EndLoc = EndLoc;
1385     return Op;
1386   }
1387 
1388   static std::unique_ptr<MipsOperand> CreateRegPair(const MipsOperand &MOP,
1389                                                     SMLoc S, SMLoc E,
1390                                                     MipsAsmParser &Parser) {
1391     auto Op = make_unique<MipsOperand>(k_RegPair, Parser);
1392     Op->RegIdx.Index = MOP.RegIdx.Index;
1393     Op->RegIdx.RegInfo = MOP.RegIdx.RegInfo;
1394     Op->RegIdx.Kind = MOP.RegIdx.Kind;
1395     Op->StartLoc = S;
1396     Op->EndLoc = E;
1397     return Op;
1398   }
1399 
1400   bool isGPRAsmReg() const {
1401     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1402   }
1403   bool isMM16AsmReg() const {
1404     if (!(isRegIdx() && RegIdx.Kind))
1405       return false;
1406     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1407             || RegIdx.Index == 16 || RegIdx.Index == 17);
1408   }
1409   bool isMM16AsmRegZero() const {
1410     if (!(isRegIdx() && RegIdx.Kind))
1411       return false;
1412     return (RegIdx.Index == 0 ||
1413             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1414             RegIdx.Index == 17);
1415   }
1416   bool isMM16AsmRegMoveP() const {
1417     if (!(isRegIdx() && RegIdx.Kind))
1418       return false;
1419     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1420       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1421   }
1422   bool isFGRAsmReg() const {
1423     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1424     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1425   }
1426   bool isHWRegsAsmReg() const {
1427     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1428   }
1429   bool isCCRAsmReg() const {
1430     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1431   }
1432   bool isFCCAsmReg() const {
1433     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1434       return false;
1435     if (!AsmParser.hasEightFccRegisters())
1436       return RegIdx.Index == 0;
1437     return RegIdx.Index <= 7;
1438   }
1439   bool isACCAsmReg() const {
1440     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1441   }
1442   bool isCOP0AsmReg() const {
1443     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1444   }
1445   bool isCOP2AsmReg() const {
1446     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1447   }
1448   bool isCOP3AsmReg() const {
1449     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1450   }
1451   bool isMSA128AsmReg() const {
1452     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1453   }
1454   bool isMSACtrlAsmReg() const {
1455     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1456   }
1457 
1458   /// getStartLoc - Get the location of the first token of this operand.
1459   SMLoc getStartLoc() const override { return StartLoc; }
1460   /// getEndLoc - Get the location of the last token of this operand.
1461   SMLoc getEndLoc() const override { return EndLoc; }
1462 
1463   virtual ~MipsOperand() {
1464     switch (Kind) {
1465     case k_Immediate:
1466       break;
1467     case k_Memory:
1468       delete Mem.Base;
1469       break;
1470     case k_RegList:
1471       delete RegList.List;
1472     case k_RegisterIndex:
1473     case k_Token:
1474     case k_RegPair:
1475       break;
1476     }
1477   }
1478 
1479   void print(raw_ostream &OS) const override {
1480     switch (Kind) {
1481     case k_Immediate:
1482       OS << "Imm<";
1483       OS << *Imm.Val;
1484       OS << ">";
1485       break;
1486     case k_Memory:
1487       OS << "Mem<";
1488       Mem.Base->print(OS);
1489       OS << ", ";
1490       OS << *Mem.Off;
1491       OS << ">";
1492       break;
1493     case k_RegisterIndex:
1494       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ", "
1495          << StringRef(RegIdx.Tok.Data, RegIdx.Tok.Length) << ">";
1496       break;
1497     case k_Token:
1498       OS << getToken();
1499       break;
1500     case k_RegList:
1501       OS << "RegList< ";
1502       for (auto Reg : (*RegList.List))
1503         OS << Reg << " ";
1504       OS <<  ">";
1505       break;
1506     case k_RegPair:
1507       OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">";
1508       break;
1509     }
1510   }
1511 
1512   bool isValidForTie(const MipsOperand &Other) const {
1513     if (Kind != Other.Kind)
1514       return false;
1515 
1516     switch (Kind) {
1517     default:
1518       llvm_unreachable("Unexpected kind");
1519       return false;
1520     case k_RegisterIndex: {
1521       StringRef Token(RegIdx.Tok.Data, RegIdx.Tok.Length);
1522       StringRef OtherToken(Other.RegIdx.Tok.Data, Other.RegIdx.Tok.Length);
1523       return Token == OtherToken;
1524     }
1525     }
1526   }
1527 }; // class MipsOperand
1528 } // namespace
1529 
1530 namespace llvm {
1531 extern const MCInstrDesc MipsInsts[];
1532 }
1533 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1534   return MipsInsts[Opcode];
1535 }
1536 
1537 static bool hasShortDelaySlot(unsigned Opcode) {
1538   switch (Opcode) {
1539     case Mips::JALS_MM:
1540     case Mips::JALRS_MM:
1541     case Mips::JALRS16_MM:
1542     case Mips::BGEZALS_MM:
1543     case Mips::BLTZALS_MM:
1544       return true;
1545     default:
1546       return false;
1547   }
1548 }
1549 
1550 static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) {
1551   if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) {
1552     return &SRExpr->getSymbol();
1553   }
1554 
1555   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) {
1556     const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS());
1557     const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS());
1558 
1559     if (LHSSym)
1560       return LHSSym;
1561 
1562     if (RHSSym)
1563       return RHSSym;
1564 
1565     return nullptr;
1566   }
1567 
1568   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1569     return getSingleMCSymbol(UExpr->getSubExpr());
1570 
1571   return nullptr;
1572 }
1573 
1574 static unsigned countMCSymbolRefExpr(const MCExpr *Expr) {
1575   if (isa<MCSymbolRefExpr>(Expr))
1576     return 1;
1577 
1578   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr))
1579     return countMCSymbolRefExpr(BExpr->getLHS()) +
1580            countMCSymbolRefExpr(BExpr->getRHS());
1581 
1582   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1583     return countMCSymbolRefExpr(UExpr->getSubExpr());
1584 
1585   return 0;
1586 }
1587 
1588 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1589                                        MCStreamer &Out,
1590                                        const MCSubtargetInfo *STI) {
1591   MipsTargetStreamer &TOut = getTargetStreamer();
1592   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1593   bool ExpandedJalSym = false;
1594 
1595   Inst.setLoc(IDLoc);
1596 
1597   if (MCID.isBranch() || MCID.isCall()) {
1598     const unsigned Opcode = Inst.getOpcode();
1599     MCOperand Offset;
1600 
1601     switch (Opcode) {
1602     default:
1603       break;
1604     case Mips::BBIT0:
1605     case Mips::BBIT032:
1606     case Mips::BBIT1:
1607     case Mips::BBIT132:
1608       assert(hasCnMips() && "instruction only valid for octeon cpus");
1609       // Fall through
1610 
1611     case Mips::BEQ:
1612     case Mips::BNE:
1613     case Mips::BEQ_MM:
1614     case Mips::BNE_MM:
1615       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1616       Offset = Inst.getOperand(2);
1617       if (!Offset.isImm())
1618         break; // We'll deal with this situation later on when applying fixups.
1619       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1620         return Error(IDLoc, "branch target out of range");
1621       if (OffsetToAlignment(Offset.getImm(),
1622                             1LL << (inMicroMipsMode() ? 1 : 2)))
1623         return Error(IDLoc, "branch to misaligned address");
1624       break;
1625     case Mips::BGEZ:
1626     case Mips::BGTZ:
1627     case Mips::BLEZ:
1628     case Mips::BLTZ:
1629     case Mips::BGEZAL:
1630     case Mips::BLTZAL:
1631     case Mips::BC1F:
1632     case Mips::BC1T:
1633     case Mips::BGEZ_MM:
1634     case Mips::BGTZ_MM:
1635     case Mips::BLEZ_MM:
1636     case Mips::BLTZ_MM:
1637     case Mips::BGEZAL_MM:
1638     case Mips::BLTZAL_MM:
1639     case Mips::BC1F_MM:
1640     case Mips::BC1T_MM:
1641     case Mips::BC1EQZC_MMR6:
1642     case Mips::BC1NEZC_MMR6:
1643     case Mips::BC2EQZC_MMR6:
1644     case Mips::BC2NEZC_MMR6:
1645       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1646       Offset = Inst.getOperand(1);
1647       if (!Offset.isImm())
1648         break; // We'll deal with this situation later on when applying fixups.
1649       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1650         return Error(IDLoc, "branch target out of range");
1651       if (OffsetToAlignment(Offset.getImm(),
1652                             1LL << (inMicroMipsMode() ? 1 : 2)))
1653         return Error(IDLoc, "branch to misaligned address");
1654       break;
1655     case Mips::BEQZ16_MM:
1656     case Mips::BEQZC16_MMR6:
1657     case Mips::BNEZ16_MM:
1658     case Mips::BNEZC16_MMR6:
1659       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1660       Offset = Inst.getOperand(1);
1661       if (!Offset.isImm())
1662         break; // We'll deal with this situation later on when applying fixups.
1663       if (!isInt<8>(Offset.getImm()))
1664         return Error(IDLoc, "branch target out of range");
1665       if (OffsetToAlignment(Offset.getImm(), 2LL))
1666         return Error(IDLoc, "branch to misaligned address");
1667       break;
1668     }
1669   }
1670 
1671   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1672   // We still accept it but it is a normal nop.
1673   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1674     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1675     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1676                                                       "nop instruction");
1677   }
1678 
1679   if (hasCnMips()) {
1680     const unsigned Opcode = Inst.getOpcode();
1681     MCOperand Opnd;
1682     int Imm;
1683 
1684     switch (Opcode) {
1685       default:
1686         break;
1687 
1688       case Mips::BBIT0:
1689       case Mips::BBIT032:
1690       case Mips::BBIT1:
1691       case Mips::BBIT132:
1692         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1693         // The offset is handled above
1694         Opnd = Inst.getOperand(1);
1695         if (!Opnd.isImm())
1696           return Error(IDLoc, "expected immediate operand kind");
1697         Imm = Opnd.getImm();
1698         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1699                               Opcode == Mips::BBIT1 ? 63 : 31))
1700           return Error(IDLoc, "immediate operand value out of range");
1701         if (Imm > 31) {
1702           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1703                                                : Mips::BBIT132);
1704           Inst.getOperand(1).setImm(Imm - 32);
1705         }
1706         break;
1707 
1708       case Mips::SEQi:
1709       case Mips::SNEi:
1710         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1711         Opnd = Inst.getOperand(2);
1712         if (!Opnd.isImm())
1713           return Error(IDLoc, "expected immediate operand kind");
1714         Imm = Opnd.getImm();
1715         if (!isInt<10>(Imm))
1716           return Error(IDLoc, "immediate operand value out of range");
1717         break;
1718     }
1719   }
1720 
1721   // This expansion is not in a function called by tryExpandInstruction()
1722   // because the pseudo-instruction doesn't have a distinct opcode.
1723   if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) &&
1724       inPicMode()) {
1725     warnIfNoMacro(IDLoc);
1726 
1727     const MCExpr *JalExpr = Inst.getOperand(0).getExpr();
1728 
1729     // We can do this expansion if there's only 1 symbol in the argument
1730     // expression.
1731     if (countMCSymbolRefExpr(JalExpr) > 1)
1732       return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode");
1733 
1734     // FIXME: This is checking the expression can be handled by the later stages
1735     //        of the assembler. We ought to leave it to those later stages.
1736     const MCSymbol *JalSym = getSingleMCSymbol(JalExpr);
1737 
1738     // FIXME: Add support for label+offset operands (currently causes an error).
1739     // FIXME: Add support for forward-declared local symbols.
1740     // FIXME: Add expansion for when the LargeGOT option is enabled.
1741     if (JalSym->isInSection() || JalSym->isTemporary()) {
1742       if (isABI_O32()) {
1743         // If it's a local symbol and the O32 ABI is being used, we expand to:
1744         //  lw $25, 0($gp)
1745         //    R_(MICRO)MIPS_GOT16  label
1746         //  addiu $25, $25, 0
1747         //    R_(MICRO)MIPS_LO16   label
1748         //  jalr  $25
1749         const MCExpr *Got16RelocExpr =
1750             MipsMCExpr::create(MipsMCExpr::MEK_GOT, JalExpr, getContext());
1751         const MCExpr *Lo16RelocExpr =
1752             MipsMCExpr::create(MipsMCExpr::MEK_LO, JalExpr, getContext());
1753 
1754         TOut.emitRRX(Mips::LW, Mips::T9, Mips::GP,
1755                      MCOperand::createExpr(Got16RelocExpr), IDLoc, STI);
1756         TOut.emitRRX(Mips::ADDiu, Mips::T9, Mips::T9,
1757                      MCOperand::createExpr(Lo16RelocExpr), IDLoc, STI);
1758       } else if (isABI_N32() || isABI_N64()) {
1759         // If it's a local symbol and the N32/N64 ABIs are being used,
1760         // we expand to:
1761         //  lw/ld $25, 0($gp)
1762         //    R_(MICRO)MIPS_GOT_DISP  label
1763         //  jalr  $25
1764         const MCExpr *GotDispRelocExpr =
1765             MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, JalExpr, getContext());
1766 
1767         TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9,
1768                      Mips::GP, MCOperand::createExpr(GotDispRelocExpr), IDLoc,
1769                      STI);
1770       }
1771     } else {
1772       // If it's an external/weak symbol, we expand to:
1773       //  lw/ld    $25, 0($gp)
1774       //    R_(MICRO)MIPS_CALL16  label
1775       //  jalr  $25
1776       const MCExpr *Call16RelocExpr =
1777           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, JalExpr, getContext());
1778 
1779       TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
1780                    MCOperand::createExpr(Call16RelocExpr), IDLoc, STI);
1781     }
1782 
1783     MCInst JalrInst;
1784     if (IsCpRestoreSet && inMicroMipsMode())
1785       JalrInst.setOpcode(Mips::JALRS_MM);
1786     else
1787       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
1788     JalrInst.addOperand(MCOperand::createReg(Mips::RA));
1789     JalrInst.addOperand(MCOperand::createReg(Mips::T9));
1790 
1791     // FIXME: Add an R_(MICRO)MIPS_JALR relocation after the JALR.
1792     // This relocation is supposed to be an optimization hint for the linker
1793     // and is not necessary for correctness.
1794 
1795     Inst = JalrInst;
1796     ExpandedJalSym = true;
1797   }
1798 
1799   if (MCID.mayLoad() || MCID.mayStore()) {
1800     // Check the offset of memory operand, if it is a symbol
1801     // reference or immediate we may have to expand instructions.
1802     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1803       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1804       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1805           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1806         MCOperand &Op = Inst.getOperand(i);
1807         if (Op.isImm()) {
1808           int MemOffset = Op.getImm();
1809           if (MemOffset < -32768 || MemOffset > 32767) {
1810             // Offset can't exceed 16bit value.
1811             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), true);
1812             return false;
1813           }
1814         } else if (Op.isExpr()) {
1815           const MCExpr *Expr = Op.getExpr();
1816           if (Expr->getKind() == MCExpr::SymbolRef) {
1817             const MCSymbolRefExpr *SR =
1818                 static_cast<const MCSymbolRefExpr *>(Expr);
1819             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
1820               // Expand symbol.
1821               expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false);
1822               return false;
1823             }
1824           } else if (!isEvaluated(Expr)) {
1825             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false);
1826             return false;
1827           }
1828         }
1829       }
1830     } // for
1831   }   // if load/store
1832 
1833   if (inMicroMipsMode()) {
1834     if (MCID.mayLoad()) {
1835       // Try to create 16-bit GP relative load instruction.
1836       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1837         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1838         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1839             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1840           MCOperand &Op = Inst.getOperand(i);
1841           if (Op.isImm()) {
1842             int MemOffset = Op.getImm();
1843             MCOperand &DstReg = Inst.getOperand(0);
1844             MCOperand &BaseReg = Inst.getOperand(1);
1845             if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) &&
1846                 getContext().getRegisterInfo()->getRegClass(
1847                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
1848                 (BaseReg.getReg() == Mips::GP ||
1849                 BaseReg.getReg() == Mips::GP_64)) {
1850 
1851               TOut.emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset,
1852                            IDLoc, STI);
1853               return false;
1854             }
1855           }
1856         }
1857       } // for
1858     }   // if load
1859 
1860     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
1861 
1862     MCOperand Opnd;
1863     int Imm;
1864 
1865     switch (Inst.getOpcode()) {
1866       default:
1867         break;
1868       case Mips::ADDIUSP_MM:
1869         Opnd = Inst.getOperand(0);
1870         if (!Opnd.isImm())
1871           return Error(IDLoc, "expected immediate operand kind");
1872         Imm = Opnd.getImm();
1873         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
1874             Imm % 4 != 0)
1875           return Error(IDLoc, "immediate operand value out of range");
1876         break;
1877       case Mips::SLL16_MM:
1878       case Mips::SRL16_MM:
1879         Opnd = Inst.getOperand(2);
1880         if (!Opnd.isImm())
1881           return Error(IDLoc, "expected immediate operand kind");
1882         Imm = Opnd.getImm();
1883         if (Imm < 1 || Imm > 8)
1884           return Error(IDLoc, "immediate operand value out of range");
1885         break;
1886       case Mips::LI16_MM:
1887         Opnd = Inst.getOperand(1);
1888         if (!Opnd.isImm())
1889           return Error(IDLoc, "expected immediate operand kind");
1890         Imm = Opnd.getImm();
1891         if (Imm < -1 || Imm > 126)
1892           return Error(IDLoc, "immediate operand value out of range");
1893         break;
1894       case Mips::ADDIUR2_MM:
1895         Opnd = Inst.getOperand(2);
1896         if (!Opnd.isImm())
1897           return Error(IDLoc, "expected immediate operand kind");
1898         Imm = Opnd.getImm();
1899         if (!(Imm == 1 || Imm == -1 ||
1900               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
1901           return Error(IDLoc, "immediate operand value out of range");
1902         break;
1903       case Mips::ANDI16_MM:
1904         Opnd = Inst.getOperand(2);
1905         if (!Opnd.isImm())
1906           return Error(IDLoc, "expected immediate operand kind");
1907         Imm = Opnd.getImm();
1908         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
1909               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
1910               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
1911           return Error(IDLoc, "immediate operand value out of range");
1912         break;
1913       case Mips::LBU16_MM:
1914         Opnd = Inst.getOperand(2);
1915         if (!Opnd.isImm())
1916           return Error(IDLoc, "expected immediate operand kind");
1917         Imm = Opnd.getImm();
1918         if (Imm < -1 || Imm > 14)
1919           return Error(IDLoc, "immediate operand value out of range");
1920         break;
1921       case Mips::SB16_MM:
1922       case Mips::SB16_MMR6:
1923         Opnd = Inst.getOperand(2);
1924         if (!Opnd.isImm())
1925           return Error(IDLoc, "expected immediate operand kind");
1926         Imm = Opnd.getImm();
1927         if (Imm < 0 || Imm > 15)
1928           return Error(IDLoc, "immediate operand value out of range");
1929         break;
1930       case Mips::LHU16_MM:
1931       case Mips::SH16_MM:
1932       case Mips::SH16_MMR6:
1933         Opnd = Inst.getOperand(2);
1934         if (!Opnd.isImm())
1935           return Error(IDLoc, "expected immediate operand kind");
1936         Imm = Opnd.getImm();
1937         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
1938           return Error(IDLoc, "immediate operand value out of range");
1939         break;
1940       case Mips::LW16_MM:
1941       case Mips::SW16_MM:
1942       case Mips::SW16_MMR6:
1943         Opnd = Inst.getOperand(2);
1944         if (!Opnd.isImm())
1945           return Error(IDLoc, "expected immediate operand kind");
1946         Imm = Opnd.getImm();
1947         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
1948           return Error(IDLoc, "immediate operand value out of range");
1949         break;
1950       case Mips::ADDIUPC_MM:
1951         MCOperand Opnd = Inst.getOperand(1);
1952         if (!Opnd.isImm())
1953           return Error(IDLoc, "expected immediate operand kind");
1954         int Imm = Opnd.getImm();
1955         if ((Imm % 4 != 0) || !isInt<25>(Imm))
1956           return Error(IDLoc, "immediate operand value out of range");
1957         break;
1958     }
1959   }
1960 
1961   bool FillDelaySlot =
1962       MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder();
1963   if (FillDelaySlot)
1964     TOut.emitDirectiveSetNoReorder();
1965 
1966   MacroExpanderResultTy ExpandResult =
1967       tryExpandInstruction(Inst, IDLoc, Out, STI);
1968   switch (ExpandResult) {
1969   case MER_NotAMacro:
1970     Out.EmitInstruction(Inst, *STI);
1971     break;
1972   case MER_Success:
1973     break;
1974   case MER_Fail:
1975     return true;
1976   }
1977 
1978   // We know we emitted an instruction on the MER_NotAMacro or MER_Success path.
1979   // If we're in microMIPS mode then we must also set EF_MIPS_MICROMIPS.
1980   if (inMicroMipsMode())
1981     TOut.setUsesMicroMips();
1982 
1983   // If this instruction has a delay slot and .set reorder is active,
1984   // emit a NOP after it.
1985   if (FillDelaySlot) {
1986     TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc, STI);
1987     TOut.emitDirectiveSetReorder();
1988   }
1989 
1990   if ((Inst.getOpcode() == Mips::JalOneReg ||
1991        Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) &&
1992       isPicAndNotNxxAbi()) {
1993     if (IsCpRestoreSet) {
1994       // We need a NOP between the JALR and the LW:
1995       // If .set reorder has been used, we've already emitted a NOP.
1996       // If .set noreorder has been used, we need to emit a NOP at this point.
1997       if (!AssemblerOptions.back()->isReorder())
1998         TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc,
1999                                 STI);
2000 
2001       // Load the $gp from the stack.
2002       TOut.emitGPRestore(CpRestoreOffset, IDLoc, STI);
2003     } else
2004       Warning(IDLoc, "no .cprestore used in PIC mode");
2005   }
2006 
2007   return false;
2008 }
2009 
2010 MipsAsmParser::MacroExpanderResultTy
2011 MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2012                                     const MCSubtargetInfo *STI) {
2013   switch (Inst.getOpcode()) {
2014   default:
2015     return MER_NotAMacro;
2016   case Mips::LoadImm32:
2017     return expandLoadImm(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2018   case Mips::LoadImm64:
2019     return expandLoadImm(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2020   case Mips::LoadAddrImm32:
2021   case Mips::LoadAddrImm64:
2022     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2023     assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) &&
2024            "expected immediate operand kind");
2025 
2026     return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister,
2027                              Inst.getOperand(1),
2028                              Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc,
2029                              Out, STI)
2030                ? MER_Fail
2031                : MER_Success;
2032   case Mips::LoadAddrReg32:
2033   case Mips::LoadAddrReg64:
2034     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2035     assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2036     assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) &&
2037            "expected immediate operand kind");
2038 
2039     return expandLoadAddress(Inst.getOperand(0).getReg(),
2040                              Inst.getOperand(1).getReg(), Inst.getOperand(2),
2041                              Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc,
2042                              Out, STI)
2043                ? MER_Fail
2044                : MER_Success;
2045   case Mips::B_MM_Pseudo:
2046   case Mips::B_MMR6_Pseudo:
2047     return expandUncondBranchMMPseudo(Inst, IDLoc, Out, STI) ? MER_Fail
2048                                                              : MER_Success;
2049   case Mips::SWM_MM:
2050   case Mips::LWM_MM:
2051     return expandLoadStoreMultiple(Inst, IDLoc, Out, STI) ? MER_Fail
2052                                                           : MER_Success;
2053   case Mips::JalOneReg:
2054   case Mips::JalTwoReg:
2055     return expandJalWithRegs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2056   case Mips::BneImm:
2057   case Mips::BeqImm:
2058     return expandBranchImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2059   case Mips::BLT:
2060   case Mips::BLE:
2061   case Mips::BGE:
2062   case Mips::BGT:
2063   case Mips::BLTU:
2064   case Mips::BLEU:
2065   case Mips::BGEU:
2066   case Mips::BGTU:
2067   case Mips::BLTL:
2068   case Mips::BLEL:
2069   case Mips::BGEL:
2070   case Mips::BGTL:
2071   case Mips::BLTUL:
2072   case Mips::BLEUL:
2073   case Mips::BGEUL:
2074   case Mips::BGTUL:
2075   case Mips::BLTImmMacro:
2076   case Mips::BLEImmMacro:
2077   case Mips::BGEImmMacro:
2078   case Mips::BGTImmMacro:
2079   case Mips::BLTUImmMacro:
2080   case Mips::BLEUImmMacro:
2081   case Mips::BGEUImmMacro:
2082   case Mips::BGTUImmMacro:
2083   case Mips::BLTLImmMacro:
2084   case Mips::BLELImmMacro:
2085   case Mips::BGELImmMacro:
2086   case Mips::BGTLImmMacro:
2087   case Mips::BLTULImmMacro:
2088   case Mips::BLEULImmMacro:
2089   case Mips::BGEULImmMacro:
2090   case Mips::BGTULImmMacro:
2091     return expandCondBranches(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2092   case Mips::SDivMacro:
2093     return expandDiv(Inst, IDLoc, Out, STI, false, true) ? MER_Fail
2094                                                          : MER_Success;
2095   case Mips::DSDivMacro:
2096     return expandDiv(Inst, IDLoc, Out, STI, true, true) ? MER_Fail
2097                                                         : MER_Success;
2098   case Mips::UDivMacro:
2099     return expandDiv(Inst, IDLoc, Out, STI, false, false) ? MER_Fail
2100                                                           : MER_Success;
2101   case Mips::DUDivMacro:
2102     return expandDiv(Inst, IDLoc, Out, STI, true, false) ? MER_Fail
2103                                                          : MER_Success;
2104   case Mips::PseudoTRUNC_W_S:
2105     return expandTrunc(Inst, false, false, IDLoc, Out, STI) ? MER_Fail
2106                                                             : MER_Success;
2107   case Mips::PseudoTRUNC_W_D32:
2108     return expandTrunc(Inst, true, false, IDLoc, Out, STI) ? MER_Fail
2109                                                            : MER_Success;
2110   case Mips::PseudoTRUNC_W_D:
2111     return expandTrunc(Inst, true, true, IDLoc, Out, STI) ? MER_Fail
2112                                                           : MER_Success;
2113   case Mips::Ulh:
2114     return expandUlh(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2115   case Mips::Ulhu:
2116     return expandUlh(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2117   case Mips::Ulw:
2118     return expandUlw(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2119   case Mips::NORImm:
2120     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2121   case Mips::ADDi:
2122   case Mips::ADDiu:
2123   case Mips::SLTi:
2124   case Mips::SLTiu:
2125     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2126         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2127       int64_t ImmValue = Inst.getOperand(2).getImm();
2128       if (isInt<16>(ImmValue))
2129         return MER_NotAMacro;
2130       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2131                                                          : MER_Success;
2132     }
2133     return MER_NotAMacro;
2134   case Mips::ANDi:
2135   case Mips::ORi:
2136   case Mips::XORi:
2137     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2138         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2139       int64_t ImmValue = Inst.getOperand(2).getImm();
2140       if (isUInt<16>(ImmValue))
2141         return MER_NotAMacro;
2142       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2143                                                          : MER_Success;
2144     }
2145     return MER_NotAMacro;
2146   case Mips::ROL:
2147   case Mips::ROR:
2148     return expandRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2149   case Mips::ROLImm:
2150   case Mips::RORImm:
2151     return expandRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2152   case Mips::DROL:
2153   case Mips::DROR:
2154     return expandDRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2155   case Mips::DROLImm:
2156   case Mips::DRORImm:
2157     return expandDRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2158   case Mips::ABSMacro:
2159     return expandAbs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2160   }
2161 }
2162 
2163 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
2164                                       MCStreamer &Out,
2165                                       const MCSubtargetInfo *STI) {
2166   MipsTargetStreamer &TOut = getTargetStreamer();
2167 
2168   // Create a JALR instruction which is going to replace the pseudo-JAL.
2169   MCInst JalrInst;
2170   JalrInst.setLoc(IDLoc);
2171   const MCOperand FirstRegOp = Inst.getOperand(0);
2172   const unsigned Opcode = Inst.getOpcode();
2173 
2174   if (Opcode == Mips::JalOneReg) {
2175     // jal $rs => jalr $rs
2176     if (IsCpRestoreSet && inMicroMipsMode()) {
2177       JalrInst.setOpcode(Mips::JALRS16_MM);
2178       JalrInst.addOperand(FirstRegOp);
2179     } else if (inMicroMipsMode()) {
2180       JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM);
2181       JalrInst.addOperand(FirstRegOp);
2182     } else {
2183       JalrInst.setOpcode(Mips::JALR);
2184       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2185       JalrInst.addOperand(FirstRegOp);
2186     }
2187   } else if (Opcode == Mips::JalTwoReg) {
2188     // jal $rd, $rs => jalr $rd, $rs
2189     if (IsCpRestoreSet && inMicroMipsMode())
2190       JalrInst.setOpcode(Mips::JALRS_MM);
2191     else
2192       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2193     JalrInst.addOperand(FirstRegOp);
2194     const MCOperand SecondRegOp = Inst.getOperand(1);
2195     JalrInst.addOperand(SecondRegOp);
2196   }
2197   Out.EmitInstruction(JalrInst, *STI);
2198 
2199   // If .set reorder is active and branch instruction has a delay slot,
2200   // emit a NOP after it.
2201   const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode());
2202   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2203     TOut.emitEmptyDelaySlot(hasShortDelaySlot(JalrInst.getOpcode()), IDLoc,
2204                             STI);
2205 
2206   return false;
2207 }
2208 
2209 /// Can the value be represented by a unsigned N-bit value and a shift left?
2210 template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) {
2211   unsigned BitNum = findFirstSet(x);
2212 
2213   return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum);
2214 }
2215 
2216 /// Load (or add) an immediate into a register.
2217 ///
2218 /// @param ImmValue     The immediate to load.
2219 /// @param DstReg       The register that will hold the immediate.
2220 /// @param SrcReg       A register to add to the immediate or Mips::NoRegister
2221 ///                     for a simple initialization.
2222 /// @param Is32BitImm   Is ImmValue 32-bit or 64-bit?
2223 /// @param IsAddress    True if the immediate represents an address. False if it
2224 ///                     is an integer.
2225 /// @param IDLoc        Location of the immediate in the source file.
2226 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
2227                                   unsigned SrcReg, bool Is32BitImm,
2228                                   bool IsAddress, SMLoc IDLoc, MCStreamer &Out,
2229                                   const MCSubtargetInfo *STI) {
2230   MipsTargetStreamer &TOut = getTargetStreamer();
2231 
2232   if (!Is32BitImm && !isGP64bit()) {
2233     Error(IDLoc, "instruction requires a 64-bit architecture");
2234     return true;
2235   }
2236 
2237   if (Is32BitImm) {
2238     if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2239       // Sign extend up to 64-bit so that the predicates match the hardware
2240       // behaviour. In particular, isInt<16>(0xffff8000) and similar should be
2241       // true.
2242       ImmValue = SignExtend64<32>(ImmValue);
2243     } else {
2244       Error(IDLoc, "instruction requires a 32-bit immediate");
2245       return true;
2246     }
2247   }
2248 
2249   unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg();
2250   unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu;
2251 
2252   bool UseSrcReg = false;
2253   if (SrcReg != Mips::NoRegister)
2254     UseSrcReg = true;
2255 
2256   unsigned TmpReg = DstReg;
2257   if (UseSrcReg &&
2258       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2259     // At this point we need AT to perform the expansions and we exit if it is
2260     // not available.
2261     unsigned ATReg = getATReg(IDLoc);
2262     if (!ATReg)
2263       return true;
2264     TmpReg = ATReg;
2265   }
2266 
2267   if (isInt<16>(ImmValue)) {
2268     if (!UseSrcReg)
2269       SrcReg = ZeroReg;
2270 
2271     // This doesn't quite follow the usual ABI expectations for N32 but matches
2272     // traditional assembler behaviour. N32 would normally use addiu for both
2273     // integers and addresses.
2274     if (IsAddress && !Is32BitImm) {
2275       TOut.emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2276       return false;
2277     }
2278 
2279     TOut.emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2280     return false;
2281   }
2282 
2283   if (isUInt<16>(ImmValue)) {
2284     unsigned TmpReg = DstReg;
2285     if (SrcReg == DstReg) {
2286       TmpReg = getATReg(IDLoc);
2287       if (!TmpReg)
2288         return true;
2289     }
2290 
2291     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, STI);
2292     if (UseSrcReg)
2293       TOut.emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, STI);
2294     return false;
2295   }
2296 
2297   if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2298     warnIfNoMacro(IDLoc);
2299 
2300     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
2301     uint16_t Bits15To0 = ImmValue & 0xffff;
2302 
2303     if (!Is32BitImm && !isInt<32>(ImmValue)) {
2304       // Traditional behaviour seems to special case this particular value. It's
2305       // not clear why other masks are handled differently.
2306       if (ImmValue == 0xffffffff) {
2307         TOut.emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, STI);
2308         TOut.emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, STI);
2309         if (UseSrcReg)
2310           TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2311         return false;
2312       }
2313 
2314       // Expand to an ORi instead of a LUi to avoid sign-extending into the
2315       // upper 32 bits.
2316       TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, STI);
2317       TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, STI);
2318       if (Bits15To0)
2319         TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2320       if (UseSrcReg)
2321         TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2322       return false;
2323     }
2324 
2325     TOut.emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, STI);
2326     if (Bits15To0)
2327       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2328     if (UseSrcReg)
2329       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2330     return false;
2331   }
2332 
2333   if (isShiftedUIntAtAnyPosition<16>(ImmValue)) {
2334     if (Is32BitImm) {
2335       Error(IDLoc, "instruction requires a 32-bit immediate");
2336       return true;
2337     }
2338 
2339     // Traditionally, these immediates are shifted as little as possible and as
2340     // such we align the most significant bit to bit 15 of our temporary.
2341     unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
2342     unsigned LastSet = findLastSet((uint64_t)ImmValue);
2343     unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
2344     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
2345     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, STI);
2346     TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, STI);
2347 
2348     if (UseSrcReg)
2349       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2350 
2351     return false;
2352   }
2353 
2354   warnIfNoMacro(IDLoc);
2355 
2356   // The remaining case is packed with a sequence of dsll and ori with zeros
2357   // being omitted and any neighbouring dsll's being coalesced.
2358   // The highest 32-bit's are equivalent to a 32-bit immediate load.
2359 
2360   // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register.
2361   if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false,
2362                     IDLoc, Out, STI))
2363     return false;
2364 
2365   // Shift and accumulate into the register. If a 16-bit chunk is zero, then
2366   // skip it and defer the shift to the next chunk.
2367   unsigned ShiftCarriedForwards = 16;
2368   for (int BitNum = 16; BitNum >= 0; BitNum -= 16) {
2369     uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff;
2370 
2371     if (ImmChunk != 0) {
2372       TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2373       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, STI);
2374       ShiftCarriedForwards = 0;
2375     }
2376 
2377     ShiftCarriedForwards += 16;
2378   }
2379   ShiftCarriedForwards -= 16;
2380 
2381   // Finish any remaining shifts left by trailing zeros.
2382   if (ShiftCarriedForwards)
2383     TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2384 
2385   if (UseSrcReg)
2386     TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2387 
2388   return false;
2389 }
2390 
2391 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2392                                   MCStreamer &Out, const MCSubtargetInfo *STI) {
2393   const MCOperand &ImmOp = Inst.getOperand(1);
2394   assert(ImmOp.isImm() && "expected immediate operand kind");
2395   const MCOperand &DstRegOp = Inst.getOperand(0);
2396   assert(DstRegOp.isReg() && "expected register operand kind");
2397 
2398   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2399                     Is32BitImm, false, IDLoc, Out, STI))
2400     return true;
2401 
2402   return false;
2403 }
2404 
2405 bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg,
2406                                       const MCOperand &Offset,
2407                                       bool Is32BitAddress, SMLoc IDLoc,
2408                                       MCStreamer &Out,
2409                                       const MCSubtargetInfo *STI) {
2410   // la can't produce a usable address when addresses are 64-bit.
2411   if (Is32BitAddress && ABI.ArePtrs64bit()) {
2412     // FIXME: Demote this to a warning and continue as if we had 'dla' instead.
2413     //        We currently can't do this because we depend on the equality
2414     //        operator and N64 can end up with a GPR32/GPR64 mismatch.
2415     Error(IDLoc, "la used to load 64-bit address");
2416     // Continue as if we had 'dla' instead.
2417     Is32BitAddress = false;
2418   }
2419 
2420   // dla requires 64-bit addresses.
2421   if (!Is32BitAddress && !hasMips3()) {
2422     Error(IDLoc, "instruction requires a 64-bit architecture");
2423     return true;
2424   }
2425 
2426   if (!Offset.isImm())
2427     return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg,
2428                                    Is32BitAddress, IDLoc, Out, STI);
2429 
2430   if (!ABI.ArePtrs64bit()) {
2431     // Continue as if we had 'la' whether we had 'la' or 'dla'.
2432     Is32BitAddress = true;
2433   }
2434 
2435   return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true,
2436                        IDLoc, Out, STI);
2437 }
2438 
2439 bool MipsAsmParser::loadAndAddSymbolAddress(const MCExpr *SymExpr,
2440                                             unsigned DstReg, unsigned SrcReg,
2441                                             bool Is32BitSym, SMLoc IDLoc,
2442                                             MCStreamer &Out,
2443                                             const MCSubtargetInfo *STI) {
2444   MipsTargetStreamer &TOut = getTargetStreamer();
2445   bool UseSrcReg = SrcReg != Mips::NoRegister;
2446   warnIfNoMacro(IDLoc);
2447 
2448   if (inPicMode() && ABI.IsO32()) {
2449     MCValue Res;
2450     if (!SymExpr->evaluateAsRelocatable(Res, nullptr, nullptr)) {
2451       Error(IDLoc, "expected relocatable expression");
2452       return true;
2453     }
2454     if (Res.getSymB() != nullptr) {
2455       Error(IDLoc, "expected relocatable expression with only one symbol");
2456       return true;
2457     }
2458 
2459     // The case where the result register is $25 is somewhat special. If the
2460     // symbol in the final relocation is external and not modified with a
2461     // constant then we must use R_MIPS_CALL16 instead of R_MIPS_GOT16.
2462     if ((DstReg == Mips::T9 || DstReg == Mips::T9_64) && !UseSrcReg &&
2463         Res.getConstant() == 0 && !Res.getSymA()->getSymbol().isInSection() &&
2464         !Res.getSymA()->getSymbol().isTemporary()) {
2465       const MCExpr *CallExpr =
2466           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, SymExpr, getContext());
2467       TOut.emitRRX(Mips::LW, DstReg, ABI.GetGlobalPtr(),
2468                    MCOperand::createExpr(CallExpr), IDLoc, STI);
2469       return false;
2470     }
2471 
2472     // The remaining cases are:
2473     //   External GOT: lw $tmp, %got(symbol+offset)($gp)
2474     //                >addiu $tmp, $tmp, %lo(offset)
2475     //                >addiu $rd, $tmp, $rs
2476     //   Local GOT:    lw $tmp, %got(symbol+offset)($gp)
2477     //                 addiu $tmp, $tmp, %lo(symbol+offset)($gp)
2478     //                >addiu $rd, $tmp, $rs
2479     // The addiu's marked with a '>' may be omitted if they are redundant. If
2480     // this happens then the last instruction must use $rd as the result
2481     // register.
2482     const MipsMCExpr *GotExpr =
2483         MipsMCExpr::create(MipsMCExpr::MEK_GOT, SymExpr, getContext());
2484     const MCExpr *LoExpr = nullptr;
2485     if (Res.getSymA()->getSymbol().isInSection() ||
2486         Res.getSymA()->getSymbol().isTemporary())
2487       LoExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
2488     else if (Res.getConstant() != 0) {
2489       // External symbols fully resolve the symbol with just the %got(symbol)
2490       // but we must still account for any offset to the symbol for expressions
2491       // like symbol+8.
2492       LoExpr = MCConstantExpr::create(Res.getConstant(), getContext());
2493     }
2494 
2495     unsigned TmpReg = DstReg;
2496     if (UseSrcReg &&
2497         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2498                                                                SrcReg)) {
2499       // If $rs is the same as $rd, we need to use AT.
2500       // If it is not available we exit.
2501       unsigned ATReg = getATReg(IDLoc);
2502       if (!ATReg)
2503         return true;
2504       TmpReg = ATReg;
2505     }
2506 
2507     TOut.emitRRX(Mips::LW, TmpReg, ABI.GetGlobalPtr(),
2508                  MCOperand::createExpr(GotExpr), IDLoc, STI);
2509 
2510     if (LoExpr)
2511       TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
2512                    IDLoc, STI);
2513 
2514     if (UseSrcReg)
2515       TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
2516 
2517     return false;
2518   }
2519 
2520   const MipsMCExpr *HiExpr =
2521       MipsMCExpr::create(MipsMCExpr::MEK_HI, SymExpr, getContext());
2522   const MipsMCExpr *LoExpr =
2523       MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
2524 
2525   // This is the 64-bit symbol address expansion.
2526   if (ABI.ArePtrs64bit() && isGP64bit()) {
2527     // We always need AT for the 64-bit expansion.
2528     // If it is not available we exit.
2529     unsigned ATReg = getATReg(IDLoc);
2530     if (!ATReg)
2531       return true;
2532 
2533     const MipsMCExpr *HighestExpr =
2534         MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, SymExpr, getContext());
2535     const MipsMCExpr *HigherExpr =
2536         MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, SymExpr, getContext());
2537 
2538     if (UseSrcReg &&
2539         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2540                                                                SrcReg)) {
2541       // If $rs is the same as $rd:
2542       // (d)la $rd, sym($rd) => lui    $at, %highest(sym)
2543       //                        daddiu $at, $at, %higher(sym)
2544       //                        dsll   $at, $at, 16
2545       //                        daddiu $at, $at, %hi(sym)
2546       //                        dsll   $at, $at, 16
2547       //                        daddiu $at, $at, %lo(sym)
2548       //                        daddu  $rd, $at, $rd
2549       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
2550                   STI);
2551       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
2552                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
2553       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
2554       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr),
2555                    IDLoc, STI);
2556       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
2557       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
2558                    IDLoc, STI);
2559       TOut.emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, STI);
2560 
2561       return false;
2562     }
2563 
2564     // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2565     // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
2566     //                            lui    $at, %hi(sym)
2567     //                            daddiu $rd, $rd, %higher(sym)
2568     //                            daddiu $at, $at, %lo(sym)
2569     //                            dsll32 $rd, $rd, 0
2570     //                            daddu  $rd, $rd, $at
2571     //                            (daddu  $rd, $rd, $rs)
2572     TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
2573                 STI);
2574     TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
2575     TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
2576                  MCOperand::createExpr(HigherExpr), IDLoc, STI);
2577     TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
2578                  IDLoc, STI);
2579     TOut.emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, STI);
2580     TOut.emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, STI);
2581     if (UseSrcReg)
2582       TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI);
2583 
2584     return false;
2585   }
2586 
2587   // And now, the 32-bit symbol address expansion:
2588   // If $rs is the same as $rd:
2589   // (d)la $rd, sym($rd)     => lui   $at, %hi(sym)
2590   //                            ori   $at, $at, %lo(sym)
2591   //                            addu  $rd, $at, $rd
2592   // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2593   // (d)la $rd, sym/sym($rs) => lui   $rd, %hi(sym)
2594   //                            ori   $rd, $rd, %lo(sym)
2595   //                            (addu $rd, $rd, $rs)
2596   unsigned TmpReg = DstReg;
2597   if (UseSrcReg &&
2598       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2599     // If $rs is the same as $rd, we need to use AT.
2600     // If it is not available we exit.
2601     unsigned ATReg = getATReg(IDLoc);
2602     if (!ATReg)
2603       return true;
2604     TmpReg = ATReg;
2605   }
2606 
2607   TOut.emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
2608   TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
2609                IDLoc, STI);
2610 
2611   if (UseSrcReg)
2612     TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
2613   else
2614     assert(
2615         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg));
2616 
2617   return false;
2618 }
2619 
2620 bool MipsAsmParser::expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
2621                                                MCStreamer &Out,
2622                                                const MCSubtargetInfo *STI) {
2623   MipsTargetStreamer &TOut = getTargetStreamer();
2624 
2625   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
2626          "unexpected number of operands");
2627 
2628   MCOperand Offset = Inst.getOperand(0);
2629   if (Offset.isExpr()) {
2630     Inst.clear();
2631     Inst.setOpcode(Mips::BEQ_MM);
2632     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2633     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2634     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
2635   } else {
2636     assert(Offset.isImm() && "expected immediate operand kind");
2637     if (isInt<11>(Offset.getImm())) {
2638       // If offset fits into 11 bits then this instruction becomes microMIPS
2639       // 16-bit unconditional branch instruction.
2640       if (inMicroMipsMode())
2641         Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM);
2642     } else {
2643       if (!isInt<17>(Offset.getImm()))
2644         Error(IDLoc, "branch target out of range");
2645       if (OffsetToAlignment(Offset.getImm(), 1LL << 1))
2646         Error(IDLoc, "branch to misaligned address");
2647       Inst.clear();
2648       Inst.setOpcode(Mips::BEQ_MM);
2649       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2650       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2651       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
2652     }
2653   }
2654   Out.EmitInstruction(Inst, *STI);
2655 
2656   // If .set reorder is active and branch instruction has a delay slot,
2657   // emit a NOP after it.
2658   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
2659   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2660     TOut.emitEmptyDelaySlot(true, IDLoc, STI);
2661 
2662   return false;
2663 }
2664 
2665 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2666                                     const MCSubtargetInfo *STI) {
2667   MipsTargetStreamer &TOut = getTargetStreamer();
2668   const MCOperand &DstRegOp = Inst.getOperand(0);
2669   assert(DstRegOp.isReg() && "expected register operand kind");
2670 
2671   const MCOperand &ImmOp = Inst.getOperand(1);
2672   assert(ImmOp.isImm() && "expected immediate operand kind");
2673 
2674   const MCOperand &MemOffsetOp = Inst.getOperand(2);
2675   assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) &&
2676          "expected immediate or expression operand");
2677 
2678   unsigned OpCode = 0;
2679   switch(Inst.getOpcode()) {
2680     case Mips::BneImm:
2681       OpCode = Mips::BNE;
2682       break;
2683     case Mips::BeqImm:
2684       OpCode = Mips::BEQ;
2685       break;
2686     default:
2687       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
2688       break;
2689   }
2690 
2691   int64_t ImmValue = ImmOp.getImm();
2692   if (ImmValue == 0)
2693     TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc,
2694                  STI);
2695   else {
2696     warnIfNoMacro(IDLoc);
2697 
2698     unsigned ATReg = getATReg(IDLoc);
2699     if (!ATReg)
2700       return true;
2701 
2702     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true,
2703                       IDLoc, Out, STI))
2704       return true;
2705 
2706     TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, STI);
2707   }
2708   return false;
2709 }
2710 
2711 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2712                                   const MCSubtargetInfo *STI, bool IsLoad,
2713                                   bool IsImmOpnd) {
2714   if (IsLoad) {
2715     expandLoadInst(Inst, IDLoc, Out, STI, IsImmOpnd);
2716     return;
2717   }
2718   expandStoreInst(Inst, IDLoc, Out, STI, IsImmOpnd);
2719 }
2720 
2721 void MipsAsmParser::expandLoadInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2722                                    const MCSubtargetInfo *STI, bool IsImmOpnd) {
2723   MipsTargetStreamer &TOut = getTargetStreamer();
2724 
2725   unsigned DstReg = Inst.getOperand(0).getReg();
2726   unsigned BaseReg = Inst.getOperand(1).getReg();
2727 
2728   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
2729   int16_t DstRegClass = Desc.OpInfo[0].RegClass;
2730   unsigned DstRegClassID =
2731       getContext().getRegisterInfo()->getRegClass(DstRegClass).getID();
2732   bool IsGPR = (DstRegClassID == Mips::GPR32RegClassID) ||
2733                (DstRegClassID == Mips::GPR64RegClassID);
2734 
2735   if (IsImmOpnd) {
2736     // Try to use DstReg as the temporary.
2737     if (IsGPR && (BaseReg != DstReg)) {
2738       TOut.emitLoadWithImmOffset(Inst.getOpcode(), DstReg, BaseReg,
2739                                  Inst.getOperand(2).getImm(), DstReg, IDLoc,
2740                                  STI);
2741       return;
2742     }
2743 
2744     // At this point we need AT to perform the expansions and we exit if it is
2745     // not available.
2746     unsigned ATReg = getATReg(IDLoc);
2747     if (!ATReg)
2748       return;
2749 
2750     TOut.emitLoadWithImmOffset(Inst.getOpcode(), DstReg, BaseReg,
2751                                Inst.getOperand(2).getImm(), ATReg, IDLoc, STI);
2752     return;
2753   }
2754 
2755   const MCExpr *ExprOffset = Inst.getOperand(2).getExpr();
2756   MCOperand LoOperand = MCOperand::createExpr(
2757       MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
2758   MCOperand HiOperand = MCOperand::createExpr(
2759       MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
2760 
2761   // Try to use DstReg as the temporary.
2762   if (IsGPR && (BaseReg != DstReg)) {
2763     TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
2764                                LoOperand, DstReg, IDLoc, STI);
2765     return;
2766   }
2767 
2768   // At this point we need AT to perform the expansions and we exit if it is
2769   // not available.
2770   unsigned ATReg = getATReg(IDLoc);
2771   if (!ATReg)
2772     return;
2773 
2774   TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
2775                              LoOperand, ATReg, IDLoc, STI);
2776 }
2777 
2778 void MipsAsmParser::expandStoreInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2779                                     const MCSubtargetInfo *STI,
2780                                     bool IsImmOpnd) {
2781   MipsTargetStreamer &TOut = getTargetStreamer();
2782 
2783   unsigned SrcReg = Inst.getOperand(0).getReg();
2784   unsigned BaseReg = Inst.getOperand(1).getReg();
2785 
2786   if (IsImmOpnd) {
2787     TOut.emitStoreWithImmOffset(Inst.getOpcode(), SrcReg, BaseReg,
2788                                 Inst.getOperand(2).getImm(),
2789                                 [&]() { return getATReg(IDLoc); }, IDLoc, STI);
2790     return;
2791   }
2792 
2793   unsigned ATReg = getATReg(IDLoc);
2794   if (!ATReg)
2795     return;
2796 
2797   const MCExpr *ExprOffset = Inst.getOperand(2).getExpr();
2798   MCOperand LoOperand = MCOperand::createExpr(
2799       MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
2800   MCOperand HiOperand = MCOperand::createExpr(
2801       MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
2802   TOut.emitStoreWithSymOffset(Inst.getOpcode(), SrcReg, BaseReg, HiOperand,
2803                               LoOperand, ATReg, IDLoc, STI);
2804 }
2805 
2806 bool MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
2807                                             MCStreamer &Out,
2808                                             const MCSubtargetInfo *STI) {
2809   unsigned OpNum = Inst.getNumOperands();
2810   unsigned Opcode = Inst.getOpcode();
2811   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
2812 
2813   assert (Inst.getOperand(OpNum - 1).isImm() &&
2814           Inst.getOperand(OpNum - 2).isReg() &&
2815           Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
2816 
2817   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
2818       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
2819       (Inst.getOperand(OpNum - 2).getReg() == Mips::SP ||
2820        Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) &&
2821       (Inst.getOperand(OpNum - 3).getReg() == Mips::RA ||
2822        Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) {
2823     // It can be implemented as SWM16 or LWM16 instruction.
2824     if (inMicroMipsMode() && hasMips32r6())
2825       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6;
2826     else
2827       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
2828   }
2829 
2830   Inst.setOpcode(NewOpcode);
2831   Out.EmitInstruction(Inst, *STI);
2832   return false;
2833 }
2834 
2835 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
2836                                        MCStreamer &Out,
2837                                        const MCSubtargetInfo *STI) {
2838   MipsTargetStreamer &TOut = getTargetStreamer();
2839   bool EmittedNoMacroWarning = false;
2840   unsigned PseudoOpcode = Inst.getOpcode();
2841   unsigned SrcReg = Inst.getOperand(0).getReg();
2842   const MCOperand &TrgOp = Inst.getOperand(1);
2843   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
2844 
2845   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
2846   bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality;
2847 
2848   unsigned TrgReg;
2849   if (TrgOp.isReg())
2850     TrgReg = TrgOp.getReg();
2851   else if (TrgOp.isImm()) {
2852     warnIfNoMacro(IDLoc);
2853     EmittedNoMacroWarning = true;
2854 
2855     TrgReg = getATReg(IDLoc);
2856     if (!TrgReg)
2857       return true;
2858 
2859     switch(PseudoOpcode) {
2860     default:
2861       llvm_unreachable("unknown opcode for branch pseudo-instruction");
2862     case Mips::BLTImmMacro:
2863       PseudoOpcode = Mips::BLT;
2864       break;
2865     case Mips::BLEImmMacro:
2866       PseudoOpcode = Mips::BLE;
2867       break;
2868     case Mips::BGEImmMacro:
2869       PseudoOpcode = Mips::BGE;
2870       break;
2871     case Mips::BGTImmMacro:
2872       PseudoOpcode = Mips::BGT;
2873       break;
2874     case Mips::BLTUImmMacro:
2875       PseudoOpcode = Mips::BLTU;
2876       break;
2877     case Mips::BLEUImmMacro:
2878       PseudoOpcode = Mips::BLEU;
2879       break;
2880     case Mips::BGEUImmMacro:
2881       PseudoOpcode = Mips::BGEU;
2882       break;
2883     case Mips::BGTUImmMacro:
2884       PseudoOpcode = Mips::BGTU;
2885       break;
2886     case Mips::BLTLImmMacro:
2887       PseudoOpcode = Mips::BLTL;
2888       break;
2889     case Mips::BLELImmMacro:
2890       PseudoOpcode = Mips::BLEL;
2891       break;
2892     case Mips::BGELImmMacro:
2893       PseudoOpcode = Mips::BGEL;
2894       break;
2895     case Mips::BGTLImmMacro:
2896       PseudoOpcode = Mips::BGTL;
2897       break;
2898     case Mips::BLTULImmMacro:
2899       PseudoOpcode = Mips::BLTUL;
2900       break;
2901     case Mips::BLEULImmMacro:
2902       PseudoOpcode = Mips::BLEUL;
2903       break;
2904     case Mips::BGEULImmMacro:
2905       PseudoOpcode = Mips::BGEUL;
2906       break;
2907     case Mips::BGTULImmMacro:
2908       PseudoOpcode = Mips::BGTUL;
2909       break;
2910     }
2911 
2912     if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(),
2913                       false, IDLoc, Out, STI))
2914       return true;
2915   }
2916 
2917   switch (PseudoOpcode) {
2918   case Mips::BLT:
2919   case Mips::BLTU:
2920   case Mips::BLTL:
2921   case Mips::BLTUL:
2922     AcceptsEquality = false;
2923     ReverseOrderSLT = false;
2924     IsUnsigned = ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL));
2925     IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL));
2926     ZeroSrcOpcode = Mips::BGTZ;
2927     ZeroTrgOpcode = Mips::BLTZ;
2928     break;
2929   case Mips::BLE:
2930   case Mips::BLEU:
2931   case Mips::BLEL:
2932   case Mips::BLEUL:
2933     AcceptsEquality = true;
2934     ReverseOrderSLT = true;
2935     IsUnsigned = ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL));
2936     IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL));
2937     ZeroSrcOpcode = Mips::BGEZ;
2938     ZeroTrgOpcode = Mips::BLEZ;
2939     break;
2940   case Mips::BGE:
2941   case Mips::BGEU:
2942   case Mips::BGEL:
2943   case Mips::BGEUL:
2944     AcceptsEquality = true;
2945     ReverseOrderSLT = false;
2946     IsUnsigned = ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL));
2947     IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL));
2948     ZeroSrcOpcode = Mips::BLEZ;
2949     ZeroTrgOpcode = Mips::BGEZ;
2950     break;
2951   case Mips::BGT:
2952   case Mips::BGTU:
2953   case Mips::BGTL:
2954   case Mips::BGTUL:
2955     AcceptsEquality = false;
2956     ReverseOrderSLT = true;
2957     IsUnsigned = ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL));
2958     IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL));
2959     ZeroSrcOpcode = Mips::BLTZ;
2960     ZeroTrgOpcode = Mips::BGTZ;
2961     break;
2962   default:
2963     llvm_unreachable("unknown opcode for branch pseudo-instruction");
2964   }
2965 
2966   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
2967   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
2968   if (IsSrcRegZero && IsTrgRegZero) {
2969     // FIXME: All of these Opcode-specific if's are needed for compatibility
2970     // with GAS' behaviour. However, they may not generate the most efficient
2971     // code in some circumstances.
2972     if (PseudoOpcode == Mips::BLT) {
2973       TOut.emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
2974                   IDLoc, STI);
2975       return false;
2976     }
2977     if (PseudoOpcode == Mips::BLE) {
2978       TOut.emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
2979                   IDLoc, STI);
2980       Warning(IDLoc, "branch is always taken");
2981       return false;
2982     }
2983     if (PseudoOpcode == Mips::BGE) {
2984       TOut.emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
2985                   IDLoc, STI);
2986       Warning(IDLoc, "branch is always taken");
2987       return false;
2988     }
2989     if (PseudoOpcode == Mips::BGT) {
2990       TOut.emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
2991                   IDLoc, STI);
2992       return false;
2993     }
2994     if (PseudoOpcode == Mips::BGTU) {
2995       TOut.emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO,
2996                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
2997       return false;
2998     }
2999     if (AcceptsEquality) {
3000       // If both registers are $0 and the pseudo-branch accepts equality, it
3001       // will always be taken, so we emit an unconditional branch.
3002       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3003                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3004       Warning(IDLoc, "branch is always taken");
3005       return false;
3006     }
3007     // If both registers are $0 and the pseudo-branch does not accept
3008     // equality, it will never be taken, so we don't have to emit anything.
3009     return false;
3010   }
3011   if (IsSrcRegZero || IsTrgRegZero) {
3012     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
3013         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
3014       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
3015       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
3016       // the pseudo-branch will never be taken, so we don't emit anything.
3017       // This only applies to unsigned pseudo-branches.
3018       return false;
3019     }
3020     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
3021         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
3022       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
3023       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
3024       // the pseudo-branch will always be taken, so we emit an unconditional
3025       // branch.
3026       // This only applies to unsigned pseudo-branches.
3027       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3028                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3029       Warning(IDLoc, "branch is always taken");
3030       return false;
3031     }
3032     if (IsUnsigned) {
3033       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
3034       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
3035       // the pseudo-branch will be taken only when the non-zero register is
3036       // different from 0, so we emit a BNEZ.
3037       //
3038       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
3039       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
3040       // the pseudo-branch will be taken only when the non-zero register is
3041       // equal to 0, so we emit a BEQZ.
3042       //
3043       // Because only BLEU and BGEU branch on equality, we can use the
3044       // AcceptsEquality variable to decide when to emit the BEQZ.
3045       TOut.emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE,
3046                    IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO,
3047                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3048       return false;
3049     }
3050     // If we have a signed pseudo-branch and one of the registers is $0,
3051     // we can use an appropriate compare-to-zero branch. We select which one
3052     // to use in the switch statement above.
3053     TOut.emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode,
3054                 IsSrcRegZero ? TrgReg : SrcReg,
3055                 MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3056     return false;
3057   }
3058 
3059   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
3060   // expansions. If it is not available, we return.
3061   unsigned ATRegNum = getATReg(IDLoc);
3062   if (!ATRegNum)
3063     return true;
3064 
3065   if (!EmittedNoMacroWarning)
3066     warnIfNoMacro(IDLoc);
3067 
3068   // SLT fits well with 2 of our 4 pseudo-branches:
3069   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
3070   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
3071   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
3072   // This is accomplished by using a BNEZ with the result of the SLT.
3073   //
3074   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
3075   // and BLE with BGT), so we change the BNEZ into a a BEQZ.
3076   // Because only BGE and BLE branch on equality, we can use the
3077   // AcceptsEquality variable to decide when to emit the BEQZ.
3078   // Note that the order of the SLT arguments doesn't change between
3079   // opposites.
3080   //
3081   // The same applies to the unsigned variants, except that SLTu is used
3082   // instead of SLT.
3083   TOut.emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum,
3084                ReverseOrderSLT ? TrgReg : SrcReg,
3085                ReverseOrderSLT ? SrcReg : TrgReg, IDLoc, STI);
3086 
3087   TOut.emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL)
3088                         : (AcceptsEquality ? Mips::BEQ : Mips::BNE),
3089                ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
3090                STI);
3091   return false;
3092 }
3093 
3094 bool MipsAsmParser::expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3095                               const MCSubtargetInfo *STI, const bool IsMips64,
3096                               const bool Signed) {
3097   MipsTargetStreamer &TOut = getTargetStreamer();
3098 
3099   warnIfNoMacro(IDLoc);
3100 
3101   const MCOperand &RdRegOp = Inst.getOperand(0);
3102   assert(RdRegOp.isReg() && "expected register operand kind");
3103   unsigned RdReg = RdRegOp.getReg();
3104 
3105   const MCOperand &RsRegOp = Inst.getOperand(1);
3106   assert(RsRegOp.isReg() && "expected register operand kind");
3107   unsigned RsReg = RsRegOp.getReg();
3108 
3109   const MCOperand &RtRegOp = Inst.getOperand(2);
3110   assert(RtRegOp.isReg() && "expected register operand kind");
3111   unsigned RtReg = RtRegOp.getReg();
3112   unsigned DivOp;
3113   unsigned ZeroReg;
3114 
3115   if (IsMips64) {
3116     DivOp = Signed ? Mips::DSDIV : Mips::DUDIV;
3117     ZeroReg = Mips::ZERO_64;
3118   } else {
3119     DivOp = Signed ? Mips::SDIV : Mips::UDIV;
3120     ZeroReg = Mips::ZERO;
3121   }
3122 
3123   bool UseTraps = useTraps();
3124 
3125   if (RsReg == Mips::ZERO || RsReg == Mips::ZERO_64) {
3126     if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)
3127       Warning(IDLoc, "dividing zero by zero");
3128     if (IsMips64) {
3129       if (Signed && (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) {
3130         if (UseTraps) {
3131           TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
3132           return false;
3133         }
3134 
3135         TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3136         return false;
3137       }
3138     } else {
3139       TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
3140       return false;
3141     }
3142   }
3143 
3144   if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) {
3145     Warning(IDLoc, "division by zero");
3146     if (Signed) {
3147       if (UseTraps) {
3148         TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
3149         return false;
3150       }
3151 
3152       TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3153       return false;
3154     }
3155   }
3156 
3157   // FIXME: The values for these two BranchTarget variables may be different in
3158   // micromips. These magic numbers need to be removed.
3159   unsigned BranchTargetNoTraps;
3160   unsigned BranchTarget;
3161 
3162   if (UseTraps) {
3163     BranchTarget = IsMips64 ? 12 : 8;
3164     TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
3165   } else {
3166     BranchTarget = IsMips64 ? 20 : 16;
3167     BranchTargetNoTraps = 8;
3168     // Branch to the li instruction.
3169     TOut.emitRRI(Mips::BNE, RtReg, ZeroReg, BranchTargetNoTraps, IDLoc, STI);
3170   }
3171 
3172   TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
3173 
3174   if (!UseTraps)
3175     TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3176 
3177   if (!Signed) {
3178     TOut.emitR(Mips::MFLO, RdReg, IDLoc, STI);
3179     return false;
3180   }
3181 
3182   unsigned ATReg = getATReg(IDLoc);
3183   if (!ATReg)
3184     return true;
3185 
3186   TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, STI);
3187   if (IsMips64) {
3188     // Branch to the mflo instruction.
3189     TOut.emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, STI);
3190     TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, STI);
3191     TOut.emitRRI(Mips::DSLL32, ATReg, ATReg, 0x1f, IDLoc, STI);
3192   } else {
3193     // Branch to the mflo instruction.
3194     TOut.emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, STI);
3195     TOut.emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, STI);
3196   }
3197 
3198   if (UseTraps)
3199     TOut.emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, STI);
3200   else {
3201     // Branch to the mflo instruction.
3202     TOut.emitRRI(Mips::BNE, RsReg, ATReg, BranchTargetNoTraps, IDLoc, STI);
3203     TOut.emitRRI(Mips::SLL, ZeroReg, ZeroReg, 0, IDLoc, STI);
3204     TOut.emitII(Mips::BREAK, 0x6, 0, IDLoc, STI);
3205   }
3206   TOut.emitR(Mips::MFLO, RdReg, IDLoc, STI);
3207   return false;
3208 }
3209 
3210 bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU,
3211                                 SMLoc IDLoc, MCStreamer &Out,
3212                                 const MCSubtargetInfo *STI) {
3213   MipsTargetStreamer &TOut = getTargetStreamer();
3214 
3215   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
3216   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() &&
3217          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
3218 
3219   unsigned FirstReg = Inst.getOperand(0).getReg();
3220   unsigned SecondReg = Inst.getOperand(1).getReg();
3221   unsigned ThirdReg = Inst.getOperand(2).getReg();
3222 
3223   if (hasMips1() && !hasMips2()) {
3224     unsigned ATReg = getATReg(IDLoc);
3225     if (!ATReg)
3226       return true;
3227     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
3228     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
3229     TOut.emitNop(IDLoc, STI);
3230     TOut.emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, STI);
3231     TOut.emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, STI);
3232     TOut.emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, STI);
3233     TOut.emitNop(IDLoc, STI);
3234     TOut.emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32)
3235                          : Mips::CVT_W_S,
3236                 FirstReg, SecondReg, IDLoc, STI);
3237     TOut.emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, STI);
3238     TOut.emitNop(IDLoc, STI);
3239     return false;
3240   }
3241 
3242   TOut.emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32)
3243                        : Mips::TRUNC_W_S,
3244               FirstReg, SecondReg, IDLoc, STI);
3245 
3246   return false;
3247 }
3248 
3249 bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
3250                               MCStreamer &Out, const MCSubtargetInfo *STI) {
3251   MipsTargetStreamer &TOut = getTargetStreamer();
3252 
3253   if (hasMips32r6() || hasMips64r6()) {
3254     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3255     return false;
3256   }
3257 
3258   warnIfNoMacro(IDLoc);
3259 
3260   const MCOperand &DstRegOp = Inst.getOperand(0);
3261   assert(DstRegOp.isReg() && "expected register operand kind");
3262 
3263   const MCOperand &SrcRegOp = Inst.getOperand(1);
3264   assert(SrcRegOp.isReg() && "expected register operand kind");
3265 
3266   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3267   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3268 
3269   unsigned DstReg = DstRegOp.getReg();
3270   unsigned SrcReg = SrcRegOp.getReg();
3271   int64_t OffsetValue = OffsetImmOp.getImm();
3272 
3273   // NOTE: We always need AT for ULHU, as it is always used as the source
3274   // register for one of the LBu's.
3275   unsigned ATReg = getATReg(IDLoc);
3276   if (!ATReg)
3277     return true;
3278 
3279   // When the value of offset+1 does not fit in 16 bits, we have to load the
3280   // offset in AT, (D)ADDu the original source register (if there was one), and
3281   // then use AT as the source register for the 2 generated LBu's.
3282   bool LoadedOffsetInAT = false;
3283   if (!isInt<16>(OffsetValue + 1) || !isInt<16>(OffsetValue)) {
3284     LoadedOffsetInAT = true;
3285 
3286     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3287                       true, IDLoc, Out, STI))
3288       return true;
3289 
3290     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3291     // because it will make our output more similar to GAS'. For example,
3292     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3293     // instead of just an "ori $1, $9, 32768".
3294     // NOTE: If there is no source register specified in the ULHU, the parser
3295     // will interpret it as $0.
3296     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3297       TOut.emitAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), STI);
3298   }
3299 
3300   unsigned FirstLbuDstReg = LoadedOffsetInAT ? DstReg : ATReg;
3301   unsigned SecondLbuDstReg = LoadedOffsetInAT ? ATReg : DstReg;
3302   unsigned LbuSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3303 
3304   int64_t FirstLbuOffset = 0, SecondLbuOffset = 0;
3305   if (isLittle()) {
3306     FirstLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3307     SecondLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3308   } else {
3309     FirstLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3310     SecondLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3311   }
3312 
3313   unsigned SllReg = LoadedOffsetInAT ? DstReg : ATReg;
3314 
3315   TOut.emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg,
3316                FirstLbuOffset, IDLoc, STI);
3317 
3318   TOut.emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondLbuOffset, IDLoc,
3319                STI);
3320 
3321   TOut.emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, STI);
3322 
3323   TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI);
3324 
3325   return false;
3326 }
3327 
3328 bool MipsAsmParser::expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3329                               const MCSubtargetInfo *STI) {
3330   MipsTargetStreamer &TOut = getTargetStreamer();
3331 
3332   if (hasMips32r6() || hasMips64r6()) {
3333     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3334     return false;
3335   }
3336 
3337   const MCOperand &DstRegOp = Inst.getOperand(0);
3338   assert(DstRegOp.isReg() && "expected register operand kind");
3339 
3340   const MCOperand &SrcRegOp = Inst.getOperand(1);
3341   assert(SrcRegOp.isReg() && "expected register operand kind");
3342 
3343   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3344   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3345 
3346   unsigned SrcReg = SrcRegOp.getReg();
3347   int64_t OffsetValue = OffsetImmOp.getImm();
3348   unsigned ATReg = 0;
3349 
3350   // When the value of offset+3 does not fit in 16 bits, we have to load the
3351   // offset in AT, (D)ADDu the original source register (if there was one), and
3352   // then use AT as the source register for the generated LWL and LWR.
3353   bool LoadedOffsetInAT = false;
3354   if (!isInt<16>(OffsetValue + 3) || !isInt<16>(OffsetValue)) {
3355     ATReg = getATReg(IDLoc);
3356     if (!ATReg)
3357       return true;
3358     LoadedOffsetInAT = true;
3359 
3360     warnIfNoMacro(IDLoc);
3361 
3362     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3363                       true, IDLoc, Out, STI))
3364       return true;
3365 
3366     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3367     // because it will make our output more similar to GAS'. For example,
3368     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3369     // instead of just an "ori $1, $9, 32768".
3370     // NOTE: If there is no source register specified in the ULW, the parser
3371     // will interpret it as $0.
3372     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3373       TOut.emitAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), STI);
3374   }
3375 
3376   unsigned FinalSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3377   int64_t LeftLoadOffset = 0, RightLoadOffset  = 0;
3378   if (isLittle()) {
3379     LeftLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3380     RightLoadOffset  = LoadedOffsetInAT ? 0 : OffsetValue;
3381   } else {
3382     LeftLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3383     RightLoadOffset  = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3384   }
3385 
3386   TOut.emitRRI(Mips::LWL, DstRegOp.getReg(), FinalSrcReg, LeftLoadOffset, IDLoc,
3387                STI);
3388 
3389   TOut.emitRRI(Mips::LWR, DstRegOp.getReg(), FinalSrcReg, RightLoadOffset,
3390                IDLoc, STI);
3391 
3392   return false;
3393 }
3394 
3395 bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
3396                                          MCStreamer &Out,
3397                                          const MCSubtargetInfo *STI) {
3398   MipsTargetStreamer &TOut = getTargetStreamer();
3399 
3400   assert (Inst.getNumOperands() == 3 && "Invalid operand count");
3401   assert (Inst.getOperand(0).isReg() &&
3402           Inst.getOperand(1).isReg() &&
3403           Inst.getOperand(2).isImm() && "Invalid instruction operand.");
3404 
3405   unsigned ATReg = Mips::NoRegister;
3406   unsigned FinalDstReg = Mips::NoRegister;
3407   unsigned DstReg = Inst.getOperand(0).getReg();
3408   unsigned SrcReg = Inst.getOperand(1).getReg();
3409   int64_t ImmValue = Inst.getOperand(2).getImm();
3410 
3411   bool Is32Bit = isInt<32>(ImmValue) || isUInt<32>(ImmValue);
3412 
3413   unsigned FinalOpcode = Inst.getOpcode();
3414 
3415   if (DstReg == SrcReg) {
3416     ATReg = getATReg(Inst.getLoc());
3417     if (!ATReg)
3418       return true;
3419     FinalDstReg = DstReg;
3420     DstReg = ATReg;
3421   }
3422 
3423   if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false, Inst.getLoc(), Out, STI)) {
3424     switch (FinalOpcode) {
3425     default:
3426       llvm_unreachable("unimplemented expansion");
3427     case (Mips::ADDi):
3428       FinalOpcode = Mips::ADD;
3429       break;
3430     case (Mips::ADDiu):
3431       FinalOpcode = Mips::ADDu;
3432       break;
3433     case (Mips::ANDi):
3434       FinalOpcode = Mips::AND;
3435       break;
3436     case (Mips::NORImm):
3437       FinalOpcode = Mips::NOR;
3438       break;
3439     case (Mips::ORi):
3440       FinalOpcode = Mips::OR;
3441       break;
3442     case (Mips::SLTi):
3443       FinalOpcode = Mips::SLT;
3444       break;
3445     case (Mips::SLTiu):
3446       FinalOpcode = Mips::SLTu;
3447       break;
3448     case (Mips::XORi):
3449       FinalOpcode = Mips::XOR;
3450       break;
3451     }
3452 
3453     if (FinalDstReg == Mips::NoRegister)
3454       TOut.emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, STI);
3455     else
3456       TOut.emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc, STI);
3457     return false;
3458   }
3459   return true;
3460 }
3461 
3462 bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3463                                    const MCSubtargetInfo *STI) {
3464   MipsTargetStreamer &TOut = getTargetStreamer();
3465   unsigned ATReg = Mips::NoRegister;
3466   unsigned DReg = Inst.getOperand(0).getReg();
3467   unsigned SReg = Inst.getOperand(1).getReg();
3468   unsigned TReg = Inst.getOperand(2).getReg();
3469   unsigned TmpReg = DReg;
3470 
3471   unsigned FirstShift = Mips::NOP;
3472   unsigned SecondShift = Mips::NOP;
3473 
3474   if (hasMips32r2()) {
3475 
3476     if (DReg == SReg) {
3477       TmpReg = getATReg(Inst.getLoc());
3478       if (!TmpReg)
3479         return true;
3480     }
3481 
3482     if (Inst.getOpcode() == Mips::ROL) {
3483       TOut.emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3484       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
3485       return false;
3486     }
3487 
3488     if (Inst.getOpcode() == Mips::ROR) {
3489       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
3490       return false;
3491     }
3492 
3493     return true;
3494   }
3495 
3496   if (hasMips32()) {
3497 
3498     switch (Inst.getOpcode()) {
3499     default:
3500       llvm_unreachable("unexpected instruction opcode");
3501     case Mips::ROL:
3502       FirstShift = Mips::SRLV;
3503       SecondShift = Mips::SLLV;
3504       break;
3505     case Mips::ROR:
3506       FirstShift = Mips::SLLV;
3507       SecondShift = Mips::SRLV;
3508       break;
3509     }
3510 
3511     ATReg = getATReg(Inst.getLoc());
3512     if (!ATReg)
3513       return true;
3514 
3515     TOut.emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3516     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
3517     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
3518     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3519 
3520     return false;
3521   }
3522 
3523   return true;
3524 }
3525 
3526 bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc,
3527                                       MCStreamer &Out,
3528                                       const MCSubtargetInfo *STI) {
3529   MipsTargetStreamer &TOut = getTargetStreamer();
3530   unsigned ATReg = Mips::NoRegister;
3531   unsigned DReg = Inst.getOperand(0).getReg();
3532   unsigned SReg = Inst.getOperand(1).getReg();
3533   int64_t ImmValue = Inst.getOperand(2).getImm();
3534 
3535   unsigned FirstShift = Mips::NOP;
3536   unsigned SecondShift = Mips::NOP;
3537 
3538   if (hasMips32r2()) {
3539 
3540     if (Inst.getOpcode() == Mips::ROLImm) {
3541       uint64_t MaxShift = 32;
3542       uint64_t ShiftValue = ImmValue;
3543       if (ImmValue != 0)
3544         ShiftValue = MaxShift - ImmValue;
3545       TOut.emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
3546       return false;
3547     }
3548 
3549     if (Inst.getOpcode() == Mips::RORImm) {
3550       TOut.emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), STI);
3551       return false;
3552     }
3553 
3554     return true;
3555   }
3556 
3557   if (hasMips32()) {
3558 
3559     if (ImmValue == 0) {
3560       TOut.emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), STI);
3561       return false;
3562     }
3563 
3564     switch (Inst.getOpcode()) {
3565     default:
3566       llvm_unreachable("unexpected instruction opcode");
3567     case Mips::ROLImm:
3568       FirstShift = Mips::SLL;
3569       SecondShift = Mips::SRL;
3570       break;
3571     case Mips::RORImm:
3572       FirstShift = Mips::SRL;
3573       SecondShift = Mips::SLL;
3574       break;
3575     }
3576 
3577     ATReg = getATReg(Inst.getLoc());
3578     if (!ATReg)
3579       return true;
3580 
3581     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), STI);
3582     TOut.emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), STI);
3583     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3584 
3585     return false;
3586   }
3587 
3588   return true;
3589 }
3590 
3591 bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3592                                     const MCSubtargetInfo *STI) {
3593   MipsTargetStreamer &TOut = getTargetStreamer();
3594   unsigned ATReg = Mips::NoRegister;
3595   unsigned DReg = Inst.getOperand(0).getReg();
3596   unsigned SReg = Inst.getOperand(1).getReg();
3597   unsigned TReg = Inst.getOperand(2).getReg();
3598   unsigned TmpReg = DReg;
3599 
3600   unsigned FirstShift = Mips::NOP;
3601   unsigned SecondShift = Mips::NOP;
3602 
3603   if (hasMips64r2()) {
3604 
3605     if (TmpReg == SReg) {
3606       TmpReg = getATReg(Inst.getLoc());
3607       if (!TmpReg)
3608         return true;
3609     }
3610 
3611     if (Inst.getOpcode() == Mips::DROL) {
3612       TOut.emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3613       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
3614       return false;
3615     }
3616 
3617     if (Inst.getOpcode() == Mips::DROR) {
3618       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
3619       return false;
3620     }
3621 
3622     return true;
3623   }
3624 
3625   if (hasMips64()) {
3626 
3627     switch (Inst.getOpcode()) {
3628     default:
3629       llvm_unreachable("unexpected instruction opcode");
3630     case Mips::DROL:
3631       FirstShift = Mips::DSRLV;
3632       SecondShift = Mips::DSLLV;
3633       break;
3634     case Mips::DROR:
3635       FirstShift = Mips::DSLLV;
3636       SecondShift = Mips::DSRLV;
3637       break;
3638     }
3639 
3640     ATReg = getATReg(Inst.getLoc());
3641     if (!ATReg)
3642       return true;
3643 
3644     TOut.emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3645     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
3646     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
3647     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3648 
3649     return false;
3650   }
3651 
3652   return true;
3653 }
3654 
3655 bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
3656                                        MCStreamer &Out,
3657                                        const MCSubtargetInfo *STI) {
3658   MipsTargetStreamer &TOut = getTargetStreamer();
3659   unsigned ATReg = Mips::NoRegister;
3660   unsigned DReg = Inst.getOperand(0).getReg();
3661   unsigned SReg = Inst.getOperand(1).getReg();
3662   int64_t ImmValue = Inst.getOperand(2).getImm() % 64;
3663 
3664   unsigned FirstShift = Mips::NOP;
3665   unsigned SecondShift = Mips::NOP;
3666 
3667   MCInst TmpInst;
3668 
3669   if (hasMips64r2()) {
3670 
3671     unsigned FinalOpcode = Mips::NOP;
3672     if (ImmValue == 0)
3673       FinalOpcode = Mips::DROTR;
3674     else if (ImmValue % 32 == 0)
3675       FinalOpcode = Mips::DROTR32;
3676     else if ((ImmValue >= 1) && (ImmValue <= 32)) {
3677       if (Inst.getOpcode() == Mips::DROLImm)
3678         FinalOpcode = Mips::DROTR32;
3679       else
3680         FinalOpcode = Mips::DROTR;
3681     } else if (ImmValue >= 33) {
3682       if (Inst.getOpcode() == Mips::DROLImm)
3683         FinalOpcode = Mips::DROTR;
3684       else
3685         FinalOpcode = Mips::DROTR32;
3686     }
3687 
3688     uint64_t ShiftValue = ImmValue % 32;
3689     if (Inst.getOpcode() == Mips::DROLImm)
3690       ShiftValue = (32 - ImmValue % 32) % 32;
3691 
3692     TOut.emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
3693 
3694     return false;
3695   }
3696 
3697   if (hasMips64()) {
3698 
3699     if (ImmValue == 0) {
3700       TOut.emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), STI);
3701       return false;
3702     }
3703 
3704     switch (Inst.getOpcode()) {
3705     default:
3706       llvm_unreachable("unexpected instruction opcode");
3707     case Mips::DROLImm:
3708       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3709         FirstShift = Mips::DSLL;
3710         SecondShift = Mips::DSRL32;
3711       }
3712       if (ImmValue == 32) {
3713         FirstShift = Mips::DSLL32;
3714         SecondShift = Mips::DSRL32;
3715       }
3716       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3717         FirstShift = Mips::DSLL32;
3718         SecondShift = Mips::DSRL;
3719       }
3720       break;
3721     case Mips::DRORImm:
3722       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3723         FirstShift = Mips::DSRL;
3724         SecondShift = Mips::DSLL32;
3725       }
3726       if (ImmValue == 32) {
3727         FirstShift = Mips::DSRL32;
3728         SecondShift = Mips::DSLL32;
3729       }
3730       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3731         FirstShift = Mips::DSRL32;
3732         SecondShift = Mips::DSLL;
3733       }
3734       break;
3735     }
3736 
3737     ATReg = getATReg(Inst.getLoc());
3738     if (!ATReg)
3739       return true;
3740 
3741     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), STI);
3742     TOut.emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32,
3743                  Inst.getLoc(), STI);
3744     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3745 
3746     return false;
3747   }
3748 
3749   return true;
3750 }
3751 
3752 bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3753                               const MCSubtargetInfo *STI) {
3754   MipsTargetStreamer &TOut = getTargetStreamer();
3755   unsigned FirstRegOp = Inst.getOperand(0).getReg();
3756   unsigned SecondRegOp = Inst.getOperand(1).getReg();
3757 
3758   TOut.emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, STI);
3759   if (FirstRegOp != SecondRegOp)
3760     TOut.emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, STI);
3761   else
3762     TOut.emitEmptyDelaySlot(false, IDLoc, STI);
3763   TOut.emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, STI);
3764 
3765   return false;
3766 }
3767 
3768 unsigned
3769 MipsAsmParser::checkEarlyTargetMatchPredicate(MCInst &Inst,
3770                                               const OperandVector &Operands) {
3771   switch (Inst.getOpcode()) {
3772   default:
3773     return Match_Success;
3774   case Mips::DATI:
3775   case Mips::DAHI:
3776     if (static_cast<MipsOperand &>(*Operands[1])
3777             .isValidForTie(static_cast<MipsOperand &>(*Operands[2])))
3778       return Match_Success;
3779     return Match_RequiresSameSrcAndDst;
3780   }
3781 }
3782 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3783   switch (Inst.getOpcode()) {
3784   // As described by the Mips32r2 spec, the registers Rd and Rs for
3785   // jalr.hb must be different.
3786   // It also applies for registers Rt and Rs of microMIPSr6 jalrc.hb instruction
3787   // and registers Rd and Base for microMIPS lwp instruction
3788   case Mips::JALR_HB:
3789   case Mips::JALRC_HB_MMR6:
3790   case Mips::JALRC_MMR6:
3791     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
3792       return Match_RequiresDifferentSrcAndDst;
3793     return Match_Success;
3794   case Mips::LWP_MM:
3795   case Mips::LWP_MMR6:
3796     if (Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg())
3797       return Match_RequiresDifferentSrcAndDst;
3798     return Match_Success;
3799   // As described the MIPSR6 spec, the compact branches that compare registers
3800   // must:
3801   // a) Not use the zero register.
3802   // b) Not use the same register twice.
3803   // c) rs < rt for bnec, beqc.
3804   //    NB: For this case, the encoding will swap the operands as their
3805   //    ordering doesn't matter. GAS performs this transformation  too.
3806   //    Hence, that constraint does not have to be enforced.
3807   //
3808   // The compact branches that branch iff the signed addition of two registers
3809   // would overflow must have rs >= rt. That can be handled like beqc/bnec with
3810   // operand swapping. They do not have restriction of using the zero register.
3811   case Mips::BLEZC:
3812   case Mips::BGEZC:
3813   case Mips::BGTZC:
3814   case Mips::BLTZC:
3815   case Mips::BEQZC:
3816   case Mips::BNEZC:
3817   case Mips::BLEZC64:
3818   case Mips::BGEZC64:
3819   case Mips::BGTZC64:
3820   case Mips::BLTZC64:
3821   case Mips::BEQZC64:
3822   case Mips::BNEZC64:
3823     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
3824         Inst.getOperand(0).getReg() == Mips::ZERO_64)
3825       return Match_RequiresNoZeroRegister;
3826     return Match_Success;
3827   case Mips::BGEC:
3828   case Mips::BLTC:
3829   case Mips::BGEUC:
3830   case Mips::BLTUC:
3831   case Mips::BEQC:
3832   case Mips::BNEC:
3833   case Mips::BGEC64:
3834   case Mips::BLTC64:
3835   case Mips::BGEUC64:
3836   case Mips::BLTUC64:
3837   case Mips::BEQC64:
3838   case Mips::BNEC64:
3839     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
3840         Inst.getOperand(0).getReg() == Mips::ZERO_64)
3841       return Match_RequiresNoZeroRegister;
3842     if (Inst.getOperand(1).getReg() == Mips::ZERO ||
3843         Inst.getOperand(1).getReg() == Mips::ZERO_64)
3844       return Match_RequiresNoZeroRegister;
3845     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
3846       return Match_RequiresDifferentOperands;
3847     return Match_Success;
3848   default:
3849     return Match_Success;
3850   }
3851 }
3852 
3853 static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands,
3854                             uint64_t ErrorInfo) {
3855   if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) {
3856     SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3857     if (ErrorLoc == SMLoc())
3858       return Loc;
3859     return ErrorLoc;
3860   }
3861   return Loc;
3862 }
3863 
3864 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3865                                             OperandVector &Operands,
3866                                             MCStreamer &Out,
3867                                             uint64_t &ErrorInfo,
3868                                             bool MatchingInlineAsm) {
3869 
3870   MCInst Inst;
3871   unsigned MatchResult =
3872       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
3873 
3874   switch (MatchResult) {
3875   case Match_Success: {
3876     if (processInstruction(Inst, IDLoc, Out, STI))
3877       return true;
3878     return false;
3879   }
3880   case Match_MissingFeature:
3881     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3882     return true;
3883   case Match_InvalidOperand: {
3884     SMLoc ErrorLoc = IDLoc;
3885     if (ErrorInfo != ~0ULL) {
3886       if (ErrorInfo >= Operands.size())
3887         return Error(IDLoc, "too few operands for instruction");
3888 
3889       ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3890       if (ErrorLoc == SMLoc())
3891         ErrorLoc = IDLoc;
3892     }
3893 
3894     return Error(ErrorLoc, "invalid operand for instruction");
3895   }
3896   case Match_MnemonicFail:
3897     return Error(IDLoc, "invalid instruction");
3898   case Match_RequiresDifferentSrcAndDst:
3899     return Error(IDLoc, "source and destination must be different");
3900   case Match_RequiresDifferentOperands:
3901     return Error(IDLoc, "registers must be different");
3902   case Match_RequiresNoZeroRegister:
3903     return Error(IDLoc, "invalid operand ($zero) for instruction");
3904   case Match_RequiresSameSrcAndDst:
3905     return Error(IDLoc, "source and destination must match");
3906   case Match_Immz:
3907     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'");
3908   case Match_UImm1_0:
3909     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3910                  "expected 1-bit unsigned immediate");
3911   case Match_UImm2_0:
3912     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3913                  "expected 2-bit unsigned immediate");
3914   case Match_UImm2_1:
3915     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3916                  "expected immediate in range 1 .. 4");
3917   case Match_UImm3_0:
3918     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3919                  "expected 3-bit unsigned immediate");
3920   case Match_UImm4_0:
3921     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3922                  "expected 4-bit unsigned immediate");
3923   case Match_SImm4_0:
3924     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3925                  "expected 4-bit signed immediate");
3926   case Match_UImm5_0:
3927     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3928                  "expected 5-bit unsigned immediate");
3929   case Match_SImm5_0:
3930     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3931                  "expected 5-bit signed immediate");
3932   case Match_UImm5_1:
3933     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3934                  "expected immediate in range 1 .. 32");
3935   case Match_UImm5_32:
3936     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3937                  "expected immediate in range 32 .. 63");
3938   case Match_UImm5_33:
3939     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3940                  "expected immediate in range 33 .. 64");
3941   case Match_UImm5_0_Report_UImm6:
3942     // This is used on UImm5 operands that have a corresponding UImm5_32
3943     // operand to avoid confusing the user.
3944     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3945                  "expected 6-bit unsigned immediate");
3946   case Match_UImm5_Lsl2:
3947     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3948                  "expected both 7-bit unsigned immediate and multiple of 4");
3949   case Match_UImmRange2_64:
3950     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3951                  "expected immediate in range 2 .. 64");
3952   case Match_UImm6_0:
3953     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3954                  "expected 6-bit unsigned immediate");
3955   case Match_UImm6_Lsl2:
3956     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3957                  "expected both 8-bit unsigned immediate and multiple of 4");
3958   case Match_SImm6_0:
3959     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3960                  "expected 6-bit signed immediate");
3961   case Match_UImm7_0:
3962     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3963                  "expected 7-bit unsigned immediate");
3964   case Match_UImm7_N1:
3965     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3966                  "expected immediate in range -1 .. 126");
3967   case Match_SImm7_Lsl2:
3968     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3969                  "expected both 9-bit signed immediate and multiple of 4");
3970   case Match_UImm8_0:
3971     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3972                  "expected 8-bit unsigned immediate");
3973   case Match_UImm10_0:
3974     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3975                  "expected 10-bit unsigned immediate");
3976   case Match_SImm10_0:
3977     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3978                  "expected 10-bit signed immediate");
3979   case Match_SImm11_0:
3980     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3981                  "expected 11-bit signed immediate");
3982   case Match_UImm16:
3983   case Match_UImm16_Relaxed:
3984     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3985                  "expected 16-bit unsigned immediate");
3986   case Match_SImm16:
3987   case Match_SImm16_Relaxed:
3988     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3989                  "expected 16-bit signed immediate");
3990   case Match_UImm20_0:
3991     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3992                  "expected 20-bit unsigned immediate");
3993   case Match_UImm26_0:
3994     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3995                  "expected 26-bit unsigned immediate");
3996   case Match_SImm32:
3997   case Match_SImm32_Relaxed:
3998     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3999                  "expected 32-bit signed immediate");
4000   case Match_MemSImm9:
4001     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4002                  "expected memory with 9-bit signed offset");
4003   case Match_MemSImm10:
4004     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4005                  "expected memory with 10-bit signed offset");
4006   case Match_MemSImm10Lsl1:
4007     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4008                  "expected memory with 11-bit signed offset and multiple of 2");
4009   case Match_MemSImm10Lsl2:
4010     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4011                  "expected memory with 12-bit signed offset and multiple of 4");
4012   case Match_MemSImm10Lsl3:
4013     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4014                  "expected memory with 13-bit signed offset and multiple of 8");
4015   case Match_MemSImm11:
4016     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4017                  "expected memory with 11-bit signed offset");
4018   case Match_MemSImm12:
4019     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4020                  "expected memory with 12-bit signed offset");
4021   case Match_MemSImm16:
4022     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4023                  "expected memory with 16-bit signed offset");
4024   }
4025 
4026   llvm_unreachable("Implement any new match types added!");
4027 }
4028 
4029 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
4030   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
4031     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
4032                      ") without \".set noat\"");
4033 }
4034 
4035 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
4036   if (!AssemblerOptions.back()->isMacro())
4037     Warning(Loc, "macro instruction expanded into multiple instructions");
4038 }
4039 
4040 void
4041 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
4042                                      SMRange Range, bool ShowColors) {
4043   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
4044                                   Range, SMFixIt(Range, FixMsg),
4045                                   ShowColors);
4046 }
4047 
4048 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
4049   int CC;
4050 
4051   CC = StringSwitch<unsigned>(Name)
4052            .Case("zero", 0)
4053            .Case("at", 1)
4054            .Case("a0", 4)
4055            .Case("a1", 5)
4056            .Case("a2", 6)
4057            .Case("a3", 7)
4058            .Case("v0", 2)
4059            .Case("v1", 3)
4060            .Case("s0", 16)
4061            .Case("s1", 17)
4062            .Case("s2", 18)
4063            .Case("s3", 19)
4064            .Case("s4", 20)
4065            .Case("s5", 21)
4066            .Case("s6", 22)
4067            .Case("s7", 23)
4068            .Case("k0", 26)
4069            .Case("k1", 27)
4070            .Case("gp", 28)
4071            .Case("sp", 29)
4072            .Case("fp", 30)
4073            .Case("s8", 30)
4074            .Case("ra", 31)
4075            .Case("t0", 8)
4076            .Case("t1", 9)
4077            .Case("t2", 10)
4078            .Case("t3", 11)
4079            .Case("t4", 12)
4080            .Case("t5", 13)
4081            .Case("t6", 14)
4082            .Case("t7", 15)
4083            .Case("t8", 24)
4084            .Case("t9", 25)
4085            .Default(-1);
4086 
4087   if (!(isABI_N32() || isABI_N64()))
4088     return CC;
4089 
4090   if (12 <= CC && CC <= 15) {
4091     // Name is one of t4-t7
4092     AsmToken RegTok = getLexer().peekTok();
4093     SMRange RegRange = RegTok.getLocRange();
4094 
4095     StringRef FixedName = StringSwitch<StringRef>(Name)
4096                               .Case("t4", "t0")
4097                               .Case("t5", "t1")
4098                               .Case("t6", "t2")
4099                               .Case("t7", "t3")
4100                               .Default("");
4101     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
4102 
4103     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
4104                           "Did you mean $" + FixedName + "?", RegRange);
4105   }
4106 
4107   // Although SGI documentation just cuts out t0-t3 for n32/n64,
4108   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
4109   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
4110   if (8 <= CC && CC <= 11)
4111     CC += 4;
4112 
4113   if (CC == -1)
4114     CC = StringSwitch<unsigned>(Name)
4115              .Case("a4", 8)
4116              .Case("a5", 9)
4117              .Case("a6", 10)
4118              .Case("a7", 11)
4119              .Case("kt0", 26)
4120              .Case("kt1", 27)
4121              .Default(-1);
4122 
4123   return CC;
4124 }
4125 
4126 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
4127   int CC;
4128 
4129   CC = StringSwitch<unsigned>(Name)
4130             .Case("hwr_cpunum", 0)
4131             .Case("hwr_synci_step", 1)
4132             .Case("hwr_cc", 2)
4133             .Case("hwr_ccres", 3)
4134             .Case("hwr_ulr", 29)
4135             .Default(-1);
4136 
4137   return CC;
4138 }
4139 
4140 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
4141 
4142   if (Name[0] == 'f') {
4143     StringRef NumString = Name.substr(1);
4144     unsigned IntVal;
4145     if (NumString.getAsInteger(10, IntVal))
4146       return -1;     // This is not an integer.
4147     if (IntVal > 31) // Maximum index for fpu register.
4148       return -1;
4149     return IntVal;
4150   }
4151   return -1;
4152 }
4153 
4154 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
4155 
4156   if (Name.startswith("fcc")) {
4157     StringRef NumString = Name.substr(3);
4158     unsigned IntVal;
4159     if (NumString.getAsInteger(10, IntVal))
4160       return -1;    // This is not an integer.
4161     if (IntVal > 7) // There are only 8 fcc registers.
4162       return -1;
4163     return IntVal;
4164   }
4165   return -1;
4166 }
4167 
4168 int MipsAsmParser::matchACRegisterName(StringRef Name) {
4169 
4170   if (Name.startswith("ac")) {
4171     StringRef NumString = Name.substr(2);
4172     unsigned IntVal;
4173     if (NumString.getAsInteger(10, IntVal))
4174       return -1;    // This is not an integer.
4175     if (IntVal > 3) // There are only 3 acc registers.
4176       return -1;
4177     return IntVal;
4178   }
4179   return -1;
4180 }
4181 
4182 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
4183   unsigned IntVal;
4184 
4185   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
4186     return -1;
4187 
4188   if (IntVal > 31)
4189     return -1;
4190 
4191   return IntVal;
4192 }
4193 
4194 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
4195   int CC;
4196 
4197   CC = StringSwitch<unsigned>(Name)
4198            .Case("msair", 0)
4199            .Case("msacsr", 1)
4200            .Case("msaaccess", 2)
4201            .Case("msasave", 3)
4202            .Case("msamodify", 4)
4203            .Case("msarequest", 5)
4204            .Case("msamap", 6)
4205            .Case("msaunmap", 7)
4206            .Default(-1);
4207 
4208   return CC;
4209 }
4210 
4211 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
4212   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
4213   if (ATIndex == 0) {
4214     reportParseError(Loc,
4215                      "pseudo-instruction requires $at, which is not available");
4216     return 0;
4217   }
4218   unsigned AT = getReg(
4219       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
4220   return AT;
4221 }
4222 
4223 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
4224   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
4225 }
4226 
4227 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
4228   MCAsmParser &Parser = getParser();
4229   DEBUG(dbgs() << "parseOperand\n");
4230 
4231   // Check if the current operand has a custom associated parser, if so, try to
4232   // custom parse the operand, or fallback to the general approach.
4233   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
4234   if (ResTy == MatchOperand_Success)
4235     return false;
4236   // If there wasn't a custom match, try the generic matcher below. Otherwise,
4237   // there was a match, but an error occurred, in which case, just return that
4238   // the operand parsing failed.
4239   if (ResTy == MatchOperand_ParseFail)
4240     return true;
4241 
4242   DEBUG(dbgs() << ".. Generic Parser\n");
4243 
4244   switch (getLexer().getKind()) {
4245   case AsmToken::Dollar: {
4246     // Parse the register.
4247     SMLoc S = Parser.getTok().getLoc();
4248 
4249     // Almost all registers have been parsed by custom parsers. There is only
4250     // one exception to this. $zero (and it's alias $0) will reach this point
4251     // for div, divu, and similar instructions because it is not an operand
4252     // to the instruction definition but an explicit register. Special case
4253     // this situation for now.
4254     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
4255       return false;
4256 
4257     // Maybe it is a symbol reference.
4258     StringRef Identifier;
4259     if (Parser.parseIdentifier(Identifier))
4260       return true;
4261 
4262     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4263     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
4264     // Otherwise create a symbol reference.
4265     const MCExpr *Res =
4266         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
4267 
4268     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
4269     return false;
4270   }
4271   default: {
4272     DEBUG(dbgs() << ".. generic integer expression\n");
4273 
4274     const MCExpr *Expr;
4275     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
4276     if (getParser().parseExpression(Expr))
4277       return true;
4278 
4279     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4280 
4281     Operands.push_back(MipsOperand::CreateImm(Expr, S, E, *this));
4282     return false;
4283   }
4284   } // switch(getLexer().getKind())
4285   return true;
4286 }
4287 
4288 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
4289 
4290   switch (Expr->getKind()) {
4291   case MCExpr::Constant:
4292     return true;
4293   case MCExpr::SymbolRef:
4294     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
4295   case MCExpr::Binary:
4296     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
4297       if (!isEvaluated(BE->getLHS()))
4298         return false;
4299       return isEvaluated(BE->getRHS());
4300     }
4301   case MCExpr::Unary:
4302     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
4303   case MCExpr::Target:
4304     return true;
4305   }
4306   return false;
4307 }
4308 
4309 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
4310                                   SMLoc &EndLoc) {
4311   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
4312   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
4313   if (ResTy == MatchOperand_Success) {
4314     assert(Operands.size() == 1);
4315     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
4316     StartLoc = Operand.getStartLoc();
4317     EndLoc = Operand.getEndLoc();
4318 
4319     // AFAIK, we only support numeric registers and named GPR's in CFI
4320     // directives.
4321     // Don't worry about eating tokens before failing. Using an unrecognised
4322     // register is a parse error.
4323     if (Operand.isGPRAsmReg()) {
4324       // Resolve to GPR32 or GPR64 appropriately.
4325       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
4326     }
4327 
4328     return (RegNo == (unsigned)-1);
4329   }
4330 
4331   assert(Operands.size() == 0);
4332   return (RegNo == (unsigned)-1);
4333 }
4334 
4335 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
4336   SMLoc S;
4337 
4338   if (isParenExpr)
4339     return getParser().parseParenExprOfDepth(0, Res, S);
4340   return getParser().parseExpression(Res);
4341 }
4342 
4343 MipsAsmParser::OperandMatchResultTy
4344 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
4345   MCAsmParser &Parser = getParser();
4346   DEBUG(dbgs() << "parseMemOperand\n");
4347   const MCExpr *IdVal = nullptr;
4348   SMLoc S;
4349   bool isParenExpr = false;
4350   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
4351   // First operand is the offset.
4352   S = Parser.getTok().getLoc();
4353 
4354   if (getLexer().getKind() == AsmToken::LParen) {
4355     Parser.Lex();
4356     isParenExpr = true;
4357   }
4358 
4359   if (getLexer().getKind() != AsmToken::Dollar) {
4360     if (parseMemOffset(IdVal, isParenExpr))
4361       return MatchOperand_ParseFail;
4362 
4363     const AsmToken &Tok = Parser.getTok(); // Get the next token.
4364     if (Tok.isNot(AsmToken::LParen)) {
4365       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
4366       if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") {
4367         SMLoc E =
4368             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4369         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4370         return MatchOperand_Success;
4371       }
4372       if (Tok.is(AsmToken::EndOfStatement)) {
4373         SMLoc E =
4374             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4375 
4376         // Zero register assumed, add a memory operand with ZERO as its base.
4377         // "Base" will be managed by k_Memory.
4378         auto Base = MipsOperand::createGPRReg(
4379             0, "0", getContext().getRegisterInfo(), S, E, *this);
4380         Operands.push_back(
4381             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
4382         return MatchOperand_Success;
4383       }
4384       Error(Parser.getTok().getLoc(), "'(' expected");
4385       return MatchOperand_ParseFail;
4386     }
4387 
4388     Parser.Lex(); // Eat the '(' token.
4389   }
4390 
4391   Res = parseAnyRegister(Operands);
4392   if (Res != MatchOperand_Success)
4393     return Res;
4394 
4395   if (Parser.getTok().isNot(AsmToken::RParen)) {
4396     Error(Parser.getTok().getLoc(), "')' expected");
4397     return MatchOperand_ParseFail;
4398   }
4399 
4400   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4401 
4402   Parser.Lex(); // Eat the ')' token.
4403 
4404   if (!IdVal)
4405     IdVal = MCConstantExpr::create(0, getContext());
4406 
4407   // Replace the register operand with the memory operand.
4408   std::unique_ptr<MipsOperand> op(
4409       static_cast<MipsOperand *>(Operands.back().release()));
4410   // Remove the register from the operands.
4411   // "op" will be managed by k_Memory.
4412   Operands.pop_back();
4413   // Add the memory operand.
4414   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
4415     int64_t Imm;
4416     if (IdVal->evaluateAsAbsolute(Imm))
4417       IdVal = MCConstantExpr::create(Imm, getContext());
4418     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
4419       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
4420                                    getContext());
4421   }
4422 
4423   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
4424   return MatchOperand_Success;
4425 }
4426 
4427 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
4428   MCAsmParser &Parser = getParser();
4429   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
4430   if (Sym) {
4431     SMLoc S = Parser.getTok().getLoc();
4432     const MCExpr *Expr;
4433     if (Sym->isVariable())
4434       Expr = Sym->getVariableValue();
4435     else
4436       return false;
4437     if (Expr->getKind() == MCExpr::SymbolRef) {
4438       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
4439       StringRef DefSymbol = Ref->getSymbol().getName();
4440       if (DefSymbol.startswith("$")) {
4441         OperandMatchResultTy ResTy =
4442             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
4443         if (ResTy == MatchOperand_Success) {
4444           Parser.Lex();
4445           return true;
4446         } else if (ResTy == MatchOperand_ParseFail)
4447           llvm_unreachable("Should never ParseFail");
4448         return false;
4449       }
4450     }
4451   }
4452   return false;
4453 }
4454 
4455 MipsAsmParser::OperandMatchResultTy
4456 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
4457                                                  StringRef Identifier,
4458                                                  SMLoc S) {
4459   int Index = matchCPURegisterName(Identifier);
4460   if (Index != -1) {
4461     Operands.push_back(MipsOperand::createGPRReg(
4462         Index, Identifier, getContext().getRegisterInfo(), S,
4463         getLexer().getLoc(), *this));
4464     return MatchOperand_Success;
4465   }
4466 
4467   Index = matchHWRegsRegisterName(Identifier);
4468   if (Index != -1) {
4469     Operands.push_back(MipsOperand::createHWRegsReg(
4470         Index, Identifier, getContext().getRegisterInfo(), S,
4471         getLexer().getLoc(), *this));
4472     return MatchOperand_Success;
4473   }
4474 
4475   Index = matchFPURegisterName(Identifier);
4476   if (Index != -1) {
4477     Operands.push_back(MipsOperand::createFGRReg(
4478         Index, Identifier, getContext().getRegisterInfo(), S,
4479         getLexer().getLoc(), *this));
4480     return MatchOperand_Success;
4481   }
4482 
4483   Index = matchFCCRegisterName(Identifier);
4484   if (Index != -1) {
4485     Operands.push_back(MipsOperand::createFCCReg(
4486         Index, Identifier, getContext().getRegisterInfo(), S,
4487         getLexer().getLoc(), *this));
4488     return MatchOperand_Success;
4489   }
4490 
4491   Index = matchACRegisterName(Identifier);
4492   if (Index != -1) {
4493     Operands.push_back(MipsOperand::createACCReg(
4494         Index, Identifier, getContext().getRegisterInfo(), S,
4495         getLexer().getLoc(), *this));
4496     return MatchOperand_Success;
4497   }
4498 
4499   Index = matchMSA128RegisterName(Identifier);
4500   if (Index != -1) {
4501     Operands.push_back(MipsOperand::createMSA128Reg(
4502         Index, Identifier, getContext().getRegisterInfo(), S,
4503         getLexer().getLoc(), *this));
4504     return MatchOperand_Success;
4505   }
4506 
4507   Index = matchMSA128CtrlRegisterName(Identifier);
4508   if (Index != -1) {
4509     Operands.push_back(MipsOperand::createMSACtrlReg(
4510         Index, Identifier, getContext().getRegisterInfo(), S,
4511         getLexer().getLoc(), *this));
4512     return MatchOperand_Success;
4513   }
4514 
4515   return MatchOperand_NoMatch;
4516 }
4517 
4518 MipsAsmParser::OperandMatchResultTy
4519 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
4520   MCAsmParser &Parser = getParser();
4521   auto Token = Parser.getLexer().peekTok(false);
4522 
4523   if (Token.is(AsmToken::Identifier)) {
4524     DEBUG(dbgs() << ".. identifier\n");
4525     StringRef Identifier = Token.getIdentifier();
4526     OperandMatchResultTy ResTy =
4527         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
4528     return ResTy;
4529   } else if (Token.is(AsmToken::Integer)) {
4530     DEBUG(dbgs() << ".. integer\n");
4531     Operands.push_back(MipsOperand::createNumericReg(
4532         Token.getIntVal(), Token.getString(), getContext().getRegisterInfo(), S,
4533         Token.getLoc(), *this));
4534     return MatchOperand_Success;
4535   }
4536 
4537   DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
4538 
4539   return MatchOperand_NoMatch;
4540 }
4541 
4542 MipsAsmParser::OperandMatchResultTy
4543 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
4544   MCAsmParser &Parser = getParser();
4545   DEBUG(dbgs() << "parseAnyRegister\n");
4546 
4547   auto Token = Parser.getTok();
4548 
4549   SMLoc S = Token.getLoc();
4550 
4551   if (Token.isNot(AsmToken::Dollar)) {
4552     DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
4553     if (Token.is(AsmToken::Identifier)) {
4554       if (searchSymbolAlias(Operands))
4555         return MatchOperand_Success;
4556     }
4557     DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
4558     return MatchOperand_NoMatch;
4559   }
4560   DEBUG(dbgs() << ".. $\n");
4561 
4562   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
4563   if (ResTy == MatchOperand_Success) {
4564     Parser.Lex(); // $
4565     Parser.Lex(); // identifier
4566   }
4567   return ResTy;
4568 }
4569 
4570 MipsAsmParser::OperandMatchResultTy
4571 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
4572   MCAsmParser &Parser = getParser();
4573   DEBUG(dbgs() << "parseJumpTarget\n");
4574 
4575   SMLoc S = getLexer().getLoc();
4576 
4577   // Registers are a valid target and have priority over symbols.
4578   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
4579   if (ResTy != MatchOperand_NoMatch)
4580     return ResTy;
4581 
4582   // Integers and expressions are acceptable
4583   const MCExpr *Expr = nullptr;
4584   if (Parser.parseExpression(Expr)) {
4585     // We have no way of knowing if a symbol was consumed so we must ParseFail
4586     return MatchOperand_ParseFail;
4587   }
4588   Operands.push_back(
4589       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
4590   return MatchOperand_Success;
4591 }
4592 
4593 MipsAsmParser::OperandMatchResultTy
4594 MipsAsmParser::parseInvNum(OperandVector &Operands) {
4595   MCAsmParser &Parser = getParser();
4596   const MCExpr *IdVal;
4597   // If the first token is '$' we may have register operand.
4598   if (Parser.getTok().is(AsmToken::Dollar))
4599     return MatchOperand_NoMatch;
4600   SMLoc S = Parser.getTok().getLoc();
4601   if (getParser().parseExpression(IdVal))
4602     return MatchOperand_ParseFail;
4603   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
4604   assert(MCE && "Unexpected MCExpr type.");
4605   int64_t Val = MCE->getValue();
4606   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4607   Operands.push_back(MipsOperand::CreateImm(
4608       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
4609   return MatchOperand_Success;
4610 }
4611 
4612 MipsAsmParser::OperandMatchResultTy
4613 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
4614   MCAsmParser &Parser = getParser();
4615   SmallVector<unsigned, 10> Regs;
4616   unsigned RegNo;
4617   unsigned PrevReg = Mips::NoRegister;
4618   bool RegRange = false;
4619   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4620 
4621   if (Parser.getTok().isNot(AsmToken::Dollar))
4622     return MatchOperand_ParseFail;
4623 
4624   SMLoc S = Parser.getTok().getLoc();
4625   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
4626     SMLoc E = getLexer().getLoc();
4627     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
4628     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
4629     if (RegRange) {
4630       // Remove last register operand because registers from register range
4631       // should be inserted first.
4632       if ((isGP64bit() && RegNo == Mips::RA_64) ||
4633           (!isGP64bit() && RegNo == Mips::RA)) {
4634         Regs.push_back(RegNo);
4635       } else {
4636         unsigned TmpReg = PrevReg + 1;
4637         while (TmpReg <= RegNo) {
4638           if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) ||
4639               (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) &&
4640                isGP64bit())) {
4641             Error(E, "invalid register operand");
4642             return MatchOperand_ParseFail;
4643           }
4644 
4645           PrevReg = TmpReg;
4646           Regs.push_back(TmpReg++);
4647         }
4648       }
4649 
4650       RegRange = false;
4651     } else {
4652       if ((PrevReg == Mips::NoRegister) &&
4653           ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) ||
4654           (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) {
4655         Error(E, "$16 or $31 expected");
4656         return MatchOperand_ParseFail;
4657       } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA ||
4658                     (RegNo >= Mips::S0 && RegNo <= Mips::S7)) &&
4659                     !isGP64bit()) ||
4660                    ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 ||
4661                     (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) &&
4662                     isGP64bit()))) {
4663         Error(E, "invalid register operand");
4664         return MatchOperand_ParseFail;
4665       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
4666                  ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) ||
4667                   (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 &&
4668                    isGP64bit()))) {
4669         Error(E, "consecutive register numbers expected");
4670         return MatchOperand_ParseFail;
4671       }
4672 
4673       Regs.push_back(RegNo);
4674     }
4675 
4676     if (Parser.getTok().is(AsmToken::Minus))
4677       RegRange = true;
4678 
4679     if (!Parser.getTok().isNot(AsmToken::Minus) &&
4680         !Parser.getTok().isNot(AsmToken::Comma)) {
4681       Error(E, "',' or '-' expected");
4682       return MatchOperand_ParseFail;
4683     }
4684 
4685     Lex(); // Consume comma or minus
4686     if (Parser.getTok().isNot(AsmToken::Dollar))
4687       break;
4688 
4689     PrevReg = RegNo;
4690   }
4691 
4692   SMLoc E = Parser.getTok().getLoc();
4693   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4694   parseMemOperand(Operands);
4695   return MatchOperand_Success;
4696 }
4697 
4698 MipsAsmParser::OperandMatchResultTy
4699 MipsAsmParser::parseRegisterPair(OperandVector &Operands) {
4700   MCAsmParser &Parser = getParser();
4701 
4702   SMLoc S = Parser.getTok().getLoc();
4703   if (parseAnyRegister(Operands) != MatchOperand_Success)
4704     return MatchOperand_ParseFail;
4705 
4706   SMLoc E = Parser.getTok().getLoc();
4707   MipsOperand Op = static_cast<MipsOperand &>(*Operands.back());
4708 
4709   Operands.pop_back();
4710   Operands.push_back(MipsOperand::CreateRegPair(Op, S, E, *this));
4711   return MatchOperand_Success;
4712 }
4713 
4714 MipsAsmParser::OperandMatchResultTy
4715 MipsAsmParser::parseMovePRegPair(OperandVector &Operands) {
4716   MCAsmParser &Parser = getParser();
4717   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4718   SmallVector<unsigned, 10> Regs;
4719 
4720   if (Parser.getTok().isNot(AsmToken::Dollar))
4721     return MatchOperand_ParseFail;
4722 
4723   SMLoc S = Parser.getTok().getLoc();
4724 
4725   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4726     return MatchOperand_ParseFail;
4727 
4728   MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4729   unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4730   Regs.push_back(RegNo);
4731 
4732   SMLoc E = Parser.getTok().getLoc();
4733   if (Parser.getTok().isNot(AsmToken::Comma)) {
4734     Error(E, "',' expected");
4735     return MatchOperand_ParseFail;
4736   }
4737 
4738   // Remove comma.
4739   Parser.Lex();
4740 
4741   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4742     return MatchOperand_ParseFail;
4743 
4744   Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4745   RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4746   Regs.push_back(RegNo);
4747 
4748   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4749 
4750   return MatchOperand_Success;
4751 }
4752 
4753 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
4754 /// either this.
4755 /// ::= '(', register, ')'
4756 /// handle it before we iterate so we don't get tripped up by the lack of
4757 /// a comma.
4758 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
4759   MCAsmParser &Parser = getParser();
4760   if (getLexer().is(AsmToken::LParen)) {
4761     Operands.push_back(
4762         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
4763     Parser.Lex();
4764     if (parseOperand(Operands, Name)) {
4765       SMLoc Loc = getLexer().getLoc();
4766       Parser.eatToEndOfStatement();
4767       return Error(Loc, "unexpected token in argument list");
4768     }
4769     if (Parser.getTok().isNot(AsmToken::RParen)) {
4770       SMLoc Loc = getLexer().getLoc();
4771       Parser.eatToEndOfStatement();
4772       return Error(Loc, "unexpected token, expected ')'");
4773     }
4774     Operands.push_back(
4775         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
4776     Parser.Lex();
4777   }
4778   return false;
4779 }
4780 
4781 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
4782 /// either one of these.
4783 /// ::= '[', register, ']'
4784 /// ::= '[', integer, ']'
4785 /// handle it before we iterate so we don't get tripped up by the lack of
4786 /// a comma.
4787 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
4788                                        OperandVector &Operands) {
4789   MCAsmParser &Parser = getParser();
4790   if (getLexer().is(AsmToken::LBrac)) {
4791     Operands.push_back(
4792         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
4793     Parser.Lex();
4794     if (parseOperand(Operands, Name)) {
4795       SMLoc Loc = getLexer().getLoc();
4796       Parser.eatToEndOfStatement();
4797       return Error(Loc, "unexpected token in argument list");
4798     }
4799     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4800       SMLoc Loc = getLexer().getLoc();
4801       Parser.eatToEndOfStatement();
4802       return Error(Loc, "unexpected token, expected ']'");
4803     }
4804     Operands.push_back(
4805         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
4806     Parser.Lex();
4807   }
4808   return false;
4809 }
4810 
4811 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
4812                                      SMLoc NameLoc, OperandVector &Operands) {
4813   MCAsmParser &Parser = getParser();
4814   DEBUG(dbgs() << "ParseInstruction\n");
4815 
4816   // We have reached first instruction, module directive are now forbidden.
4817   getTargetStreamer().forbidModuleDirective();
4818 
4819   // Check if we have valid mnemonic
4820   if (!mnemonicIsValid(Name, 0)) {
4821     Parser.eatToEndOfStatement();
4822     return Error(NameLoc, "unknown instruction");
4823   }
4824   // First operand in MCInst is instruction mnemonic.
4825   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
4826 
4827   // Read the remaining operands.
4828   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4829     // Read the first operand.
4830     if (parseOperand(Operands, Name)) {
4831       SMLoc Loc = getLexer().getLoc();
4832       Parser.eatToEndOfStatement();
4833       return Error(Loc, "unexpected token in argument list");
4834     }
4835     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
4836       return true;
4837     // AFAIK, parenthesis suffixes are never on the first operand
4838 
4839     while (getLexer().is(AsmToken::Comma)) {
4840       Parser.Lex(); // Eat the comma.
4841       // Parse and remember the operand.
4842       if (parseOperand(Operands, Name)) {
4843         SMLoc Loc = getLexer().getLoc();
4844         Parser.eatToEndOfStatement();
4845         return Error(Loc, "unexpected token in argument list");
4846       }
4847       // Parse bracket and parenthesis suffixes before we iterate
4848       if (getLexer().is(AsmToken::LBrac)) {
4849         if (parseBracketSuffix(Name, Operands))
4850           return true;
4851       } else if (getLexer().is(AsmToken::LParen) &&
4852                  parseParenSuffix(Name, Operands))
4853         return true;
4854     }
4855   }
4856   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4857     SMLoc Loc = getLexer().getLoc();
4858     Parser.eatToEndOfStatement();
4859     return Error(Loc, "unexpected token in argument list");
4860   }
4861   Parser.Lex(); // Consume the EndOfStatement.
4862   return false;
4863 }
4864 
4865 // FIXME: Given that these have the same name, these should both be
4866 // consistent on affecting the Parser.
4867 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
4868   MCAsmParser &Parser = getParser();
4869   SMLoc Loc = getLexer().getLoc();
4870   Parser.eatToEndOfStatement();
4871   return Error(Loc, ErrorMsg);
4872 }
4873 
4874 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
4875   return Error(Loc, ErrorMsg);
4876 }
4877 
4878 bool MipsAsmParser::parseSetNoAtDirective() {
4879   MCAsmParser &Parser = getParser();
4880   // Line should look like: ".set noat".
4881 
4882   // Set the $at register to $0.
4883   AssemblerOptions.back()->setATRegIndex(0);
4884 
4885   Parser.Lex(); // Eat "noat".
4886 
4887   // If this is not the end of the statement, report an error.
4888   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4889     reportParseError("unexpected token, expected end of statement");
4890     return false;
4891   }
4892 
4893   getTargetStreamer().emitDirectiveSetNoAt();
4894   Parser.Lex(); // Consume the EndOfStatement.
4895   return false;
4896 }
4897 
4898 bool MipsAsmParser::parseSetAtDirective() {
4899   // Line can be: ".set at", which sets $at to $1
4900   //          or  ".set at=$reg", which sets $at to $reg.
4901   MCAsmParser &Parser = getParser();
4902   Parser.Lex(); // Eat "at".
4903 
4904   if (getLexer().is(AsmToken::EndOfStatement)) {
4905     // No register was specified, so we set $at to $1.
4906     AssemblerOptions.back()->setATRegIndex(1);
4907 
4908     getTargetStreamer().emitDirectiveSetAt();
4909     Parser.Lex(); // Consume the EndOfStatement.
4910     return false;
4911   }
4912 
4913   if (getLexer().isNot(AsmToken::Equal)) {
4914     reportParseError("unexpected token, expected equals sign");
4915     return false;
4916   }
4917   Parser.Lex(); // Eat "=".
4918 
4919   if (getLexer().isNot(AsmToken::Dollar)) {
4920     if (getLexer().is(AsmToken::EndOfStatement)) {
4921       reportParseError("no register specified");
4922       return false;
4923     } else {
4924       reportParseError("unexpected token, expected dollar sign '$'");
4925       return false;
4926     }
4927   }
4928   Parser.Lex(); // Eat "$".
4929 
4930   // Find out what "reg" is.
4931   unsigned AtRegNo;
4932   const AsmToken &Reg = Parser.getTok();
4933   if (Reg.is(AsmToken::Identifier)) {
4934     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
4935   } else if (Reg.is(AsmToken::Integer)) {
4936     AtRegNo = Reg.getIntVal();
4937   } else {
4938     reportParseError("unexpected token, expected identifier or integer");
4939     return false;
4940   }
4941 
4942   // Check if $reg is a valid register. If it is, set $at to $reg.
4943   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
4944     reportParseError("invalid register");
4945     return false;
4946   }
4947   Parser.Lex(); // Eat "reg".
4948 
4949   // If this is not the end of the statement, report an error.
4950   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4951     reportParseError("unexpected token, expected end of statement");
4952     return false;
4953   }
4954 
4955   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
4956 
4957   Parser.Lex(); // Consume the EndOfStatement.
4958   return false;
4959 }
4960 
4961 bool MipsAsmParser::parseSetReorderDirective() {
4962   MCAsmParser &Parser = getParser();
4963   Parser.Lex();
4964   // If this is not the end of the statement, report an error.
4965   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4966     reportParseError("unexpected token, expected end of statement");
4967     return false;
4968   }
4969   AssemblerOptions.back()->setReorder();
4970   getTargetStreamer().emitDirectiveSetReorder();
4971   Parser.Lex(); // Consume the EndOfStatement.
4972   return false;
4973 }
4974 
4975 bool MipsAsmParser::parseSetNoReorderDirective() {
4976   MCAsmParser &Parser = getParser();
4977   Parser.Lex();
4978   // If this is not the end of the statement, report an error.
4979   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4980     reportParseError("unexpected token, expected end of statement");
4981     return false;
4982   }
4983   AssemblerOptions.back()->setNoReorder();
4984   getTargetStreamer().emitDirectiveSetNoReorder();
4985   Parser.Lex(); // Consume the EndOfStatement.
4986   return false;
4987 }
4988 
4989 bool MipsAsmParser::parseSetMacroDirective() {
4990   MCAsmParser &Parser = getParser();
4991   Parser.Lex();
4992   // If this is not the end of the statement, report an error.
4993   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4994     reportParseError("unexpected token, expected end of statement");
4995     return false;
4996   }
4997   AssemblerOptions.back()->setMacro();
4998   getTargetStreamer().emitDirectiveSetMacro();
4999   Parser.Lex(); // Consume the EndOfStatement.
5000   return false;
5001 }
5002 
5003 bool MipsAsmParser::parseSetNoMacroDirective() {
5004   MCAsmParser &Parser = getParser();
5005   Parser.Lex();
5006   // If this is not the end of the statement, report an error.
5007   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5008     reportParseError("unexpected token, expected end of statement");
5009     return false;
5010   }
5011   if (AssemblerOptions.back()->isReorder()) {
5012     reportParseError("`noreorder' must be set before `nomacro'");
5013     return false;
5014   }
5015   AssemblerOptions.back()->setNoMacro();
5016   getTargetStreamer().emitDirectiveSetNoMacro();
5017   Parser.Lex(); // Consume the EndOfStatement.
5018   return false;
5019 }
5020 
5021 bool MipsAsmParser::parseSetMsaDirective() {
5022   MCAsmParser &Parser = getParser();
5023   Parser.Lex();
5024 
5025   // If this is not the end of the statement, report an error.
5026   if (getLexer().isNot(AsmToken::EndOfStatement))
5027     return reportParseError("unexpected token, expected end of statement");
5028 
5029   setFeatureBits(Mips::FeatureMSA, "msa");
5030   getTargetStreamer().emitDirectiveSetMsa();
5031   return false;
5032 }
5033 
5034 bool MipsAsmParser::parseSetNoMsaDirective() {
5035   MCAsmParser &Parser = getParser();
5036   Parser.Lex();
5037 
5038   // If this is not the end of the statement, report an error.
5039   if (getLexer().isNot(AsmToken::EndOfStatement))
5040     return reportParseError("unexpected token, expected end of statement");
5041 
5042   clearFeatureBits(Mips::FeatureMSA, "msa");
5043   getTargetStreamer().emitDirectiveSetNoMsa();
5044   return false;
5045 }
5046 
5047 bool MipsAsmParser::parseSetNoDspDirective() {
5048   MCAsmParser &Parser = getParser();
5049   Parser.Lex(); // Eat "nodsp".
5050 
5051   // If this is not the end of the statement, report an error.
5052   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5053     reportParseError("unexpected token, expected end of statement");
5054     return false;
5055   }
5056 
5057   clearFeatureBits(Mips::FeatureDSP, "dsp");
5058   getTargetStreamer().emitDirectiveSetNoDsp();
5059   return false;
5060 }
5061 
5062 bool MipsAsmParser::parseSetMips16Directive() {
5063   MCAsmParser &Parser = getParser();
5064   Parser.Lex(); // Eat "mips16".
5065 
5066   // If this is not the end of the statement, report an error.
5067   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5068     reportParseError("unexpected token, expected end of statement");
5069     return false;
5070   }
5071 
5072   setFeatureBits(Mips::FeatureMips16, "mips16");
5073   getTargetStreamer().emitDirectiveSetMips16();
5074   Parser.Lex(); // Consume the EndOfStatement.
5075   return false;
5076 }
5077 
5078 bool MipsAsmParser::parseSetNoMips16Directive() {
5079   MCAsmParser &Parser = getParser();
5080   Parser.Lex(); // Eat "nomips16".
5081 
5082   // If this is not the end of the statement, report an error.
5083   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5084     reportParseError("unexpected token, expected end of statement");
5085     return false;
5086   }
5087 
5088   clearFeatureBits(Mips::FeatureMips16, "mips16");
5089   getTargetStreamer().emitDirectiveSetNoMips16();
5090   Parser.Lex(); // Consume the EndOfStatement.
5091   return false;
5092 }
5093 
5094 bool MipsAsmParser::parseSetFpDirective() {
5095   MCAsmParser &Parser = getParser();
5096   MipsABIFlagsSection::FpABIKind FpAbiVal;
5097   // Line can be: .set fp=32
5098   //              .set fp=xx
5099   //              .set fp=64
5100   Parser.Lex(); // Eat fp token
5101   AsmToken Tok = Parser.getTok();
5102   if (Tok.isNot(AsmToken::Equal)) {
5103     reportParseError("unexpected token, expected equals sign '='");
5104     return false;
5105   }
5106   Parser.Lex(); // Eat '=' token.
5107   Tok = Parser.getTok();
5108 
5109   if (!parseFpABIValue(FpAbiVal, ".set"))
5110     return false;
5111 
5112   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5113     reportParseError("unexpected token, expected end of statement");
5114     return false;
5115   }
5116   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
5117   Parser.Lex(); // Consume the EndOfStatement.
5118   return false;
5119 }
5120 
5121 bool MipsAsmParser::parseSetOddSPRegDirective() {
5122   MCAsmParser &Parser = getParser();
5123 
5124   Parser.Lex(); // Eat "oddspreg".
5125   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5126     reportParseError("unexpected token, expected end of statement");
5127     return false;
5128   }
5129 
5130   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5131   getTargetStreamer().emitDirectiveSetOddSPReg();
5132   return false;
5133 }
5134 
5135 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
5136   MCAsmParser &Parser = getParser();
5137 
5138   Parser.Lex(); // Eat "nooddspreg".
5139   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5140     reportParseError("unexpected token, expected end of statement");
5141     return false;
5142   }
5143 
5144   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5145   getTargetStreamer().emitDirectiveSetNoOddSPReg();
5146   return false;
5147 }
5148 
5149 bool MipsAsmParser::parseSetPopDirective() {
5150   MCAsmParser &Parser = getParser();
5151   SMLoc Loc = getLexer().getLoc();
5152 
5153   Parser.Lex();
5154   if (getLexer().isNot(AsmToken::EndOfStatement))
5155     return reportParseError("unexpected token, expected end of statement");
5156 
5157   // Always keep an element on the options "stack" to prevent the user
5158   // from changing the initial options. This is how we remember them.
5159   if (AssemblerOptions.size() == 2)
5160     return reportParseError(Loc, ".set pop with no .set push");
5161 
5162   MCSubtargetInfo &STI = copySTI();
5163   AssemblerOptions.pop_back();
5164   setAvailableFeatures(
5165       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
5166   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
5167 
5168   getTargetStreamer().emitDirectiveSetPop();
5169   return false;
5170 }
5171 
5172 bool MipsAsmParser::parseSetPushDirective() {
5173   MCAsmParser &Parser = getParser();
5174   Parser.Lex();
5175   if (getLexer().isNot(AsmToken::EndOfStatement))
5176     return reportParseError("unexpected token, expected end of statement");
5177 
5178   // Create a copy of the current assembler options environment and push it.
5179   AssemblerOptions.push_back(
5180               make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
5181 
5182   getTargetStreamer().emitDirectiveSetPush();
5183   return false;
5184 }
5185 
5186 bool MipsAsmParser::parseSetSoftFloatDirective() {
5187   MCAsmParser &Parser = getParser();
5188   Parser.Lex();
5189   if (getLexer().isNot(AsmToken::EndOfStatement))
5190     return reportParseError("unexpected token, expected end of statement");
5191 
5192   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5193   getTargetStreamer().emitDirectiveSetSoftFloat();
5194   return false;
5195 }
5196 
5197 bool MipsAsmParser::parseSetHardFloatDirective() {
5198   MCAsmParser &Parser = getParser();
5199   Parser.Lex();
5200   if (getLexer().isNot(AsmToken::EndOfStatement))
5201     return reportParseError("unexpected token, expected end of statement");
5202 
5203   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5204   getTargetStreamer().emitDirectiveSetHardFloat();
5205   return false;
5206 }
5207 
5208 bool MipsAsmParser::parseSetAssignment() {
5209   StringRef Name;
5210   const MCExpr *Value;
5211   MCAsmParser &Parser = getParser();
5212 
5213   if (Parser.parseIdentifier(Name))
5214     reportParseError("expected identifier after .set");
5215 
5216   if (getLexer().isNot(AsmToken::Comma))
5217     return reportParseError("unexpected token, expected comma");
5218   Lex(); // Eat comma
5219 
5220   if (Parser.parseExpression(Value))
5221     return reportParseError("expected valid expression after comma");
5222 
5223   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5224   Sym->setVariableValue(Value);
5225 
5226   return false;
5227 }
5228 
5229 bool MipsAsmParser::parseSetMips0Directive() {
5230   MCAsmParser &Parser = getParser();
5231   Parser.Lex();
5232   if (getLexer().isNot(AsmToken::EndOfStatement))
5233     return reportParseError("unexpected token, expected end of statement");
5234 
5235   // Reset assembler options to their initial values.
5236   MCSubtargetInfo &STI = copySTI();
5237   setAvailableFeatures(
5238       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
5239   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
5240   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
5241 
5242   getTargetStreamer().emitDirectiveSetMips0();
5243   return false;
5244 }
5245 
5246 bool MipsAsmParser::parseSetArchDirective() {
5247   MCAsmParser &Parser = getParser();
5248   Parser.Lex();
5249   if (getLexer().isNot(AsmToken::Equal))
5250     return reportParseError("unexpected token, expected equals sign");
5251 
5252   Parser.Lex();
5253   StringRef Arch;
5254   if (Parser.parseIdentifier(Arch))
5255     return reportParseError("expected arch identifier");
5256 
5257   StringRef ArchFeatureName =
5258       StringSwitch<StringRef>(Arch)
5259           .Case("mips1", "mips1")
5260           .Case("mips2", "mips2")
5261           .Case("mips3", "mips3")
5262           .Case("mips4", "mips4")
5263           .Case("mips5", "mips5")
5264           .Case("mips32", "mips32")
5265           .Case("mips32r2", "mips32r2")
5266           .Case("mips32r3", "mips32r3")
5267           .Case("mips32r5", "mips32r5")
5268           .Case("mips32r6", "mips32r6")
5269           .Case("mips64", "mips64")
5270           .Case("mips64r2", "mips64r2")
5271           .Case("mips64r3", "mips64r3")
5272           .Case("mips64r5", "mips64r5")
5273           .Case("mips64r6", "mips64r6")
5274           .Case("octeon", "cnmips")
5275           .Case("r4000", "mips3") // This is an implementation of Mips3.
5276           .Default("");
5277 
5278   if (ArchFeatureName.empty())
5279     return reportParseError("unsupported architecture");
5280 
5281   selectArch(ArchFeatureName);
5282   getTargetStreamer().emitDirectiveSetArch(Arch);
5283   return false;
5284 }
5285 
5286 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
5287   MCAsmParser &Parser = getParser();
5288   Parser.Lex();
5289   if (getLexer().isNot(AsmToken::EndOfStatement))
5290     return reportParseError("unexpected token, expected end of statement");
5291 
5292   switch (Feature) {
5293   default:
5294     llvm_unreachable("Unimplemented feature");
5295   case Mips::FeatureDSP:
5296     setFeatureBits(Mips::FeatureDSP, "dsp");
5297     getTargetStreamer().emitDirectiveSetDsp();
5298     break;
5299   case Mips::FeatureMicroMips:
5300     setFeatureBits(Mips::FeatureMicroMips, "micromips");
5301     getTargetStreamer().emitDirectiveSetMicroMips();
5302     break;
5303   case Mips::FeatureMips1:
5304     selectArch("mips1");
5305     getTargetStreamer().emitDirectiveSetMips1();
5306     break;
5307   case Mips::FeatureMips2:
5308     selectArch("mips2");
5309     getTargetStreamer().emitDirectiveSetMips2();
5310     break;
5311   case Mips::FeatureMips3:
5312     selectArch("mips3");
5313     getTargetStreamer().emitDirectiveSetMips3();
5314     break;
5315   case Mips::FeatureMips4:
5316     selectArch("mips4");
5317     getTargetStreamer().emitDirectiveSetMips4();
5318     break;
5319   case Mips::FeatureMips5:
5320     selectArch("mips5");
5321     getTargetStreamer().emitDirectiveSetMips5();
5322     break;
5323   case Mips::FeatureMips32:
5324     selectArch("mips32");
5325     getTargetStreamer().emitDirectiveSetMips32();
5326     break;
5327   case Mips::FeatureMips32r2:
5328     selectArch("mips32r2");
5329     getTargetStreamer().emitDirectiveSetMips32R2();
5330     break;
5331   case Mips::FeatureMips32r3:
5332     selectArch("mips32r3");
5333     getTargetStreamer().emitDirectiveSetMips32R3();
5334     break;
5335   case Mips::FeatureMips32r5:
5336     selectArch("mips32r5");
5337     getTargetStreamer().emitDirectiveSetMips32R5();
5338     break;
5339   case Mips::FeatureMips32r6:
5340     selectArch("mips32r6");
5341     getTargetStreamer().emitDirectiveSetMips32R6();
5342     break;
5343   case Mips::FeatureMips64:
5344     selectArch("mips64");
5345     getTargetStreamer().emitDirectiveSetMips64();
5346     break;
5347   case Mips::FeatureMips64r2:
5348     selectArch("mips64r2");
5349     getTargetStreamer().emitDirectiveSetMips64R2();
5350     break;
5351   case Mips::FeatureMips64r3:
5352     selectArch("mips64r3");
5353     getTargetStreamer().emitDirectiveSetMips64R3();
5354     break;
5355   case Mips::FeatureMips64r5:
5356     selectArch("mips64r5");
5357     getTargetStreamer().emitDirectiveSetMips64R5();
5358     break;
5359   case Mips::FeatureMips64r6:
5360     selectArch("mips64r6");
5361     getTargetStreamer().emitDirectiveSetMips64R6();
5362     break;
5363   }
5364   return false;
5365 }
5366 
5367 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
5368   MCAsmParser &Parser = getParser();
5369   if (getLexer().isNot(AsmToken::Comma)) {
5370     SMLoc Loc = getLexer().getLoc();
5371     Parser.eatToEndOfStatement();
5372     return Error(Loc, ErrorStr);
5373   }
5374 
5375   Parser.Lex(); // Eat the comma.
5376   return true;
5377 }
5378 
5379 // Used to determine if .cpload, .cprestore, and .cpsetup have any effect.
5380 // In this class, it is only used for .cprestore.
5381 // FIXME: Only keep track of IsPicEnabled in one place, instead of in both
5382 // MipsTargetELFStreamer and MipsAsmParser.
5383 bool MipsAsmParser::isPicAndNotNxxAbi() {
5384   return inPicMode() && !(isABI_N32() || isABI_N64());
5385 }
5386 
5387 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
5388   if (AssemblerOptions.back()->isReorder())
5389     Warning(Loc, ".cpload should be inside a noreorder section");
5390 
5391   if (inMips16Mode()) {
5392     reportParseError(".cpload is not supported in Mips16 mode");
5393     return false;
5394   }
5395 
5396   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
5397   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
5398   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
5399     reportParseError("expected register containing function address");
5400     return false;
5401   }
5402 
5403   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
5404   if (!RegOpnd.isGPRAsmReg()) {
5405     reportParseError(RegOpnd.getStartLoc(), "invalid register");
5406     return false;
5407   }
5408 
5409   // If this is not the end of the statement, report an error.
5410   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5411     reportParseError("unexpected token, expected end of statement");
5412     return false;
5413   }
5414 
5415   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
5416   return false;
5417 }
5418 
5419 bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) {
5420   MCAsmParser &Parser = getParser();
5421 
5422   // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
5423   // is used in non-PIC mode.
5424 
5425   if (inMips16Mode()) {
5426     reportParseError(".cprestore is not supported in Mips16 mode");
5427     return false;
5428   }
5429 
5430   // Get the stack offset value.
5431   const MCExpr *StackOffset;
5432   int64_t StackOffsetVal;
5433   if (Parser.parseExpression(StackOffset)) {
5434     reportParseError("expected stack offset value");
5435     return false;
5436   }
5437 
5438   if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) {
5439     reportParseError("stack offset is not an absolute expression");
5440     return false;
5441   }
5442 
5443   if (StackOffsetVal < 0) {
5444     Warning(Loc, ".cprestore with negative stack offset has no effect");
5445     IsCpRestoreSet = false;
5446   } else {
5447     IsCpRestoreSet = true;
5448     CpRestoreOffset = StackOffsetVal;
5449   }
5450 
5451   // If this is not the end of the statement, report an error.
5452   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5453     reportParseError("unexpected token, expected end of statement");
5454     return false;
5455   }
5456 
5457   if (!getTargetStreamer().emitDirectiveCpRestore(
5458           CpRestoreOffset, [&]() { return getATReg(Loc); }, Loc, STI))
5459     return true;
5460   Parser.Lex(); // Consume the EndOfStatement.
5461   return false;
5462 }
5463 
5464 bool MipsAsmParser::parseDirectiveCPSetup() {
5465   MCAsmParser &Parser = getParser();
5466   unsigned FuncReg;
5467   unsigned Save;
5468   bool SaveIsReg = true;
5469 
5470   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
5471   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
5472   if (ResTy == MatchOperand_NoMatch) {
5473     reportParseError("expected register containing function address");
5474     return false;
5475   }
5476 
5477   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5478   if (!FuncRegOpnd.isGPRAsmReg()) {
5479     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
5480     Parser.eatToEndOfStatement();
5481     return false;
5482   }
5483 
5484   FuncReg = FuncRegOpnd.getGPR32Reg();
5485   TmpReg.clear();
5486 
5487   if (!eatComma("unexpected token, expected comma"))
5488     return true;
5489 
5490   ResTy = parseAnyRegister(TmpReg);
5491   if (ResTy == MatchOperand_NoMatch) {
5492     const MCExpr *OffsetExpr;
5493     int64_t OffsetVal;
5494     SMLoc ExprLoc = getLexer().getLoc();
5495 
5496     if (Parser.parseExpression(OffsetExpr) ||
5497         !OffsetExpr->evaluateAsAbsolute(OffsetVal)) {
5498       reportParseError(ExprLoc, "expected save register or stack offset");
5499       Parser.eatToEndOfStatement();
5500       return false;
5501     }
5502 
5503     Save = OffsetVal;
5504     SaveIsReg = false;
5505   } else {
5506     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5507     if (!SaveOpnd.isGPRAsmReg()) {
5508       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
5509       Parser.eatToEndOfStatement();
5510       return false;
5511     }
5512     Save = SaveOpnd.getGPR32Reg();
5513   }
5514 
5515   if (!eatComma("unexpected token, expected comma"))
5516     return true;
5517 
5518   const MCExpr *Expr;
5519   if (Parser.parseExpression(Expr)) {
5520     reportParseError("expected expression");
5521     return false;
5522   }
5523 
5524   if (Expr->getKind() != MCExpr::SymbolRef) {
5525     reportParseError("expected symbol");
5526     return false;
5527   }
5528   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
5529 
5530   CpSaveLocation = Save;
5531   CpSaveLocationIsRegister = SaveIsReg;
5532 
5533   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
5534                                            SaveIsReg);
5535   return false;
5536 }
5537 
5538 bool MipsAsmParser::parseDirectiveCPReturn() {
5539   getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation,
5540                                             CpSaveLocationIsRegister);
5541   return false;
5542 }
5543 
5544 bool MipsAsmParser::parseDirectiveNaN() {
5545   MCAsmParser &Parser = getParser();
5546   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5547     const AsmToken &Tok = Parser.getTok();
5548 
5549     if (Tok.getString() == "2008") {
5550       Parser.Lex();
5551       getTargetStreamer().emitDirectiveNaN2008();
5552       return false;
5553     } else if (Tok.getString() == "legacy") {
5554       Parser.Lex();
5555       getTargetStreamer().emitDirectiveNaNLegacy();
5556       return false;
5557     }
5558   }
5559   // If we don't recognize the option passed to the .nan
5560   // directive (e.g. no option or unknown option), emit an error.
5561   reportParseError("invalid option in .nan directive");
5562   return false;
5563 }
5564 
5565 bool MipsAsmParser::parseDirectiveSet() {
5566   MCAsmParser &Parser = getParser();
5567   // Get the next token.
5568   const AsmToken &Tok = Parser.getTok();
5569 
5570   if (Tok.getString() == "noat") {
5571     return parseSetNoAtDirective();
5572   } else if (Tok.getString() == "at") {
5573     return parseSetAtDirective();
5574   } else if (Tok.getString() == "arch") {
5575     return parseSetArchDirective();
5576   } else if (Tok.getString() == "fp") {
5577     return parseSetFpDirective();
5578   } else if (Tok.getString() == "oddspreg") {
5579     return parseSetOddSPRegDirective();
5580   } else if (Tok.getString() == "nooddspreg") {
5581     return parseSetNoOddSPRegDirective();
5582   } else if (Tok.getString() == "pop") {
5583     return parseSetPopDirective();
5584   } else if (Tok.getString() == "push") {
5585     return parseSetPushDirective();
5586   } else if (Tok.getString() == "reorder") {
5587     return parseSetReorderDirective();
5588   } else if (Tok.getString() == "noreorder") {
5589     return parseSetNoReorderDirective();
5590   } else if (Tok.getString() == "macro") {
5591     return parseSetMacroDirective();
5592   } else if (Tok.getString() == "nomacro") {
5593     return parseSetNoMacroDirective();
5594   } else if (Tok.getString() == "mips16") {
5595     return parseSetMips16Directive();
5596   } else if (Tok.getString() == "nomips16") {
5597     return parseSetNoMips16Directive();
5598   } else if (Tok.getString() == "nomicromips") {
5599     clearFeatureBits(Mips::FeatureMicroMips, "micromips");
5600     getTargetStreamer().emitDirectiveSetNoMicroMips();
5601     Parser.eatToEndOfStatement();
5602     return false;
5603   } else if (Tok.getString() == "micromips") {
5604     return parseSetFeature(Mips::FeatureMicroMips);
5605   } else if (Tok.getString() == "mips0") {
5606     return parseSetMips0Directive();
5607   } else if (Tok.getString() == "mips1") {
5608     return parseSetFeature(Mips::FeatureMips1);
5609   } else if (Tok.getString() == "mips2") {
5610     return parseSetFeature(Mips::FeatureMips2);
5611   } else if (Tok.getString() == "mips3") {
5612     return parseSetFeature(Mips::FeatureMips3);
5613   } else if (Tok.getString() == "mips4") {
5614     return parseSetFeature(Mips::FeatureMips4);
5615   } else if (Tok.getString() == "mips5") {
5616     return parseSetFeature(Mips::FeatureMips5);
5617   } else if (Tok.getString() == "mips32") {
5618     return parseSetFeature(Mips::FeatureMips32);
5619   } else if (Tok.getString() == "mips32r2") {
5620     return parseSetFeature(Mips::FeatureMips32r2);
5621   } else if (Tok.getString() == "mips32r3") {
5622     return parseSetFeature(Mips::FeatureMips32r3);
5623   } else if (Tok.getString() == "mips32r5") {
5624     return parseSetFeature(Mips::FeatureMips32r5);
5625   } else if (Tok.getString() == "mips32r6") {
5626     return parseSetFeature(Mips::FeatureMips32r6);
5627   } else if (Tok.getString() == "mips64") {
5628     return parseSetFeature(Mips::FeatureMips64);
5629   } else if (Tok.getString() == "mips64r2") {
5630     return parseSetFeature(Mips::FeatureMips64r2);
5631   } else if (Tok.getString() == "mips64r3") {
5632     return parseSetFeature(Mips::FeatureMips64r3);
5633   } else if (Tok.getString() == "mips64r5") {
5634     return parseSetFeature(Mips::FeatureMips64r5);
5635   } else if (Tok.getString() == "mips64r6") {
5636     return parseSetFeature(Mips::FeatureMips64r6);
5637   } else if (Tok.getString() == "dsp") {
5638     return parseSetFeature(Mips::FeatureDSP);
5639   } else if (Tok.getString() == "nodsp") {
5640     return parseSetNoDspDirective();
5641   } else if (Tok.getString() == "msa") {
5642     return parseSetMsaDirective();
5643   } else if (Tok.getString() == "nomsa") {
5644     return parseSetNoMsaDirective();
5645   } else if (Tok.getString() == "softfloat") {
5646     return parseSetSoftFloatDirective();
5647   } else if (Tok.getString() == "hardfloat") {
5648     return parseSetHardFloatDirective();
5649   } else {
5650     // It is just an identifier, look for an assignment.
5651     parseSetAssignment();
5652     return false;
5653   }
5654 
5655   return true;
5656 }
5657 
5658 /// parseDataDirective
5659 ///  ::= .word [ expression (, expression)* ]
5660 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
5661   MCAsmParser &Parser = getParser();
5662   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5663     for (;;) {
5664       const MCExpr *Value;
5665       if (getParser().parseExpression(Value))
5666         return true;
5667 
5668       getParser().getStreamer().EmitValue(Value, Size);
5669 
5670       if (getLexer().is(AsmToken::EndOfStatement))
5671         break;
5672 
5673       if (getLexer().isNot(AsmToken::Comma))
5674         return Error(L, "unexpected token, expected comma");
5675       Parser.Lex();
5676     }
5677   }
5678 
5679   Parser.Lex();
5680   return false;
5681 }
5682 
5683 /// parseDirectiveGpWord
5684 ///  ::= .gpword local_sym
5685 bool MipsAsmParser::parseDirectiveGpWord() {
5686   MCAsmParser &Parser = getParser();
5687   const MCExpr *Value;
5688   // EmitGPRel32Value requires an expression, so we are using base class
5689   // method to evaluate the expression.
5690   if (getParser().parseExpression(Value))
5691     return true;
5692   getParser().getStreamer().EmitGPRel32Value(Value);
5693 
5694   if (getLexer().isNot(AsmToken::EndOfStatement))
5695     return Error(getLexer().getLoc(),
5696                 "unexpected token, expected end of statement");
5697   Parser.Lex(); // Eat EndOfStatement token.
5698   return false;
5699 }
5700 
5701 /// parseDirectiveGpDWord
5702 ///  ::= .gpdword local_sym
5703 bool MipsAsmParser::parseDirectiveGpDWord() {
5704   MCAsmParser &Parser = getParser();
5705   const MCExpr *Value;
5706   // EmitGPRel64Value requires an expression, so we are using base class
5707   // method to evaluate the expression.
5708   if (getParser().parseExpression(Value))
5709     return true;
5710   getParser().getStreamer().EmitGPRel64Value(Value);
5711 
5712   if (getLexer().isNot(AsmToken::EndOfStatement))
5713     return Error(getLexer().getLoc(),
5714                 "unexpected token, expected end of statement");
5715   Parser.Lex(); // Eat EndOfStatement token.
5716   return false;
5717 }
5718 
5719 bool MipsAsmParser::parseDirectiveOption() {
5720   MCAsmParser &Parser = getParser();
5721   // Get the option token.
5722   AsmToken Tok = Parser.getTok();
5723   // At the moment only identifiers are supported.
5724   if (Tok.isNot(AsmToken::Identifier)) {
5725     Error(Parser.getTok().getLoc(), "unexpected token, expected identifier");
5726     Parser.eatToEndOfStatement();
5727     return false;
5728   }
5729 
5730   StringRef Option = Tok.getIdentifier();
5731 
5732   if (Option == "pic0") {
5733     // MipsAsmParser needs to know if the current PIC mode changes.
5734     IsPicEnabled = false;
5735 
5736     getTargetStreamer().emitDirectiveOptionPic0();
5737     Parser.Lex();
5738     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5739       Error(Parser.getTok().getLoc(),
5740             "unexpected token, expected end of statement");
5741       Parser.eatToEndOfStatement();
5742     }
5743     return false;
5744   }
5745 
5746   if (Option == "pic2") {
5747     // MipsAsmParser needs to know if the current PIC mode changes.
5748     IsPicEnabled = true;
5749 
5750     getTargetStreamer().emitDirectiveOptionPic2();
5751     Parser.Lex();
5752     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5753       Error(Parser.getTok().getLoc(),
5754             "unexpected token, expected end of statement");
5755       Parser.eatToEndOfStatement();
5756     }
5757     return false;
5758   }
5759 
5760   // Unknown option.
5761   Warning(Parser.getTok().getLoc(),
5762           "unknown option, expected 'pic0' or 'pic2'");
5763   Parser.eatToEndOfStatement();
5764   return false;
5765 }
5766 
5767 /// parseInsnDirective
5768 ///  ::= .insn
5769 bool MipsAsmParser::parseInsnDirective() {
5770   // If this is not the end of the statement, report an error.
5771   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5772     reportParseError("unexpected token, expected end of statement");
5773     return false;
5774   }
5775 
5776   // The actual label marking happens in
5777   // MipsELFStreamer::createPendingLabelRelocs().
5778   getTargetStreamer().emitDirectiveInsn();
5779 
5780   getParser().Lex(); // Eat EndOfStatement token.
5781   return false;
5782 }
5783 
5784 /// parseSSectionDirective
5785 ///  ::= .sbss
5786 ///  ::= .sdata
5787 bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) {
5788   // If this is not the end of the statement, report an error.
5789   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5790     reportParseError("unexpected token, expected end of statement");
5791     return false;
5792   }
5793 
5794   MCSection *ELFSection = getContext().getELFSection(
5795       Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
5796   getParser().getStreamer().SwitchSection(ELFSection);
5797 
5798   getParser().Lex(); // Eat EndOfStatement token.
5799   return false;
5800 }
5801 
5802 /// parseDirectiveModule
5803 ///  ::= .module oddspreg
5804 ///  ::= .module nooddspreg
5805 ///  ::= .module fp=value
5806 ///  ::= .module softfloat
5807 ///  ::= .module hardfloat
5808 bool MipsAsmParser::parseDirectiveModule() {
5809   MCAsmParser &Parser = getParser();
5810   MCAsmLexer &Lexer = getLexer();
5811   SMLoc L = Lexer.getLoc();
5812 
5813   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
5814     // TODO : get a better message.
5815     reportParseError(".module directive must appear before any code");
5816     return false;
5817   }
5818 
5819   StringRef Option;
5820   if (Parser.parseIdentifier(Option)) {
5821     reportParseError("expected .module option identifier");
5822     return false;
5823   }
5824 
5825   if (Option == "oddspreg") {
5826     clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5827 
5828     // Synchronize the abiflags information with the FeatureBits information we
5829     // changed above.
5830     getTargetStreamer().updateABIInfo(*this);
5831 
5832     // If printing assembly, use the recently updated abiflags information.
5833     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5834     // emitted at the end).
5835     getTargetStreamer().emitDirectiveModuleOddSPReg();
5836 
5837     // If this is not the end of the statement, report an error.
5838     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5839       reportParseError("unexpected token, expected end of statement");
5840       return false;
5841     }
5842 
5843     return false; // parseDirectiveModule has finished successfully.
5844   } else if (Option == "nooddspreg") {
5845     if (!isABI_O32()) {
5846       Error(L, "'.module nooddspreg' requires the O32 ABI");
5847       return false;
5848     }
5849 
5850     setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5851 
5852     // Synchronize the abiflags information with the FeatureBits information we
5853     // changed above.
5854     getTargetStreamer().updateABIInfo(*this);
5855 
5856     // If printing assembly, use the recently updated abiflags information.
5857     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5858     // emitted at the end).
5859     getTargetStreamer().emitDirectiveModuleOddSPReg();
5860 
5861     // If this is not the end of the statement, report an error.
5862     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5863       reportParseError("unexpected token, expected end of statement");
5864       return false;
5865     }
5866 
5867     return false; // parseDirectiveModule has finished successfully.
5868   } else if (Option == "fp") {
5869     return parseDirectiveModuleFP();
5870   } else if (Option == "softfloat") {
5871     setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5872 
5873     // Synchronize the ABI Flags information with the FeatureBits information we
5874     // updated above.
5875     getTargetStreamer().updateABIInfo(*this);
5876 
5877     // If printing assembly, use the recently updated ABI Flags information.
5878     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5879     // emitted later).
5880     getTargetStreamer().emitDirectiveModuleSoftFloat();
5881 
5882     // If this is not the end of the statement, report an error.
5883     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5884       reportParseError("unexpected token, expected end of statement");
5885       return false;
5886     }
5887 
5888     return false; // parseDirectiveModule has finished successfully.
5889   } else if (Option == "hardfloat") {
5890     clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5891 
5892     // Synchronize the ABI Flags information with the FeatureBits information we
5893     // updated above.
5894     getTargetStreamer().updateABIInfo(*this);
5895 
5896     // If printing assembly, use the recently updated ABI Flags information.
5897     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5898     // emitted later).
5899     getTargetStreamer().emitDirectiveModuleHardFloat();
5900 
5901     // If this is not the end of the statement, report an error.
5902     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5903       reportParseError("unexpected token, expected end of statement");
5904       return false;
5905     }
5906 
5907     return false; // parseDirectiveModule has finished successfully.
5908   } else {
5909     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
5910   }
5911 }
5912 
5913 /// parseDirectiveModuleFP
5914 ///  ::= =32
5915 ///  ::= =xx
5916 ///  ::= =64
5917 bool MipsAsmParser::parseDirectiveModuleFP() {
5918   MCAsmParser &Parser = getParser();
5919   MCAsmLexer &Lexer = getLexer();
5920 
5921   if (Lexer.isNot(AsmToken::Equal)) {
5922     reportParseError("unexpected token, expected equals sign '='");
5923     return false;
5924   }
5925   Parser.Lex(); // Eat '=' token.
5926 
5927   MipsABIFlagsSection::FpABIKind FpABI;
5928   if (!parseFpABIValue(FpABI, ".module"))
5929     return false;
5930 
5931   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5932     reportParseError("unexpected token, expected end of statement");
5933     return false;
5934   }
5935 
5936   // Synchronize the abiflags information with the FeatureBits information we
5937   // changed above.
5938   getTargetStreamer().updateABIInfo(*this);
5939 
5940   // If printing assembly, use the recently updated abiflags information.
5941   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5942   // emitted at the end).
5943   getTargetStreamer().emitDirectiveModuleFP();
5944 
5945   Parser.Lex(); // Consume the EndOfStatement.
5946   return false;
5947 }
5948 
5949 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
5950                                     StringRef Directive) {
5951   MCAsmParser &Parser = getParser();
5952   MCAsmLexer &Lexer = getLexer();
5953   bool ModuleLevelOptions = Directive == ".module";
5954 
5955   if (Lexer.is(AsmToken::Identifier)) {
5956     StringRef Value = Parser.getTok().getString();
5957     Parser.Lex();
5958 
5959     if (Value != "xx") {
5960       reportParseError("unsupported value, expected 'xx', '32' or '64'");
5961       return false;
5962     }
5963 
5964     if (!isABI_O32()) {
5965       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
5966       return false;
5967     }
5968 
5969     FpABI = MipsABIFlagsSection::FpABIKind::XX;
5970     if (ModuleLevelOptions) {
5971       setModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
5972       clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
5973     } else {
5974       setFeatureBits(Mips::FeatureFPXX, "fpxx");
5975       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
5976     }
5977     return true;
5978   }
5979 
5980   if (Lexer.is(AsmToken::Integer)) {
5981     unsigned Value = Parser.getTok().getIntVal();
5982     Parser.Lex();
5983 
5984     if (Value != 32 && Value != 64) {
5985       reportParseError("unsupported value, expected 'xx', '32' or '64'");
5986       return false;
5987     }
5988 
5989     if (Value == 32) {
5990       if (!isABI_O32()) {
5991         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
5992         return false;
5993       }
5994 
5995       FpABI = MipsABIFlagsSection::FpABIKind::S32;
5996       if (ModuleLevelOptions) {
5997         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
5998         clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
5999       } else {
6000         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6001         clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6002       }
6003     } else {
6004       FpABI = MipsABIFlagsSection::FpABIKind::S64;
6005       if (ModuleLevelOptions) {
6006         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6007         setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6008       } else {
6009         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6010         setFeatureBits(Mips::FeatureFP64Bit, "fp64");
6011       }
6012     }
6013 
6014     return true;
6015   }
6016 
6017   return false;
6018 }
6019 
6020 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
6021   // This returns false if this function recognizes the directive
6022   // regardless of whether it is successfully handles or reports an
6023   // error. Otherwise it returns true to give the generic parser a
6024   // chance at recognizing it.
6025 
6026   MCAsmParser &Parser = getParser();
6027   StringRef IDVal = DirectiveID.getString();
6028 
6029   if (IDVal == ".cpload") {
6030     parseDirectiveCpLoad(DirectiveID.getLoc());
6031     return false;
6032   }
6033   if (IDVal == ".cprestore") {
6034     parseDirectiveCpRestore(DirectiveID.getLoc());
6035     return false;
6036   }
6037   if (IDVal == ".dword") {
6038     parseDataDirective(8, DirectiveID.getLoc());
6039     return false;
6040   }
6041   if (IDVal == ".ent") {
6042     StringRef SymbolName;
6043 
6044     if (Parser.parseIdentifier(SymbolName)) {
6045       reportParseError("expected identifier after .ent");
6046       return false;
6047     }
6048 
6049     // There's an undocumented extension that allows an integer to
6050     // follow the name of the procedure which AFAICS is ignored by GAS.
6051     // Example: .ent foo,2
6052     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6053       if (getLexer().isNot(AsmToken::Comma)) {
6054         // Even though we accept this undocumented extension for compatibility
6055         // reasons, the additional integer argument does not actually change
6056         // the behaviour of the '.ent' directive, so we would like to discourage
6057         // its use. We do this by not referring to the extended version in
6058         // error messages which are not directly related to its use.
6059         reportParseError("unexpected token, expected end of statement");
6060         return false;
6061       }
6062       Parser.Lex(); // Eat the comma.
6063       const MCExpr *DummyNumber;
6064       int64_t DummyNumberVal;
6065       // If the user was explicitly trying to use the extended version,
6066       // we still give helpful extension-related error messages.
6067       if (Parser.parseExpression(DummyNumber)) {
6068         reportParseError("expected number after comma");
6069         return false;
6070       }
6071       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
6072         reportParseError("expected an absolute expression after comma");
6073         return false;
6074       }
6075     }
6076 
6077     // If this is not the end of the statement, report an error.
6078     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6079       reportParseError("unexpected token, expected end of statement");
6080       return false;
6081     }
6082 
6083     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
6084 
6085     getTargetStreamer().emitDirectiveEnt(*Sym);
6086     CurrentFn = Sym;
6087     IsCpRestoreSet = false;
6088     return false;
6089   }
6090 
6091   if (IDVal == ".end") {
6092     StringRef SymbolName;
6093 
6094     if (Parser.parseIdentifier(SymbolName)) {
6095       reportParseError("expected identifier after .end");
6096       return false;
6097     }
6098 
6099     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6100       reportParseError("unexpected token, expected end of statement");
6101       return false;
6102     }
6103 
6104     if (CurrentFn == nullptr) {
6105       reportParseError(".end used without .ent");
6106       return false;
6107     }
6108 
6109     if ((SymbolName != CurrentFn->getName())) {
6110       reportParseError(".end symbol does not match .ent symbol");
6111       return false;
6112     }
6113 
6114     getTargetStreamer().emitDirectiveEnd(SymbolName);
6115     CurrentFn = nullptr;
6116     IsCpRestoreSet = false;
6117     return false;
6118   }
6119 
6120   if (IDVal == ".frame") {
6121     // .frame $stack_reg, frame_size_in_bytes, $return_reg
6122     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
6123     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
6124     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6125       reportParseError("expected stack register");
6126       return false;
6127     }
6128 
6129     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6130     if (!StackRegOpnd.isGPRAsmReg()) {
6131       reportParseError(StackRegOpnd.getStartLoc(),
6132                        "expected general purpose register");
6133       return false;
6134     }
6135     unsigned StackReg = StackRegOpnd.getGPR32Reg();
6136 
6137     if (Parser.getTok().is(AsmToken::Comma))
6138       Parser.Lex();
6139     else {
6140       reportParseError("unexpected token, expected comma");
6141       return false;
6142     }
6143 
6144     // Parse the frame size.
6145     const MCExpr *FrameSize;
6146     int64_t FrameSizeVal;
6147 
6148     if (Parser.parseExpression(FrameSize)) {
6149       reportParseError("expected frame size value");
6150       return false;
6151     }
6152 
6153     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
6154       reportParseError("frame size not an absolute expression");
6155       return false;
6156     }
6157 
6158     if (Parser.getTok().is(AsmToken::Comma))
6159       Parser.Lex();
6160     else {
6161       reportParseError("unexpected token, expected comma");
6162       return false;
6163     }
6164 
6165     // Parse the return register.
6166     TmpReg.clear();
6167     ResTy = parseAnyRegister(TmpReg);
6168     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6169       reportParseError("expected return register");
6170       return false;
6171     }
6172 
6173     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6174     if (!ReturnRegOpnd.isGPRAsmReg()) {
6175       reportParseError(ReturnRegOpnd.getStartLoc(),
6176                        "expected general purpose register");
6177       return false;
6178     }
6179 
6180     // If this is not the end of the statement, report an error.
6181     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6182       reportParseError("unexpected token, expected end of statement");
6183       return false;
6184     }
6185 
6186     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
6187                                   ReturnRegOpnd.getGPR32Reg());
6188     IsCpRestoreSet = false;
6189     return false;
6190   }
6191 
6192   if (IDVal == ".set") {
6193     parseDirectiveSet();
6194     return false;
6195   }
6196 
6197   if (IDVal == ".mask" || IDVal == ".fmask") {
6198     // .mask bitmask, frame_offset
6199     // bitmask: One bit for each register used.
6200     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
6201     //               first register is expected to be saved.
6202     // Examples:
6203     //   .mask 0x80000000, -4
6204     //   .fmask 0x80000000, -4
6205     //
6206 
6207     // Parse the bitmask
6208     const MCExpr *BitMask;
6209     int64_t BitMaskVal;
6210 
6211     if (Parser.parseExpression(BitMask)) {
6212       reportParseError("expected bitmask value");
6213       return false;
6214     }
6215 
6216     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
6217       reportParseError("bitmask not an absolute expression");
6218       return false;
6219     }
6220 
6221     if (Parser.getTok().is(AsmToken::Comma))
6222       Parser.Lex();
6223     else {
6224       reportParseError("unexpected token, expected comma");
6225       return false;
6226     }
6227 
6228     // Parse the frame_offset
6229     const MCExpr *FrameOffset;
6230     int64_t FrameOffsetVal;
6231 
6232     if (Parser.parseExpression(FrameOffset)) {
6233       reportParseError("expected frame offset value");
6234       return false;
6235     }
6236 
6237     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
6238       reportParseError("frame offset not an absolute expression");
6239       return false;
6240     }
6241 
6242     // If this is not the end of the statement, report an error.
6243     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6244       reportParseError("unexpected token, expected end of statement");
6245       return false;
6246     }
6247 
6248     if (IDVal == ".mask")
6249       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
6250     else
6251       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
6252     return false;
6253   }
6254 
6255   if (IDVal == ".nan")
6256     return parseDirectiveNaN();
6257 
6258   if (IDVal == ".gpword") {
6259     parseDirectiveGpWord();
6260     return false;
6261   }
6262 
6263   if (IDVal == ".gpdword") {
6264     parseDirectiveGpDWord();
6265     return false;
6266   }
6267 
6268   if (IDVal == ".word") {
6269     parseDataDirective(4, DirectiveID.getLoc());
6270     return false;
6271   }
6272 
6273   if (IDVal == ".hword") {
6274     parseDataDirective(2, DirectiveID.getLoc());
6275     return false;
6276   }
6277 
6278   if (IDVal == ".option") {
6279     parseDirectiveOption();
6280     return false;
6281   }
6282 
6283   if (IDVal == ".abicalls") {
6284     getTargetStreamer().emitDirectiveAbiCalls();
6285     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
6286       Error(Parser.getTok().getLoc(),
6287             "unexpected token, expected end of statement");
6288       // Clear line
6289       Parser.eatToEndOfStatement();
6290     }
6291     return false;
6292   }
6293 
6294   if (IDVal == ".cpsetup") {
6295     parseDirectiveCPSetup();
6296     return false;
6297   }
6298   if (IDVal == ".cpreturn") {
6299     parseDirectiveCPReturn();
6300     return false;
6301   }
6302   if (IDVal == ".module") {
6303     parseDirectiveModule();
6304     return false;
6305   }
6306   if (IDVal == ".llvm_internal_mips_reallow_module_directive") {
6307     parseInternalDirectiveReallowModule();
6308     return false;
6309   }
6310   if (IDVal == ".insn") {
6311     parseInsnDirective();
6312     return false;
6313   }
6314   if (IDVal == ".sbss") {
6315     parseSSectionDirective(IDVal, ELF::SHT_NOBITS);
6316     return false;
6317   }
6318   if (IDVal == ".sdata") {
6319     parseSSectionDirective(IDVal, ELF::SHT_PROGBITS);
6320     return false;
6321   }
6322 
6323   return true;
6324 }
6325 
6326 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
6327   // If this is not the end of the statement, report an error.
6328   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6329     reportParseError("unexpected token, expected end of statement");
6330     return false;
6331   }
6332 
6333   getTargetStreamer().reallowModuleDirective();
6334 
6335   getParser().Lex(); // Eat EndOfStatement token.
6336   return false;
6337 }
6338 
6339 extern "C" void LLVMInitializeMipsAsmParser() {
6340   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
6341   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
6342   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
6343   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
6344 }
6345 
6346 #define GET_REGISTER_MATCHER
6347 #define GET_MATCHER_IMPLEMENTATION
6348 #include "MipsGenAsmMatcher.inc"
6349