1 //===-- RISCVAsmParser.cpp - Parse RISCV assembly to MCInst instructions --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MCTargetDesc/RISCVAsmBackend.h"
10 #include "MCTargetDesc/RISCVBaseInfo.h"
11 #include "MCTargetDesc/RISCVInstPrinter.h"
12 #include "MCTargetDesc/RISCVMCExpr.h"
13 #include "MCTargetDesc/RISCVMCTargetDesc.h"
14 #include "MCTargetDesc/RISCVMatInt.h"
15 #include "MCTargetDesc/RISCVTargetStreamer.h"
16 #include "TargetInfo/RISCVTargetInfo.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstBuilder.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmLexer.h"
30 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCValue.h"
36 #include "llvm/MC/TargetRegistry.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/RISCVAttributes.h"
40 #include "llvm/Support/RISCVISAInfo.h"
41 
42 #include <limits>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "riscv-asm-parser"
47 
48 // Include the auto-generated portion of the compress emitter.
49 #define GEN_COMPRESS_INSTR
50 #include "RISCVGenCompressInstEmitter.inc"
51 
52 STATISTIC(RISCVNumInstrsCompressed,
53           "Number of RISC-V Compressed instructions emitted");
54 
55 namespace llvm {
56 extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
57 } // namespace llvm
58 
59 namespace {
60 struct RISCVOperand;
61 
62 struct ParserOptionsSet {
63   bool IsPicEnabled;
64 };
65 
66 class RISCVAsmParser : public MCTargetAsmParser {
67   SmallVector<FeatureBitset, 4> FeatureBitStack;
68 
69   SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
70   ParserOptionsSet ParserOptions;
71 
72   SMLoc getLoc() const { return getParser().getTok().getLoc(); }
73   bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
74   bool isRV32E() const { return getSTI().hasFeature(RISCV::FeatureRV32E); }
75 
76   RISCVTargetStreamer &getTargetStreamer() {
77     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
78     return static_cast<RISCVTargetStreamer &>(TS);
79   }
80 
81   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
82                                       unsigned Kind) override;
83 
84   bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
85                                   int64_t Lower, int64_t Upper, Twine Msg);
86 
87   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
88                                OperandVector &Operands, MCStreamer &Out,
89                                uint64_t &ErrorInfo,
90                                bool MatchingInlineAsm) override;
91 
92   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
93   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
94                                         SMLoc &EndLoc) override;
95 
96   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
97                         SMLoc NameLoc, OperandVector &Operands) override;
98 
99   bool ParseDirective(AsmToken DirectiveID) override;
100 
101   // Helper to actually emit an instruction to the MCStreamer. Also, when
102   // possible, compression of the instruction is performed.
103   void emitToStreamer(MCStreamer &S, const MCInst &Inst);
104 
105   // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
106   // synthesize the desired immedate value into the destination register.
107   void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
108 
109   // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
110   // helpers such as emitLoadLocalAddress and emitLoadAddress.
111   void emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
112                          const MCExpr *Symbol, RISCVMCExpr::VariantKind VKHi,
113                          unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
114 
115   // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
116   void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
117 
118   // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
119   void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
120 
121   // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
122   // addressing.
123   void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
124 
125   // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
126   // addressing.
127   void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
128 
129   // Helper to emit pseudo load/store instruction with a symbol.
130   void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
131                            MCStreamer &Out, bool HasTmpReg);
132 
133   // Helper to emit pseudo sign/zero extend instruction.
134   void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
135                         SMLoc IDLoc, MCStreamer &Out);
136 
137   // Helper to emit pseudo vmsge{u}.vx instruction.
138   void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
139 
140   // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
141   // Enforcing this using a restricted register class for the second input
142   // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
143   // 'add' is an overloaded mnemonic.
144   bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
145 
146   // Check instruction constraints.
147   bool validateInstruction(MCInst &Inst, OperandVector &Operands);
148 
149   /// Helper for processing MC instructions that have been successfully matched
150   /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
151   /// like the expansion of pseudo instructions (e.g., "li"), can be performed
152   /// in this method.
153   bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
154                           MCStreamer &Out);
155 
156 // Auto-generated instruction matching functions
157 #define GET_ASSEMBLER_HEADER
158 #include "RISCVGenAsmMatcher.inc"
159 
160   OperandMatchResultTy parseCSRSystemRegister(OperandVector &Operands);
161   OperandMatchResultTy parseImmediate(OperandVector &Operands);
162   OperandMatchResultTy parseRegister(OperandVector &Operands,
163                                      bool AllowParens = false);
164   OperandMatchResultTy parseMemOpBaseReg(OperandVector &Operands);
165   OperandMatchResultTy parseAtomicMemOp(OperandVector &Operands);
166   OperandMatchResultTy parseOperandWithModifier(OperandVector &Operands);
167   OperandMatchResultTy parseBareSymbol(OperandVector &Operands);
168   OperandMatchResultTy parseCallSymbol(OperandVector &Operands);
169   OperandMatchResultTy parsePseudoJumpSymbol(OperandVector &Operands);
170   OperandMatchResultTy parseJALOffset(OperandVector &Operands);
171   OperandMatchResultTy parseVTypeI(OperandVector &Operands);
172   OperandMatchResultTy parseMaskReg(OperandVector &Operands);
173   OperandMatchResultTy parseInsnDirectiveOpcode(OperandVector &Operands);
174   OperandMatchResultTy parseGPRAsFPR(OperandVector &Operands);
175 
176   bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
177 
178   bool parseDirectiveOption();
179   bool parseDirectiveAttribute();
180   bool parseDirectiveInsn(SMLoc L);
181 
182   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
183     if (!(getSTI().getFeatureBits()[Feature])) {
184       MCSubtargetInfo &STI = copySTI();
185       setAvailableFeatures(
186           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
187     }
188   }
189 
190   bool getFeatureBits(uint64_t Feature) {
191     return getSTI().getFeatureBits()[Feature];
192   }
193 
194   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
195     if (getSTI().getFeatureBits()[Feature]) {
196       MCSubtargetInfo &STI = copySTI();
197       setAvailableFeatures(
198           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
199     }
200   }
201 
202   void pushFeatureBits() {
203     assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
204            "These two stacks must be kept synchronized");
205     FeatureBitStack.push_back(getSTI().getFeatureBits());
206     ParserOptionsStack.push_back(ParserOptions);
207   }
208 
209   bool popFeatureBits() {
210     assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
211            "These two stacks must be kept synchronized");
212     if (FeatureBitStack.empty())
213       return true;
214 
215     FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
216     copySTI().setFeatureBits(FeatureBits);
217     setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
218 
219     ParserOptions = ParserOptionsStack.pop_back_val();
220 
221     return false;
222   }
223 
224   std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
225 
226 public:
227   enum RISCVMatchResultTy {
228     Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
229 #define GET_OPERAND_DIAGNOSTIC_TYPES
230 #include "RISCVGenAsmMatcher.inc"
231 #undef GET_OPERAND_DIAGNOSTIC_TYPES
232   };
233 
234   static bool classifySymbolRef(const MCExpr *Expr,
235                                 RISCVMCExpr::VariantKind &Kind);
236 
237   RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
238                  const MCInstrInfo &MII, const MCTargetOptions &Options)
239       : MCTargetAsmParser(Options, STI, MII) {
240     Parser.addAliasForDirective(".half", ".2byte");
241     Parser.addAliasForDirective(".hword", ".2byte");
242     Parser.addAliasForDirective(".word", ".4byte");
243     Parser.addAliasForDirective(".dword", ".8byte");
244     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
245 
246     auto ABIName = StringRef(Options.ABIName);
247     if (ABIName.endswith("f") &&
248         !getSTI().getFeatureBits()[RISCV::FeatureStdExtF]) {
249       errs() << "Hard-float 'f' ABI can't be used for a target that "
250                 "doesn't support the F instruction set extension (ignoring "
251                 "target-abi)\n";
252     } else if (ABIName.endswith("d") &&
253                !getSTI().getFeatureBits()[RISCV::FeatureStdExtD]) {
254       errs() << "Hard-float 'd' ABI can't be used for a target that "
255                 "doesn't support the D instruction set extension (ignoring "
256                 "target-abi)\n";
257     }
258 
259     const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
260     ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
261   }
262 };
263 
264 /// RISCVOperand - Instances of this class represent a parsed machine
265 /// instruction
266 struct RISCVOperand : public MCParsedAsmOperand {
267 
268   enum class KindTy {
269     Token,
270     Register,
271     Immediate,
272     SystemRegister,
273     VType,
274   } Kind;
275 
276   bool IsRV64;
277 
278   bool IsGPRAsFPR;
279 
280   struct RegOp {
281     MCRegister RegNum;
282   };
283 
284   struct ImmOp {
285     const MCExpr *Val;
286   };
287 
288   struct SysRegOp {
289     const char *Data;
290     unsigned Length;
291     unsigned Encoding;
292     // FIXME: Add the Encoding parsed fields as needed for checks,
293     // e.g.: read/write or user/supervisor/machine privileges.
294   };
295 
296   struct VTypeOp {
297     unsigned Val;
298   };
299 
300   SMLoc StartLoc, EndLoc;
301   union {
302     StringRef Tok;
303     RegOp Reg;
304     ImmOp Imm;
305     struct SysRegOp SysReg;
306     struct VTypeOp VType;
307   };
308 
309   RISCVOperand(KindTy K) : Kind(K) {}
310 
311 public:
312   RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
313     Kind = o.Kind;
314     IsRV64 = o.IsRV64;
315     StartLoc = o.StartLoc;
316     EndLoc = o.EndLoc;
317     switch (Kind) {
318     case KindTy::Register:
319       Reg = o.Reg;
320       break;
321     case KindTy::Immediate:
322       Imm = o.Imm;
323       break;
324     case KindTy::Token:
325       Tok = o.Tok;
326       break;
327     case KindTy::SystemRegister:
328       SysReg = o.SysReg;
329       break;
330     case KindTy::VType:
331       VType = o.VType;
332       break;
333     }
334   }
335 
336   bool isToken() const override { return Kind == KindTy::Token; }
337   bool isReg() const override { return Kind == KindTy::Register; }
338   bool isV0Reg() const {
339     return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
340   }
341   bool isImm() const override { return Kind == KindTy::Immediate; }
342   bool isMem() const override { return false; }
343   bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
344 
345   bool isGPR() const {
346     return Kind == KindTy::Register &&
347            RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum);
348   }
349 
350   bool isGPRAsFPR() const { return isGPR() && IsGPRAsFPR; }
351 
352   bool isGPRF64AsFPR() const { return isGPR() && IsGPRAsFPR && IsRV64; }
353 
354   bool isGPRPF64AsFPR() const {
355     return isGPR() && IsGPRAsFPR && !IsRV64 && !((Reg.RegNum - RISCV::X0) & 1);
356   }
357 
358   static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
359                                   RISCVMCExpr::VariantKind &VK) {
360     if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
361       VK = RE->getKind();
362       return RE->evaluateAsConstant(Imm);
363     }
364 
365     if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
366       VK = RISCVMCExpr::VK_RISCV_None;
367       Imm = CE->getValue();
368       return true;
369     }
370 
371     return false;
372   }
373 
374   // True if operand is a symbol with no modifiers, or a constant with no
375   // modifiers and isShiftedInt<N-1, 1>(Op).
376   template <int N> bool isBareSimmNLsb0() const {
377     int64_t Imm;
378     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
379     if (!isImm())
380       return false;
381     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
382     bool IsValid;
383     if (!IsConstantImm)
384       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
385     else
386       IsValid = isShiftedInt<N - 1, 1>(Imm);
387     return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
388   }
389 
390   // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
391 
392   bool isBareSymbol() const {
393     int64_t Imm;
394     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
395     // Must be of 'immediate' type but not a constant.
396     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
397       return false;
398     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
399            VK == RISCVMCExpr::VK_RISCV_None;
400   }
401 
402   bool isCallSymbol() const {
403     int64_t Imm;
404     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
405     // Must be of 'immediate' type but not a constant.
406     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
407       return false;
408     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
409            (VK == RISCVMCExpr::VK_RISCV_CALL ||
410             VK == RISCVMCExpr::VK_RISCV_CALL_PLT);
411   }
412 
413   bool isPseudoJumpSymbol() const {
414     int64_t Imm;
415     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
416     // Must be of 'immediate' type but not a constant.
417     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
418       return false;
419     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
420            VK == RISCVMCExpr::VK_RISCV_CALL;
421   }
422 
423   bool isTPRelAddSymbol() const {
424     int64_t Imm;
425     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
426     // Must be of 'immediate' type but not a constant.
427     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
428       return false;
429     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
430            VK == RISCVMCExpr::VK_RISCV_TPREL_ADD;
431   }
432 
433   bool isCSRSystemRegister() const { return isSystemRegister(); }
434 
435   bool isVTypeImm(unsigned N) const {
436     int64_t Imm;
437     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
438     if (!isImm())
439       return false;
440     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
441     return IsConstantImm && isUIntN(N, Imm) && VK == RISCVMCExpr::VK_RISCV_None;
442   }
443 
444   // If the last operand of the vsetvli/vsetvli instruction is a constant
445   // expression, KindTy is Immediate.
446   bool isVTypeI10() const {
447     if (Kind == KindTy::Immediate)
448       return isVTypeImm(10);
449     return Kind == KindTy::VType;
450   }
451   bool isVTypeI11() const {
452     if (Kind == KindTy::Immediate)
453       return isVTypeImm(11);
454     return Kind == KindTy::VType;
455   }
456 
457   /// Return true if the operand is a valid for the fence instruction e.g.
458   /// ('iorw').
459   bool isFenceArg() const {
460     if (!isImm())
461       return false;
462 
463     int64_t Imm;
464     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
465     if (evaluateConstantImm(getImm(), Imm, VK)) {
466       // Only accept 0 as a constant immediate.
467       return VK == RISCVMCExpr::VK_RISCV_None && Imm == 0;
468     }
469 
470     auto *SVal = dyn_cast<MCSymbolRefExpr>(getImm());
471 
472     if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
473       return false;
474 
475     StringRef Str = SVal->getSymbol().getName();
476     // Letters must be unique, taken from 'iorw', and in ascending order. This
477     // holds as long as each individual character is one of 'iorw' and is
478     // greater than the previous character.
479     char Prev = '\0';
480     for (char c : Str) {
481       if (c != 'i' && c != 'o' && c != 'r' && c != 'w')
482         return false;
483       if (c <= Prev)
484         return false;
485       Prev = c;
486     }
487     return true;
488   }
489 
490   /// Return true if the operand is a valid floating point rounding mode.
491   bool isFRMArg() const {
492     if (!isImm())
493       return false;
494     const MCExpr *Val = getImm();
495     auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
496     if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
497       return false;
498 
499     StringRef Str = SVal->getSymbol().getName();
500 
501     return RISCVFPRndMode::stringToRoundingMode(Str) != RISCVFPRndMode::Invalid;
502   }
503 
504   bool isImmXLenLI() const {
505     int64_t Imm;
506     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
507     if (!isImm())
508       return false;
509     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
510     if (VK == RISCVMCExpr::VK_RISCV_LO || VK == RISCVMCExpr::VK_RISCV_PCREL_LO)
511       return true;
512     // Given only Imm, ensuring that the actually specified constant is either
513     // a signed or unsigned 64-bit number is unfortunately impossible.
514     return IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None &&
515            (isRV64() || (isInt<32>(Imm) || isUInt<32>(Imm)));
516   }
517 
518   bool isUImmLog2XLen() const {
519     int64_t Imm;
520     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
521     if (!isImm())
522       return false;
523     if (!evaluateConstantImm(getImm(), Imm, VK) ||
524         VK != RISCVMCExpr::VK_RISCV_None)
525       return false;
526     return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
527   }
528 
529   bool isUImmLog2XLenNonZero() const {
530     int64_t Imm;
531     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
532     if (!isImm())
533       return false;
534     if (!evaluateConstantImm(getImm(), Imm, VK) ||
535         VK != RISCVMCExpr::VK_RISCV_None)
536       return false;
537     if (Imm == 0)
538       return false;
539     return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
540   }
541 
542   bool isUImmLog2XLenHalf() const {
543     int64_t Imm;
544     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
545     if (!isImm())
546       return false;
547     if (!evaluateConstantImm(getImm(), Imm, VK) ||
548         VK != RISCVMCExpr::VK_RISCV_None)
549       return false;
550     return (isRV64() && isUInt<5>(Imm)) || isUInt<4>(Imm);
551   }
552 
553   bool isUImm2() const {
554     int64_t Imm;
555     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
556     if (!isImm())
557       return false;
558     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
559     return IsConstantImm && isUInt<2>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
560   }
561 
562   bool isUImm3() const {
563     int64_t Imm;
564     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
565     if (!isImm())
566       return false;
567     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
568     return IsConstantImm && isUInt<3>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
569   }
570 
571   bool isUImm5() const {
572     int64_t Imm;
573     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
574     if (!isImm())
575       return false;
576     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
577     return IsConstantImm && isUInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
578   }
579 
580   bool isUImm7() const {
581     int64_t Imm;
582     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
583     if (!isImm())
584       return false;
585     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
586     return IsConstantImm && isUInt<7>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
587   }
588 
589   bool isRnumArg() const {
590     int64_t Imm;
591     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
592     if (!isImm())
593       return false;
594     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
595     return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(10) &&
596            VK == RISCVMCExpr::VK_RISCV_None;
597   }
598 
599   bool isSImm5() const {
600     if (!isImm())
601       return false;
602     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
603     int64_t Imm;
604     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
605     return IsConstantImm && isInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
606   }
607 
608   bool isSImm6() const {
609     if (!isImm())
610       return false;
611     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
612     int64_t Imm;
613     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
614     return IsConstantImm && isInt<6>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
615   }
616 
617   bool isSImm6NonZero() const {
618     if (!isImm())
619       return false;
620     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
621     int64_t Imm;
622     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
623     return IsConstantImm && isInt<6>(Imm) && (Imm != 0) &&
624            VK == RISCVMCExpr::VK_RISCV_None;
625   }
626 
627   bool isCLUIImm() const {
628     if (!isImm())
629       return false;
630     int64_t Imm;
631     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
632     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
633     return IsConstantImm && (Imm != 0) &&
634            (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
635            VK == RISCVMCExpr::VK_RISCV_None;
636   }
637 
638   bool isUImm7Lsb00() const {
639     if (!isImm())
640       return false;
641     int64_t Imm;
642     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
643     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
644     return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
645            VK == RISCVMCExpr::VK_RISCV_None;
646   }
647 
648   bool isUImm8Lsb00() const {
649     if (!isImm())
650       return false;
651     int64_t Imm;
652     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
653     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
654     return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
655            VK == RISCVMCExpr::VK_RISCV_None;
656   }
657 
658   bool isUImm8Lsb000() const {
659     if (!isImm())
660       return false;
661     int64_t Imm;
662     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
663     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
664     return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
665            VK == RISCVMCExpr::VK_RISCV_None;
666   }
667 
668   bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
669 
670   bool isUImm9Lsb000() const {
671     if (!isImm())
672       return false;
673     int64_t Imm;
674     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
675     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
676     return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
677            VK == RISCVMCExpr::VK_RISCV_None;
678   }
679 
680   bool isUImm10Lsb00NonZero() const {
681     if (!isImm())
682       return false;
683     int64_t Imm;
684     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
685     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
686     return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
687            VK == RISCVMCExpr::VK_RISCV_None;
688   }
689 
690   bool isSImm12() const {
691     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
692     int64_t Imm;
693     bool IsValid;
694     if (!isImm())
695       return false;
696     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
697     if (!IsConstantImm)
698       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
699     else
700       IsValid = isInt<12>(Imm);
701     return IsValid && ((IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None) ||
702                        VK == RISCVMCExpr::VK_RISCV_LO ||
703                        VK == RISCVMCExpr::VK_RISCV_PCREL_LO ||
704                        VK == RISCVMCExpr::VK_RISCV_TPREL_LO);
705   }
706 
707   bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
708 
709   bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
710 
711   bool isSImm10Lsb0000NonZero() const {
712     if (!isImm())
713       return false;
714     int64_t Imm;
715     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
716     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
717     return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
718            VK == RISCVMCExpr::VK_RISCV_None;
719   }
720 
721   bool isUImm20LUI() const {
722     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
723     int64_t Imm;
724     bool IsValid;
725     if (!isImm())
726       return false;
727     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
728     if (!IsConstantImm) {
729       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
730       return IsValid && (VK == RISCVMCExpr::VK_RISCV_HI ||
731                          VK == RISCVMCExpr::VK_RISCV_TPREL_HI);
732     } else {
733       return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
734                                  VK == RISCVMCExpr::VK_RISCV_HI ||
735                                  VK == RISCVMCExpr::VK_RISCV_TPREL_HI);
736     }
737   }
738 
739   bool isUImm20AUIPC() const {
740     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
741     int64_t Imm;
742     bool IsValid;
743     if (!isImm())
744       return false;
745     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
746     if (!IsConstantImm) {
747       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
748       return IsValid && (VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
749                          VK == RISCVMCExpr::VK_RISCV_GOT_HI ||
750                          VK == RISCVMCExpr::VK_RISCV_TLS_GOT_HI ||
751                          VK == RISCVMCExpr::VK_RISCV_TLS_GD_HI);
752     } else {
753       return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
754                                  VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
755                                  VK == RISCVMCExpr::VK_RISCV_GOT_HI ||
756                                  VK == RISCVMCExpr::VK_RISCV_TLS_GOT_HI ||
757                                  VK == RISCVMCExpr::VK_RISCV_TLS_GD_HI);
758     }
759   }
760 
761   bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
762 
763   bool isImmZero() const {
764     if (!isImm())
765       return false;
766     int64_t Imm;
767     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
768     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
769     return IsConstantImm && (Imm == 0) && VK == RISCVMCExpr::VK_RISCV_None;
770   }
771 
772   bool isSImm5Plus1() const {
773     if (!isImm())
774       return false;
775     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
776     int64_t Imm;
777     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
778     return IsConstantImm && isInt<5>(Imm - 1) &&
779            VK == RISCVMCExpr::VK_RISCV_None;
780   }
781 
782   /// getStartLoc - Gets location of the first token of this operand
783   SMLoc getStartLoc() const override { return StartLoc; }
784   /// getEndLoc - Gets location of the last token of this operand
785   SMLoc getEndLoc() const override { return EndLoc; }
786   /// True if this operand is for an RV64 instruction
787   bool isRV64() const { return IsRV64; }
788 
789   unsigned getReg() const override {
790     assert(Kind == KindTy::Register && "Invalid type access!");
791     return Reg.RegNum.id();
792   }
793 
794   StringRef getSysReg() const {
795     assert(Kind == KindTy::SystemRegister && "Invalid type access!");
796     return StringRef(SysReg.Data, SysReg.Length);
797   }
798 
799   const MCExpr *getImm() const {
800     assert(Kind == KindTy::Immediate && "Invalid type access!");
801     return Imm.Val;
802   }
803 
804   StringRef getToken() const {
805     assert(Kind == KindTy::Token && "Invalid type access!");
806     return Tok;
807   }
808 
809   unsigned getVType() const {
810     assert(Kind == KindTy::VType && "Invalid type access!");
811     return VType.Val;
812   }
813 
814   void print(raw_ostream &OS) const override {
815     auto RegName = [](unsigned Reg) {
816       if (Reg)
817         return RISCVInstPrinter::getRegisterName(Reg);
818       else
819         return "noreg";
820     };
821 
822     switch (Kind) {
823     case KindTy::Immediate:
824       OS << *getImm();
825       break;
826     case KindTy::Register:
827       OS << "<register " << RegName(getReg()) << ">";
828       break;
829     case KindTy::Token:
830       OS << "'" << getToken() << "'";
831       break;
832     case KindTy::SystemRegister:
833       OS << "<sysreg: " << getSysReg() << '>';
834       break;
835     case KindTy::VType:
836       OS << "<vtype: ";
837       RISCVVType::printVType(getVType(), OS);
838       OS << '>';
839       break;
840     }
841   }
842 
843   static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
844                                                    bool IsRV64) {
845     auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
846     Op->Tok = Str;
847     Op->StartLoc = S;
848     Op->EndLoc = S;
849     Op->IsRV64 = IsRV64;
850     return Op;
851   }
852 
853   static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
854                                                  SMLoc E, bool IsRV64,
855                                                  bool IsGPRAsFPR = false) {
856     auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
857     Op->Reg.RegNum = RegNo;
858     Op->StartLoc = S;
859     Op->EndLoc = E;
860     Op->IsRV64 = IsRV64;
861     Op->IsGPRAsFPR = IsGPRAsFPR;
862     return Op;
863   }
864 
865   static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
866                                                  SMLoc E, bool IsRV64) {
867     auto Op = std::make_unique<RISCVOperand>(KindTy::Immediate);
868     Op->Imm.Val = Val;
869     Op->StartLoc = S;
870     Op->EndLoc = E;
871     Op->IsRV64 = IsRV64;
872     return Op;
873   }
874 
875   static std::unique_ptr<RISCVOperand>
876   createSysReg(StringRef Str, SMLoc S, unsigned Encoding, bool IsRV64) {
877     auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
878     Op->SysReg.Data = Str.data();
879     Op->SysReg.Length = Str.size();
880     Op->SysReg.Encoding = Encoding;
881     Op->StartLoc = S;
882     Op->EndLoc = S;
883     Op->IsRV64 = IsRV64;
884     return Op;
885   }
886 
887   static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S,
888                                                    bool IsRV64) {
889     auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
890     Op->VType.Val = VTypeI;
891     Op->StartLoc = S;
892     Op->EndLoc = S;
893     Op->IsRV64 = IsRV64;
894     return Op;
895   }
896 
897   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
898     assert(Expr && "Expr shouldn't be null!");
899     int64_t Imm = 0;
900     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
901     bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
902 
903     if (IsConstant)
904       Inst.addOperand(MCOperand::createImm(Imm));
905     else
906       Inst.addOperand(MCOperand::createExpr(Expr));
907   }
908 
909   // Used by the TableGen Code
910   void addRegOperands(MCInst &Inst, unsigned N) const {
911     assert(N == 1 && "Invalid number of operands!");
912     Inst.addOperand(MCOperand::createReg(getReg()));
913   }
914 
915   void addImmOperands(MCInst &Inst, unsigned N) const {
916     assert(N == 1 && "Invalid number of operands!");
917     addExpr(Inst, getImm());
918   }
919 
920   void addFenceArgOperands(MCInst &Inst, unsigned N) const {
921     assert(N == 1 && "Invalid number of operands!");
922 
923     int64_t Constant = 0;
924     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
925     if (evaluateConstantImm(getImm(), Constant, VK)) {
926       if (Constant == 0) {
927         Inst.addOperand(MCOperand::createImm(Constant));
928         return;
929       }
930       llvm_unreachable("FenceArg must contain only [iorw] or be 0");
931     }
932 
933     // isFenceArg has validated the operand, meaning this cast is safe
934     auto SE = cast<MCSymbolRefExpr>(getImm());
935 
936     unsigned Imm = 0;
937     for (char c : SE->getSymbol().getName()) {
938       switch (c) {
939       default:
940         llvm_unreachable("FenceArg must contain only [iorw] or be 0");
941       case 'i':
942         Imm |= RISCVFenceField::I;
943         break;
944       case 'o':
945         Imm |= RISCVFenceField::O;
946         break;
947       case 'r':
948         Imm |= RISCVFenceField::R;
949         break;
950       case 'w':
951         Imm |= RISCVFenceField::W;
952         break;
953       }
954     }
955     Inst.addOperand(MCOperand::createImm(Imm));
956   }
957 
958   void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
959     assert(N == 1 && "Invalid number of operands!");
960     Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
961   }
962 
963   // Support non-canonical syntax:
964   // "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
965   // "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
966   void addVTypeIOperands(MCInst &Inst, unsigned N) const {
967     assert(N == 1 && "Invalid number of operands!");
968     int64_t Imm = 0;
969     if (Kind == KindTy::Immediate) {
970       RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
971       bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
972       (void)IsConstantImm;
973       assert(IsConstantImm && "Invalid VTypeI Operand!");
974     } else {
975       Imm = getVType();
976     }
977     Inst.addOperand(MCOperand::createImm(Imm));
978   }
979 
980   // Returns the rounding mode represented by this RISCVOperand. Should only
981   // be called after checking isFRMArg.
982   RISCVFPRndMode::RoundingMode getRoundingMode() const {
983     // isFRMArg has validated the operand, meaning this cast is safe.
984     auto SE = cast<MCSymbolRefExpr>(getImm());
985     RISCVFPRndMode::RoundingMode FRM =
986         RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
987     assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
988     return FRM;
989   }
990 
991   void addFRMArgOperands(MCInst &Inst, unsigned N) const {
992     assert(N == 1 && "Invalid number of operands!");
993     Inst.addOperand(MCOperand::createImm(getRoundingMode()));
994   }
995 };
996 } // end anonymous namespace.
997 
998 #define GET_REGISTER_MATCHER
999 #define GET_SUBTARGET_FEATURE_NAME
1000 #define GET_MATCHER_IMPLEMENTATION
1001 #define GET_MNEMONIC_SPELL_CHECKER
1002 #include "RISCVGenAsmMatcher.inc"
1003 
1004 static MCRegister convertFPR64ToFPR16(MCRegister Reg) {
1005   assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1006   return Reg - RISCV::F0_D + RISCV::F0_H;
1007 }
1008 
1009 static MCRegister convertFPR64ToFPR32(MCRegister Reg) {
1010   assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1011   return Reg - RISCV::F0_D + RISCV::F0_F;
1012 }
1013 
1014 static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg,
1015                                   unsigned Kind) {
1016   unsigned RegClassID;
1017   if (Kind == MCK_VRM2)
1018     RegClassID = RISCV::VRM2RegClassID;
1019   else if (Kind == MCK_VRM4)
1020     RegClassID = RISCV::VRM4RegClassID;
1021   else if (Kind == MCK_VRM8)
1022     RegClassID = RISCV::VRM8RegClassID;
1023   else
1024     return 0;
1025   return RI.getMatchingSuperReg(Reg, RISCV::sub_vrm1_0,
1026                                 &RISCVMCRegisterClasses[RegClassID]);
1027 }
1028 
1029 unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1030                                                     unsigned Kind) {
1031   RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
1032   if (!Op.isReg())
1033     return Match_InvalidOperand;
1034 
1035   MCRegister Reg = Op.getReg();
1036   bool IsRegFPR64 =
1037       RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
1038   bool IsRegFPR64C =
1039       RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
1040   bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
1041 
1042   // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
1043   // register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
1044   if ((IsRegFPR64 && Kind == MCK_FPR32) ||
1045       (IsRegFPR64C && Kind == MCK_FPR32C)) {
1046     Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
1047     return Match_Success;
1048   }
1049   // As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
1050   // register from FPR64 to FPR16 if necessary.
1051   if (IsRegFPR64 && Kind == MCK_FPR16) {
1052     Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
1053     return Match_Success;
1054   }
1055   // As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
1056   // the register from VR to VRM2/VRM4/VRM8 if necessary.
1057   if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
1058     Op.Reg.RegNum = convertVRToVRMx(*getContext().getRegisterInfo(), Reg, Kind);
1059     if (Op.Reg.RegNum == 0)
1060       return Match_InvalidOperand;
1061     return Match_Success;
1062   }
1063   return Match_InvalidOperand;
1064 }
1065 
1066 bool RISCVAsmParser::generateImmOutOfRangeError(
1067     OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
1068     Twine Msg = "immediate must be an integer in the range") {
1069   SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1070   return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
1071 }
1072 
1073 bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1074                                              OperandVector &Operands,
1075                                              MCStreamer &Out,
1076                                              uint64_t &ErrorInfo,
1077                                              bool MatchingInlineAsm) {
1078   MCInst Inst;
1079   FeatureBitset MissingFeatures;
1080 
1081   auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
1082                                      MatchingInlineAsm);
1083   switch (Result) {
1084   default:
1085     break;
1086   case Match_Success:
1087     if (validateInstruction(Inst, Operands))
1088       return true;
1089     return processInstruction(Inst, IDLoc, Operands, Out);
1090   case Match_MissingFeature: {
1091     assert(MissingFeatures.any() && "Unknown missing features!");
1092     bool FirstFeature = true;
1093     std::string Msg = "instruction requires the following:";
1094     for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
1095       if (MissingFeatures[i]) {
1096         Msg += FirstFeature ? " " : ", ";
1097         Msg += getSubtargetFeatureName(i);
1098         FirstFeature = false;
1099       }
1100     }
1101     return Error(IDLoc, Msg);
1102   }
1103   case Match_MnemonicFail: {
1104     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1105     std::string Suggestion = RISCVMnemonicSpellCheck(
1106         ((RISCVOperand &)*Operands[0]).getToken(), FBS, 0);
1107     return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
1108   }
1109   case Match_InvalidOperand: {
1110     SMLoc ErrorLoc = IDLoc;
1111     if (ErrorInfo != ~0ULL) {
1112       if (ErrorInfo >= Operands.size())
1113         return Error(ErrorLoc, "too few operands for instruction");
1114 
1115       ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1116       if (ErrorLoc == SMLoc())
1117         ErrorLoc = IDLoc;
1118     }
1119     return Error(ErrorLoc, "invalid operand for instruction");
1120   }
1121   }
1122 
1123   // Handle the case when the error message is of specific type
1124   // other than the generic Match_InvalidOperand, and the
1125   // corresponding operand is missing.
1126   if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
1127     SMLoc ErrorLoc = IDLoc;
1128     if (ErrorInfo != ~0ULL && ErrorInfo >= Operands.size())
1129       return Error(ErrorLoc, "too few operands for instruction");
1130   }
1131 
1132   switch (Result) {
1133   default:
1134     break;
1135   case Match_InvalidImmXLenLI:
1136     if (isRV64()) {
1137       SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1138       return Error(ErrorLoc, "operand must be a constant 64-bit integer");
1139     }
1140     return generateImmOutOfRangeError(Operands, ErrorInfo,
1141                                       std::numeric_limits<int32_t>::min(),
1142                                       std::numeric_limits<uint32_t>::max());
1143   case Match_InvalidImmZero: {
1144     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1145     return Error(ErrorLoc, "immediate must be zero");
1146   }
1147   case Match_InvalidUImmLog2XLen:
1148     if (isRV64())
1149       return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1150     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1151   case Match_InvalidUImmLog2XLenNonZero:
1152     if (isRV64())
1153       return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
1154     return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
1155   case Match_InvalidUImmLog2XLenHalf:
1156     if (isRV64())
1157       return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1158     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1159   case Match_InvalidUImm2:
1160     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 2) - 1);
1161   case Match_InvalidUImm3:
1162     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 3) - 1);
1163   case Match_InvalidUImm5:
1164     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1165   case Match_InvalidUImm7:
1166     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 7) - 1);
1167   case Match_InvalidSImm5:
1168     return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4),
1169                                       (1 << 4) - 1);
1170   case Match_InvalidSImm6:
1171     return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
1172                                       (1 << 5) - 1);
1173   case Match_InvalidSImm6NonZero:
1174     return generateImmOutOfRangeError(
1175         Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
1176         "immediate must be non-zero in the range");
1177   case Match_InvalidCLUIImm:
1178     return generateImmOutOfRangeError(
1179         Operands, ErrorInfo, 1, (1 << 5) - 1,
1180         "immediate must be in [0xfffe0, 0xfffff] or");
1181   case Match_InvalidUImm7Lsb00:
1182     return generateImmOutOfRangeError(
1183         Operands, ErrorInfo, 0, (1 << 7) - 4,
1184         "immediate must be a multiple of 4 bytes in the range");
1185   case Match_InvalidUImm8Lsb00:
1186     return generateImmOutOfRangeError(
1187         Operands, ErrorInfo, 0, (1 << 8) - 4,
1188         "immediate must be a multiple of 4 bytes in the range");
1189   case Match_InvalidUImm8Lsb000:
1190     return generateImmOutOfRangeError(
1191         Operands, ErrorInfo, 0, (1 << 8) - 8,
1192         "immediate must be a multiple of 8 bytes in the range");
1193   case Match_InvalidSImm9Lsb0:
1194     return generateImmOutOfRangeError(
1195         Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
1196         "immediate must be a multiple of 2 bytes in the range");
1197   case Match_InvalidUImm9Lsb000:
1198     return generateImmOutOfRangeError(
1199         Operands, ErrorInfo, 0, (1 << 9) - 8,
1200         "immediate must be a multiple of 8 bytes in the range");
1201   case Match_InvalidUImm10Lsb00NonZero:
1202     return generateImmOutOfRangeError(
1203         Operands, ErrorInfo, 4, (1 << 10) - 4,
1204         "immediate must be a multiple of 4 bytes in the range");
1205   case Match_InvalidSImm10Lsb0000NonZero:
1206     return generateImmOutOfRangeError(
1207         Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
1208         "immediate must be a multiple of 16 bytes and non-zero in the range");
1209   case Match_InvalidSImm12:
1210     return generateImmOutOfRangeError(
1211         Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
1212         "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an "
1213         "integer in the range");
1214   case Match_InvalidSImm12Lsb0:
1215     return generateImmOutOfRangeError(
1216         Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
1217         "immediate must be a multiple of 2 bytes in the range");
1218   case Match_InvalidSImm13Lsb0:
1219     return generateImmOutOfRangeError(
1220         Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
1221         "immediate must be a multiple of 2 bytes in the range");
1222   case Match_InvalidUImm20LUI:
1223     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
1224                                       "operand must be a symbol with "
1225                                       "%hi/%tprel_hi modifier or an integer in "
1226                                       "the range");
1227   case Match_InvalidUImm20AUIPC:
1228     return generateImmOutOfRangeError(
1229         Operands, ErrorInfo, 0, (1 << 20) - 1,
1230         "operand must be a symbol with a "
1231         "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi modifier or "
1232         "an integer in the range");
1233   case Match_InvalidSImm21Lsb0JAL:
1234     return generateImmOutOfRangeError(
1235         Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
1236         "immediate must be a multiple of 2 bytes in the range");
1237   case Match_InvalidCSRSystemRegister: {
1238     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
1239                                       "operand must be a valid system register "
1240                                       "name or an integer in the range");
1241   }
1242   case Match_InvalidFenceArg: {
1243     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1244     return Error(ErrorLoc, "operand must be formed of letters selected "
1245                            "in-order from 'iorw' or be 0");
1246   }
1247   case Match_InvalidFRMArg: {
1248     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1249     return Error(
1250         ErrorLoc,
1251         "operand must be a valid floating point rounding mode mnemonic");
1252   }
1253   case Match_InvalidBareSymbol: {
1254     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1255     return Error(ErrorLoc, "operand must be a bare symbol name");
1256   }
1257   case Match_InvalidPseudoJumpSymbol: {
1258     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1259     return Error(ErrorLoc, "operand must be a valid jump target");
1260   }
1261   case Match_InvalidCallSymbol: {
1262     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1263     return Error(ErrorLoc, "operand must be a bare symbol name");
1264   }
1265   case Match_InvalidTPRelAddSymbol: {
1266     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1267     return Error(ErrorLoc, "operand must be a symbol with %tprel_add modifier");
1268   }
1269   case Match_InvalidVTypeI: {
1270     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1271     return Error(
1272         ErrorLoc,
1273         "operand must be "
1274         "e[8|16|32|64|128|256|512|1024],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
1275   }
1276   case Match_InvalidVMaskRegister: {
1277     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1278     return Error(ErrorLoc, "operand must be v0.t");
1279   }
1280   case Match_InvalidSImm5Plus1: {
1281     return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4) + 1,
1282                                       (1 << 4),
1283                                       "immediate must be in the range");
1284   }
1285   case Match_InvalidRnumArg: {
1286     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 10);
1287   }
1288   }
1289 
1290   llvm_unreachable("Unknown match type detected!");
1291 }
1292 
1293 // Attempts to match Name as a register (either using the default name or
1294 // alternative ABI names), setting RegNo to the matching register. Upon
1295 // failure, returns true and sets RegNo to 0. If IsRV32E then registers
1296 // x16-x31 will be rejected.
1297 static bool matchRegisterNameHelper(bool IsRV32E, MCRegister &RegNo,
1298                                     StringRef Name) {
1299   RegNo = MatchRegisterName(Name);
1300   // The 16-/32- and 64-bit FPRs have the same asm name. Check that the initial
1301   // match always matches the 64-bit variant, and not the 16/32-bit one.
1302   assert(!(RegNo >= RISCV::F0_H && RegNo <= RISCV::F31_H));
1303   assert(!(RegNo >= RISCV::F0_F && RegNo <= RISCV::F31_F));
1304   // The default FPR register class is based on the tablegen enum ordering.
1305   static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1306   static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1307   if (RegNo == RISCV::NoRegister)
1308     RegNo = MatchRegisterAltName(Name);
1309   if (IsRV32E && RegNo >= RISCV::X16 && RegNo <= RISCV::X31)
1310     RegNo = RISCV::NoRegister;
1311   return RegNo == RISCV::NoRegister;
1312 }
1313 
1314 bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1315                                    SMLoc &EndLoc) {
1316   if (tryParseRegister(RegNo, StartLoc, EndLoc) != MatchOperand_Success)
1317     return Error(StartLoc, "invalid register name");
1318   return false;
1319 }
1320 
1321 OperandMatchResultTy RISCVAsmParser::tryParseRegister(unsigned &RegNo,
1322                                                       SMLoc &StartLoc,
1323                                                       SMLoc &EndLoc) {
1324   const AsmToken &Tok = getParser().getTok();
1325   StartLoc = Tok.getLoc();
1326   EndLoc = Tok.getEndLoc();
1327   RegNo = 0;
1328   StringRef Name = getLexer().getTok().getIdentifier();
1329 
1330   if (matchRegisterNameHelper(isRV32E(), (MCRegister &)RegNo, Name))
1331     return MatchOperand_NoMatch;
1332 
1333   getParser().Lex(); // Eat identifier token.
1334   return MatchOperand_Success;
1335 }
1336 
1337 OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
1338                                                    bool AllowParens) {
1339   SMLoc FirstS = getLoc();
1340   bool HadParens = false;
1341   AsmToken LParen;
1342 
1343   // If this is an LParen and a parenthesised register name is allowed, parse it
1344   // atomically.
1345   if (AllowParens && getLexer().is(AsmToken::LParen)) {
1346     AsmToken Buf[2];
1347     size_t ReadCount = getLexer().peekTokens(Buf);
1348     if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1349       HadParens = true;
1350       LParen = getParser().getTok();
1351       getParser().Lex(); // Eat '('
1352     }
1353   }
1354 
1355   switch (getLexer().getKind()) {
1356   default:
1357     if (HadParens)
1358       getLexer().UnLex(LParen);
1359     return MatchOperand_NoMatch;
1360   case AsmToken::Identifier:
1361     StringRef Name = getLexer().getTok().getIdentifier();
1362     MCRegister RegNo;
1363     matchRegisterNameHelper(isRV32E(), RegNo, Name);
1364 
1365     if (RegNo == RISCV::NoRegister) {
1366       if (HadParens)
1367         getLexer().UnLex(LParen);
1368       return MatchOperand_NoMatch;
1369     }
1370     if (HadParens)
1371       Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
1372     SMLoc S = getLoc();
1373     SMLoc E = SMLoc::getFromPointer(S.getPointer() + Name.size());
1374     getLexer().Lex();
1375     Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
1376   }
1377 
1378   if (HadParens) {
1379     getParser().Lex(); // Eat ')'
1380     Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
1381   }
1382 
1383   return MatchOperand_Success;
1384 }
1385 
1386 OperandMatchResultTy
1387 RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
1388   SMLoc S = getLoc();
1389   SMLoc E;
1390   const MCExpr *Res;
1391 
1392   switch (getLexer().getKind()) {
1393   default:
1394     return MatchOperand_NoMatch;
1395   case AsmToken::LParen:
1396   case AsmToken::Minus:
1397   case AsmToken::Plus:
1398   case AsmToken::Exclaim:
1399   case AsmToken::Tilde:
1400   case AsmToken::Integer:
1401   case AsmToken::String: {
1402     if (getParser().parseExpression(Res, E))
1403       return MatchOperand_ParseFail;
1404 
1405     auto *CE = dyn_cast<MCConstantExpr>(Res);
1406     if (CE) {
1407       int64_t Imm = CE->getValue();
1408       if (isUInt<7>(Imm)) {
1409         Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1410         return MatchOperand_Success;
1411       }
1412     }
1413 
1414     Twine Msg = "immediate must be an integer in the range";
1415     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 7) - 1) + "]");
1416     return MatchOperand_ParseFail;
1417   }
1418   case AsmToken::Identifier: {
1419     StringRef Identifier;
1420     if (getParser().parseIdentifier(Identifier))
1421       return MatchOperand_ParseFail;
1422 
1423     auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Identifier);
1424     if (Opcode) {
1425       Res = MCConstantExpr::create(Opcode->Value, getContext());
1426       E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
1427       Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1428       return MatchOperand_Success;
1429     }
1430 
1431     Twine Msg = "operand must be a valid opcode name or an "
1432                 "integer in the range";
1433     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 7) - 1) + "]");
1434     return MatchOperand_ParseFail;
1435   }
1436   case AsmToken::Percent: {
1437     // Discard operand with modifier.
1438     Twine Msg = "immediate must be an integer in the range";
1439     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 7) - 1) + "]");
1440     return MatchOperand_ParseFail;
1441   }
1442   }
1443 
1444   return MatchOperand_NoMatch;
1445 }
1446 
1447 OperandMatchResultTy
1448 RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1449   SMLoc S = getLoc();
1450   const MCExpr *Res;
1451 
1452   switch (getLexer().getKind()) {
1453   default:
1454     return MatchOperand_NoMatch;
1455   case AsmToken::LParen:
1456   case AsmToken::Minus:
1457   case AsmToken::Plus:
1458   case AsmToken::Exclaim:
1459   case AsmToken::Tilde:
1460   case AsmToken::Integer:
1461   case AsmToken::String: {
1462     if (getParser().parseExpression(Res))
1463       return MatchOperand_ParseFail;
1464 
1465     auto *CE = dyn_cast<MCConstantExpr>(Res);
1466     if (CE) {
1467       int64_t Imm = CE->getValue();
1468       if (isUInt<12>(Imm)) {
1469         auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
1470         // Accept an immediate representing a named or un-named Sys Reg
1471         // if the range is valid, regardless of the required features.
1472         Operands.push_back(RISCVOperand::createSysReg(
1473             SysReg ? SysReg->Name : "", S, Imm, isRV64()));
1474         return MatchOperand_Success;
1475       }
1476     }
1477 
1478     Twine Msg = "immediate must be an integer in the range";
1479     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1480     return MatchOperand_ParseFail;
1481   }
1482   case AsmToken::Identifier: {
1483     StringRef Identifier;
1484     if (getParser().parseIdentifier(Identifier))
1485       return MatchOperand_ParseFail;
1486 
1487     auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
1488     if (!SysReg)
1489       SysReg = RISCVSysReg::lookupSysRegByAltName(Identifier);
1490     if (!SysReg)
1491       if ((SysReg = RISCVSysReg::lookupSysRegByDeprecatedName(Identifier)))
1492         Warning(S, "'" + Identifier + "' is a deprecated alias for '" +
1493                        SysReg->Name + "'");
1494 
1495     // Accept a named Sys Reg if the required features are present.
1496     if (SysReg) {
1497       if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits())) {
1498         Error(S, "system register use requires an option to be enabled");
1499         return MatchOperand_ParseFail;
1500       }
1501       Operands.push_back(RISCVOperand::createSysReg(
1502           Identifier, S, SysReg->Encoding, isRV64()));
1503       return MatchOperand_Success;
1504     }
1505 
1506     Twine Msg = "operand must be a valid system register name "
1507                 "or an integer in the range";
1508     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1509     return MatchOperand_ParseFail;
1510   }
1511   case AsmToken::Percent: {
1512     // Discard operand with modifier.
1513     Twine Msg = "immediate must be an integer in the range";
1514     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1515     return MatchOperand_ParseFail;
1516   }
1517   }
1518 
1519   return MatchOperand_NoMatch;
1520 }
1521 
1522 OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
1523   SMLoc S = getLoc();
1524   SMLoc E;
1525   const MCExpr *Res;
1526 
1527   switch (getLexer().getKind()) {
1528   default:
1529     return MatchOperand_NoMatch;
1530   case AsmToken::LParen:
1531   case AsmToken::Dot:
1532   case AsmToken::Minus:
1533   case AsmToken::Plus:
1534   case AsmToken::Exclaim:
1535   case AsmToken::Tilde:
1536   case AsmToken::Integer:
1537   case AsmToken::String:
1538   case AsmToken::Identifier:
1539     if (getParser().parseExpression(Res, E))
1540       return MatchOperand_ParseFail;
1541     break;
1542   case AsmToken::Percent:
1543     return parseOperandWithModifier(Operands);
1544   }
1545 
1546   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1547   return MatchOperand_Success;
1548 }
1549 
1550 OperandMatchResultTy
1551 RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1552   SMLoc S = getLoc();
1553   SMLoc E;
1554 
1555   if (getLexer().getKind() != AsmToken::Percent) {
1556     Error(getLoc(), "expected '%' for operand modifier");
1557     return MatchOperand_ParseFail;
1558   }
1559 
1560   getParser().Lex(); // Eat '%'
1561 
1562   if (getLexer().getKind() != AsmToken::Identifier) {
1563     Error(getLoc(), "expected valid identifier for operand modifier");
1564     return MatchOperand_ParseFail;
1565   }
1566   StringRef Identifier = getParser().getTok().getIdentifier();
1567   RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
1568   if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
1569     Error(getLoc(), "unrecognized operand modifier");
1570     return MatchOperand_ParseFail;
1571   }
1572 
1573   getParser().Lex(); // Eat the identifier
1574   if (getLexer().getKind() != AsmToken::LParen) {
1575     Error(getLoc(), "expected '('");
1576     return MatchOperand_ParseFail;
1577   }
1578   getParser().Lex(); // Eat '('
1579 
1580   const MCExpr *SubExpr;
1581   if (getParser().parseParenExpression(SubExpr, E)) {
1582     return MatchOperand_ParseFail;
1583   }
1584 
1585   const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
1586   Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
1587   return MatchOperand_Success;
1588 }
1589 
1590 OperandMatchResultTy RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
1591   SMLoc S = getLoc();
1592   const MCExpr *Res;
1593 
1594   if (getLexer().getKind() != AsmToken::Identifier)
1595     return MatchOperand_NoMatch;
1596 
1597   StringRef Identifier;
1598   AsmToken Tok = getLexer().getTok();
1599 
1600   if (getParser().parseIdentifier(Identifier))
1601     return MatchOperand_ParseFail;
1602 
1603   SMLoc E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
1604 
1605   if (Identifier.consume_back("@plt")) {
1606     Error(getLoc(), "'@plt' operand not valid for instruction");
1607     return MatchOperand_ParseFail;
1608   }
1609 
1610   MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1611 
1612   if (Sym->isVariable()) {
1613     const MCExpr *V = Sym->getVariableValue(/*SetUsed=*/false);
1614     if (!isa<MCSymbolRefExpr>(V)) {
1615       getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
1616       return MatchOperand_NoMatch;
1617     }
1618     Res = V;
1619   } else
1620     Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1621 
1622   MCBinaryExpr::Opcode Opcode;
1623   switch (getLexer().getKind()) {
1624   default:
1625     Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1626     return MatchOperand_Success;
1627   case AsmToken::Plus:
1628     Opcode = MCBinaryExpr::Add;
1629     break;
1630   case AsmToken::Minus:
1631     Opcode = MCBinaryExpr::Sub;
1632     break;
1633   }
1634 
1635   const MCExpr *Expr;
1636   if (getParser().parseExpression(Expr, E))
1637     return MatchOperand_ParseFail;
1638   Res = MCBinaryExpr::create(Opcode, Res, Expr, getContext());
1639   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1640   return MatchOperand_Success;
1641 }
1642 
1643 OperandMatchResultTy RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
1644   SMLoc S = getLoc();
1645   const MCExpr *Res;
1646 
1647   if (getLexer().getKind() != AsmToken::Identifier)
1648     return MatchOperand_NoMatch;
1649 
1650   // Avoid parsing the register in `call rd, foo` as a call symbol.
1651   if (getLexer().peekTok().getKind() != AsmToken::EndOfStatement)
1652     return MatchOperand_NoMatch;
1653 
1654   StringRef Identifier;
1655   if (getParser().parseIdentifier(Identifier))
1656     return MatchOperand_ParseFail;
1657 
1658   SMLoc E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
1659 
1660   RISCVMCExpr::VariantKind Kind = RISCVMCExpr::VK_RISCV_CALL;
1661   if (Identifier.consume_back("@plt"))
1662     Kind = RISCVMCExpr::VK_RISCV_CALL_PLT;
1663 
1664   MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1665   Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1666   Res = RISCVMCExpr::create(Res, Kind, getContext());
1667   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1668   return MatchOperand_Success;
1669 }
1670 
1671 OperandMatchResultTy
1672 RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
1673   SMLoc S = getLoc();
1674   SMLoc E;
1675   const MCExpr *Res;
1676 
1677   if (getParser().parseExpression(Res, E))
1678     return MatchOperand_ParseFail;
1679 
1680   if (Res->getKind() != MCExpr::ExprKind::SymbolRef ||
1681       cast<MCSymbolRefExpr>(Res)->getKind() ==
1682           MCSymbolRefExpr::VariantKind::VK_PLT) {
1683     Error(S, "operand must be a valid jump target");
1684     return MatchOperand_ParseFail;
1685   }
1686 
1687   Res = RISCVMCExpr::create(Res, RISCVMCExpr::VK_RISCV_CALL, getContext());
1688   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1689   return MatchOperand_Success;
1690 }
1691 
1692 OperandMatchResultTy RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
1693   // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
1694   // both being acceptable forms. When parsing `jal ra, foo` this function
1695   // will be called for the `ra` register operand in an attempt to match the
1696   // single-operand alias. parseJALOffset must fail for this case. It would
1697   // seem logical to try parse the operand using parseImmediate and return
1698   // NoMatch if the next token is a comma (meaning we must be parsing a jal in
1699   // the second form rather than the first). We can't do this as there's no
1700   // way of rewinding the lexer state. Instead, return NoMatch if this operand
1701   // is an identifier and is followed by a comma.
1702   if (getLexer().is(AsmToken::Identifier) &&
1703       getLexer().peekTok().is(AsmToken::Comma))
1704     return MatchOperand_NoMatch;
1705 
1706   return parseImmediate(Operands);
1707 }
1708 
1709 OperandMatchResultTy RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
1710   SMLoc S = getLoc();
1711   if (getLexer().isNot(AsmToken::Identifier))
1712     return MatchOperand_NoMatch;
1713 
1714   SmallVector<AsmToken, 7> VTypeIElements;
1715   // Put all the tokens for vtypei operand into VTypeIElements vector.
1716   while (getLexer().isNot(AsmToken::EndOfStatement)) {
1717     VTypeIElements.push_back(getLexer().getTok());
1718     getLexer().Lex();
1719     if (getLexer().is(AsmToken::EndOfStatement))
1720       break;
1721     if (getLexer().isNot(AsmToken::Comma))
1722       goto MatchFail;
1723     AsmToken Comma = getLexer().getTok();
1724     VTypeIElements.push_back(Comma);
1725     getLexer().Lex();
1726   }
1727 
1728   if (VTypeIElements.size() == 7) {
1729     // The VTypeIElements layout is:
1730     // SEW comma LMUL comma TA comma MA
1731     //  0    1    2     3    4   5    6
1732     StringRef Name = VTypeIElements[0].getIdentifier();
1733     if (!Name.consume_front("e"))
1734       goto MatchFail;
1735     unsigned Sew;
1736     if (Name.getAsInteger(10, Sew))
1737       goto MatchFail;
1738     if (!RISCVVType::isValidSEW(Sew))
1739       goto MatchFail;
1740 
1741     Name = VTypeIElements[2].getIdentifier();
1742     if (!Name.consume_front("m"))
1743       goto MatchFail;
1744     // "m" or "mf"
1745     bool Fractional = Name.consume_front("f");
1746     unsigned Lmul;
1747     if (Name.getAsInteger(10, Lmul))
1748       goto MatchFail;
1749     if (!RISCVVType::isValidLMUL(Lmul, Fractional))
1750       goto MatchFail;
1751 
1752     // ta or tu
1753     Name = VTypeIElements[4].getIdentifier();
1754     bool TailAgnostic;
1755     if (Name == "ta")
1756       TailAgnostic = true;
1757     else if (Name == "tu")
1758       TailAgnostic = false;
1759     else
1760       goto MatchFail;
1761 
1762     // ma or mu
1763     Name = VTypeIElements[6].getIdentifier();
1764     bool MaskAgnostic;
1765     if (Name == "ma")
1766       MaskAgnostic = true;
1767     else if (Name == "mu")
1768       MaskAgnostic = false;
1769     else
1770       goto MatchFail;
1771 
1772     unsigned LmulLog2 = Log2_32(Lmul);
1773     RISCVII::VLMUL VLMUL =
1774         static_cast<RISCVII::VLMUL>(Fractional ? 8 - LmulLog2 : LmulLog2);
1775 
1776     unsigned VTypeI =
1777         RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
1778     Operands.push_back(RISCVOperand::createVType(VTypeI, S, isRV64()));
1779     return MatchOperand_Success;
1780   }
1781 
1782 // If NoMatch, unlex all the tokens that comprise a vtypei operand
1783 MatchFail:
1784   while (!VTypeIElements.empty())
1785     getLexer().UnLex(VTypeIElements.pop_back_val());
1786   return MatchOperand_NoMatch;
1787 }
1788 
1789 OperandMatchResultTy RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
1790   switch (getLexer().getKind()) {
1791   default:
1792     return MatchOperand_NoMatch;
1793   case AsmToken::Identifier:
1794     StringRef Name = getLexer().getTok().getIdentifier();
1795     if (!Name.consume_back(".t")) {
1796       Error(getLoc(), "expected '.t' suffix");
1797       return MatchOperand_ParseFail;
1798     }
1799     MCRegister RegNo;
1800     matchRegisterNameHelper(isRV32E(), RegNo, Name);
1801 
1802     if (RegNo == RISCV::NoRegister)
1803       return MatchOperand_NoMatch;
1804     if (RegNo != RISCV::V0)
1805       return MatchOperand_NoMatch;
1806     SMLoc S = getLoc();
1807     SMLoc E = SMLoc::getFromPointer(S.getPointer() + Name.size());
1808     getLexer().Lex();
1809     Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
1810   }
1811 
1812   return MatchOperand_Success;
1813 }
1814 
1815 OperandMatchResultTy RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
1816   switch (getLexer().getKind()) {
1817   default:
1818     return MatchOperand_NoMatch;
1819   case AsmToken::Identifier:
1820     StringRef Name = getLexer().getTok().getIdentifier();
1821     MCRegister RegNo;
1822     matchRegisterNameHelper(isRV32E(), RegNo, Name);
1823 
1824     if (RegNo == RISCV::NoRegister)
1825       return MatchOperand_NoMatch;
1826     SMLoc S = getLoc();
1827     SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1828     getLexer().Lex();
1829     Operands.push_back(RISCVOperand::createReg(
1830         RegNo, S, E, isRV64(), !getSTI().hasFeature(RISCV::FeatureStdExtF)));
1831   }
1832   return MatchOperand_Success;
1833 }
1834 
1835 OperandMatchResultTy
1836 RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
1837   if (getLexer().isNot(AsmToken::LParen)) {
1838     Error(getLoc(), "expected '('");
1839     return MatchOperand_ParseFail;
1840   }
1841 
1842   getParser().Lex(); // Eat '('
1843   Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
1844 
1845   if (parseRegister(Operands) != MatchOperand_Success) {
1846     Error(getLoc(), "expected register");
1847     return MatchOperand_ParseFail;
1848   }
1849 
1850   if (getLexer().isNot(AsmToken::RParen)) {
1851     Error(getLoc(), "expected ')'");
1852     return MatchOperand_ParseFail;
1853   }
1854 
1855   getParser().Lex(); // Eat ')'
1856   Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
1857 
1858   return MatchOperand_Success;
1859 }
1860 
1861 OperandMatchResultTy RISCVAsmParser::parseAtomicMemOp(OperandVector &Operands) {
1862   // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
1863   // as one of their register operands, such as `(a0)`. This just denotes that
1864   // the register (in this case `a0`) contains a memory address.
1865   //
1866   // Normally, we would be able to parse these by putting the parens into the
1867   // instruction string. However, GNU as also accepts a zero-offset memory
1868   // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
1869   // with parseImmediate followed by parseMemOpBaseReg, but these instructions
1870   // do not accept an immediate operand, and we do not want to add a "dummy"
1871   // operand that is silently dropped.
1872   //
1873   // Instead, we use this custom parser. This will: allow (and discard) an
1874   // offset if it is zero; require (and discard) parentheses; and add only the
1875   // parsed register operand to `Operands`.
1876   //
1877   // These operands are printed with RISCVInstPrinter::printAtomicMemOp, which
1878   // will only print the register surrounded by parentheses (which GNU as also
1879   // uses as its canonical representation for these operands).
1880   std::unique_ptr<RISCVOperand> OptionalImmOp;
1881 
1882   if (getLexer().isNot(AsmToken::LParen)) {
1883     // Parse an Integer token. We do not accept arbritrary constant expressions
1884     // in the offset field (because they may include parens, which complicates
1885     // parsing a lot).
1886     int64_t ImmVal;
1887     SMLoc ImmStart = getLoc();
1888     if (getParser().parseIntToken(ImmVal,
1889                                   "expected '(' or optional integer offset"))
1890       return MatchOperand_ParseFail;
1891 
1892     // Create a RISCVOperand for checking later (so the error messages are
1893     // nicer), but we don't add it to Operands.
1894     SMLoc ImmEnd = getLoc();
1895     OptionalImmOp =
1896         RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
1897                                 ImmStart, ImmEnd, isRV64());
1898   }
1899 
1900   if (getLexer().isNot(AsmToken::LParen)) {
1901     Error(getLoc(), OptionalImmOp ? "expected '(' after optional integer offset"
1902                                   : "expected '(' or optional integer offset");
1903     return MatchOperand_ParseFail;
1904   }
1905   getParser().Lex(); // Eat '('
1906 
1907   if (parseRegister(Operands) != MatchOperand_Success) {
1908     Error(getLoc(), "expected register");
1909     return MatchOperand_ParseFail;
1910   }
1911 
1912   if (getLexer().isNot(AsmToken::RParen)) {
1913     Error(getLoc(), "expected ')'");
1914     return MatchOperand_ParseFail;
1915   }
1916   getParser().Lex(); // Eat ')'
1917 
1918   // Deferred Handling of non-zero offsets. This makes the error messages nicer.
1919   if (OptionalImmOp && !OptionalImmOp->isImmZero()) {
1920     Error(OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
1921           SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
1922     return MatchOperand_ParseFail;
1923   }
1924 
1925   return MatchOperand_Success;
1926 }
1927 
1928 /// Looks at a token type and creates the relevant operand from this
1929 /// information, adding to Operands. If operand was parsed, returns false, else
1930 /// true.
1931 bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
1932   // Check if the current operand has a custom associated parser, if so, try to
1933   // custom parse the operand, or fallback to the general approach.
1934   OperandMatchResultTy Result =
1935       MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
1936   if (Result == MatchOperand_Success)
1937     return false;
1938   if (Result == MatchOperand_ParseFail)
1939     return true;
1940 
1941   // Attempt to parse token as a register.
1942   if (parseRegister(Operands, true) == MatchOperand_Success)
1943     return false;
1944 
1945   // Attempt to parse token as an immediate
1946   if (parseImmediate(Operands) == MatchOperand_Success) {
1947     // Parse memory base register if present
1948     if (getLexer().is(AsmToken::LParen))
1949       return parseMemOpBaseReg(Operands) != MatchOperand_Success;
1950     return false;
1951   }
1952 
1953   // Finally we have exhausted all options and must declare defeat.
1954   Error(getLoc(), "unknown operand");
1955   return true;
1956 }
1957 
1958 bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1959                                       StringRef Name, SMLoc NameLoc,
1960                                       OperandVector &Operands) {
1961   // Ensure that if the instruction occurs when relaxation is enabled,
1962   // relocations are forced for the file. Ideally this would be done when there
1963   // is enough information to reliably determine if the instruction itself may
1964   // cause relaxations. Unfortunately instruction processing stage occurs in the
1965   // same pass as relocation emission, so it's too late to set a 'sticky bit'
1966   // for the entire file.
1967   if (getSTI().getFeatureBits()[RISCV::FeatureRelax]) {
1968     auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
1969     if (Assembler != nullptr) {
1970       RISCVAsmBackend &MAB =
1971           static_cast<RISCVAsmBackend &>(Assembler->getBackend());
1972       MAB.setForceRelocs();
1973     }
1974   }
1975 
1976   // First operand is token for instruction
1977   Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
1978 
1979   // If there are no more operands, then finish
1980   if (getLexer().is(AsmToken::EndOfStatement)) {
1981     getParser().Lex(); // Consume the EndOfStatement.
1982     return false;
1983   }
1984 
1985   // Parse first operand
1986   if (parseOperand(Operands, Name))
1987     return true;
1988 
1989   // Parse until end of statement, consuming commas between operands
1990   unsigned OperandIdx = 1;
1991   while (getLexer().is(AsmToken::Comma)) {
1992     // Consume comma token
1993     getLexer().Lex();
1994 
1995     // Parse next operand
1996     if (parseOperand(Operands, Name))
1997       return true;
1998 
1999     ++OperandIdx;
2000   }
2001 
2002   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2003     SMLoc Loc = getLexer().getLoc();
2004     getParser().eatToEndOfStatement();
2005     return Error(Loc, "unexpected token");
2006   }
2007 
2008   getParser().Lex(); // Consume the EndOfStatement.
2009   return false;
2010 }
2011 
2012 bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2013                                        RISCVMCExpr::VariantKind &Kind) {
2014   Kind = RISCVMCExpr::VK_RISCV_None;
2015 
2016   if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
2017     Kind = RE->getKind();
2018     Expr = RE->getSubExpr();
2019   }
2020 
2021   MCValue Res;
2022   MCFixup Fixup;
2023   if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup))
2024     return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None;
2025   return false;
2026 }
2027 
2028 bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
2029   // This returns false if this function recognizes the directive
2030   // regardless of whether it is successfully handles or reports an
2031   // error. Otherwise it returns true to give the generic parser a
2032   // chance at recognizing it.
2033   StringRef IDVal = DirectiveID.getString();
2034 
2035   if (IDVal == ".option")
2036     return parseDirectiveOption();
2037   if (IDVal == ".attribute")
2038     return parseDirectiveAttribute();
2039   if (IDVal == ".insn")
2040     return parseDirectiveInsn(DirectiveID.getLoc());
2041 
2042   return true;
2043 }
2044 
2045 bool RISCVAsmParser::parseDirectiveOption() {
2046   MCAsmParser &Parser = getParser();
2047   // Get the option token.
2048   AsmToken Tok = Parser.getTok();
2049   // At the moment only identifiers are supported.
2050   if (Tok.isNot(AsmToken::Identifier))
2051     return Error(Parser.getTok().getLoc(),
2052                  "unexpected token, expected identifier");
2053 
2054   StringRef Option = Tok.getIdentifier();
2055 
2056   if (Option == "push") {
2057     getTargetStreamer().emitDirectiveOptionPush();
2058 
2059     Parser.Lex();
2060     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2061       return Error(Parser.getTok().getLoc(),
2062                    "unexpected token, expected end of statement");
2063 
2064     pushFeatureBits();
2065     return false;
2066   }
2067 
2068   if (Option == "pop") {
2069     SMLoc StartLoc = Parser.getTok().getLoc();
2070     getTargetStreamer().emitDirectiveOptionPop();
2071 
2072     Parser.Lex();
2073     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2074       return Error(Parser.getTok().getLoc(),
2075                    "unexpected token, expected end of statement");
2076 
2077     if (popFeatureBits())
2078       return Error(StartLoc, ".option pop with no .option push");
2079 
2080     return false;
2081   }
2082 
2083   if (Option == "rvc") {
2084     getTargetStreamer().emitDirectiveOptionRVC();
2085 
2086     Parser.Lex();
2087     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2088       return Error(Parser.getTok().getLoc(),
2089                    "unexpected token, expected end of statement");
2090 
2091     setFeatureBits(RISCV::FeatureStdExtC, "c");
2092     return false;
2093   }
2094 
2095   if (Option == "norvc") {
2096     getTargetStreamer().emitDirectiveOptionNoRVC();
2097 
2098     Parser.Lex();
2099     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2100       return Error(Parser.getTok().getLoc(),
2101                    "unexpected token, expected end of statement");
2102 
2103     clearFeatureBits(RISCV::FeatureStdExtC, "c");
2104     return false;
2105   }
2106 
2107   if (Option == "pic") {
2108     getTargetStreamer().emitDirectiveOptionPIC();
2109 
2110     Parser.Lex();
2111     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2112       return Error(Parser.getTok().getLoc(),
2113                    "unexpected token, expected end of statement");
2114 
2115     ParserOptions.IsPicEnabled = true;
2116     return false;
2117   }
2118 
2119   if (Option == "nopic") {
2120     getTargetStreamer().emitDirectiveOptionNoPIC();
2121 
2122     Parser.Lex();
2123     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2124       return Error(Parser.getTok().getLoc(),
2125                    "unexpected token, expected end of statement");
2126 
2127     ParserOptions.IsPicEnabled = false;
2128     return false;
2129   }
2130 
2131   if (Option == "relax") {
2132     getTargetStreamer().emitDirectiveOptionRelax();
2133 
2134     Parser.Lex();
2135     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2136       return Error(Parser.getTok().getLoc(),
2137                    "unexpected token, expected end of statement");
2138 
2139     setFeatureBits(RISCV::FeatureRelax, "relax");
2140     return false;
2141   }
2142 
2143   if (Option == "norelax") {
2144     getTargetStreamer().emitDirectiveOptionNoRelax();
2145 
2146     Parser.Lex();
2147     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
2148       return Error(Parser.getTok().getLoc(),
2149                    "unexpected token, expected end of statement");
2150 
2151     clearFeatureBits(RISCV::FeatureRelax, "relax");
2152     return false;
2153   }
2154 
2155   // Unknown option.
2156   Warning(Parser.getTok().getLoc(),
2157           "unknown option, expected 'push', 'pop', 'rvc', 'norvc', 'relax' or "
2158           "'norelax'");
2159   Parser.eatToEndOfStatement();
2160   return false;
2161 }
2162 
2163 /// parseDirectiveAttribute
2164 ///  ::= .attribute expression ',' ( expression | "string" )
2165 ///  ::= .attribute identifier ',' ( expression | "string" )
2166 bool RISCVAsmParser::parseDirectiveAttribute() {
2167   MCAsmParser &Parser = getParser();
2168   int64_t Tag;
2169   SMLoc TagLoc;
2170   TagLoc = Parser.getTok().getLoc();
2171   if (Parser.getTok().is(AsmToken::Identifier)) {
2172     StringRef Name = Parser.getTok().getIdentifier();
2173     Optional<unsigned> Ret =
2174         ELFAttrs::attrTypeFromString(Name, RISCVAttrs::getRISCVAttributeTags());
2175     if (!Ret.hasValue()) {
2176       Error(TagLoc, "attribute name not recognised: " + Name);
2177       return false;
2178     }
2179     Tag = Ret.getValue();
2180     Parser.Lex();
2181   } else {
2182     const MCExpr *AttrExpr;
2183 
2184     TagLoc = Parser.getTok().getLoc();
2185     if (Parser.parseExpression(AttrExpr))
2186       return true;
2187 
2188     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
2189     if (check(!CE, TagLoc, "expected numeric constant"))
2190       return true;
2191 
2192     Tag = CE->getValue();
2193   }
2194 
2195   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
2196     return true;
2197 
2198   StringRef StringValue;
2199   int64_t IntegerValue = 0;
2200   bool IsIntegerValue = true;
2201 
2202   // RISC-V attributes have a string value if the tag number is odd
2203   // and an integer value if the tag number is even.
2204   if (Tag % 2)
2205     IsIntegerValue = false;
2206 
2207   SMLoc ValueExprLoc = Parser.getTok().getLoc();
2208   if (IsIntegerValue) {
2209     const MCExpr *ValueExpr;
2210     if (Parser.parseExpression(ValueExpr))
2211       return true;
2212 
2213     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
2214     if (!CE)
2215       return Error(ValueExprLoc, "expected numeric constant");
2216     IntegerValue = CE->getValue();
2217   } else {
2218     if (Parser.getTok().isNot(AsmToken::String))
2219       return Error(Parser.getTok().getLoc(), "expected string constant");
2220 
2221     StringValue = Parser.getTok().getStringContents();
2222     Parser.Lex();
2223   }
2224 
2225   if (Parser.parseToken(AsmToken::EndOfStatement,
2226                         "unexpected token in '.attribute' directive"))
2227     return true;
2228 
2229   if (IsIntegerValue)
2230     getTargetStreamer().emitAttribute(Tag, IntegerValue);
2231   else if (Tag != RISCVAttrs::ARCH)
2232     getTargetStreamer().emitTextAttribute(Tag, StringValue);
2233   else {
2234     StringRef Arch = StringValue;
2235     for (auto Feature : RISCVFeatureKV)
2236       if (llvm::RISCVISAInfo::isSupportedExtensionFeature(Feature.Key))
2237         clearFeatureBits(Feature.Value, Feature.Key);
2238 
2239     auto ParseResult = llvm::RISCVISAInfo::parseArchString(
2240         StringValue, /*EnableExperimentalExtension=*/true,
2241         /*ExperimentalExtensionVersionCheck=*/true);
2242     if (!ParseResult) {
2243       std::string Buffer;
2244       raw_string_ostream OutputErrMsg(Buffer);
2245       handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2246         OutputErrMsg << "invalid arch name '" << Arch << "', "
2247                      << ErrMsg.getMessage();
2248       });
2249 
2250       return Error(ValueExprLoc, OutputErrMsg.str());
2251     }
2252     auto &ISAInfo = *ParseResult;
2253 
2254     for (auto Feature : RISCVFeatureKV)
2255       if (ISAInfo->hasExtension(Feature.Key))
2256         setFeatureBits(Feature.Value, Feature.Key);
2257 
2258     if (ISAInfo->getXLen() == 32)
2259       clearFeatureBits(RISCV::Feature64Bit, "64bit");
2260     else if (ISAInfo->getXLen() == 64)
2261       setFeatureBits(RISCV::Feature64Bit, "64bit");
2262     else
2263       return Error(ValueExprLoc, "bad arch string " + Arch);
2264 
2265     // Then emit the arch string.
2266     getTargetStreamer().emitTextAttribute(Tag, ISAInfo->toString());
2267   }
2268 
2269   return false;
2270 }
2271 
2272 /// parseDirectiveInsn
2273 /// ::= .insn [ format encoding, (operands (, operands)*) ]
2274 bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
2275   MCAsmParser &Parser = getParser();
2276 
2277   // Expect instruction format as identifier.
2278   StringRef Format;
2279   SMLoc ErrorLoc = Parser.getTok().getLoc();
2280   if (Parser.parseIdentifier(Format))
2281     return Error(ErrorLoc, "expected instruction format");
2282 
2283   if (Format != "r" && Format != "r4" && Format != "i" && Format != "b" &&
2284       Format != "sb" && Format != "u" && Format != "j" && Format != "uj" &&
2285       Format != "s")
2286     return Error(ErrorLoc, "invalid instruction format");
2287 
2288   std::string FormatName = (".insn_" + Format).str();
2289 
2290   ParseInstructionInfo Info;
2291   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> Operands;
2292 
2293   if (ParseInstruction(Info, FormatName, L, Operands))
2294     return true;
2295 
2296   unsigned Opcode;
2297   uint64_t ErrorInfo;
2298   return MatchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
2299                                  ErrorInfo,
2300                                  /*MatchingInlineAsm=*/false);
2301 }
2302 
2303 void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
2304   MCInst CInst;
2305   bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
2306   if (Res)
2307     ++RISCVNumInstrsCompressed;
2308   S.emitInstruction((Res ? CInst : Inst), getSTI());
2309 }
2310 
2311 void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
2312                                  MCStreamer &Out) {
2313   RISCVMatInt::InstSeq Seq =
2314       RISCVMatInt::generateInstSeq(Value, getSTI().getFeatureBits());
2315 
2316   MCRegister SrcReg = RISCV::X0;
2317   for (RISCVMatInt::Inst &Inst : Seq) {
2318     if (Inst.Opc == RISCV::LUI) {
2319       emitToStreamer(
2320           Out, MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Inst.Imm));
2321     } else if (Inst.Opc == RISCV::ADD_UW) {
2322       emitToStreamer(Out, MCInstBuilder(RISCV::ADD_UW)
2323                               .addReg(DestReg)
2324                               .addReg(SrcReg)
2325                               .addReg(RISCV::X0));
2326     } else if (Inst.Opc == RISCV::SH1ADD || Inst.Opc == RISCV::SH2ADD ||
2327                Inst.Opc == RISCV::SH3ADD) {
2328       emitToStreamer(
2329           Out, MCInstBuilder(Inst.Opc).addReg(DestReg).addReg(SrcReg).addReg(
2330                    SrcReg));
2331     } else {
2332       emitToStreamer(
2333           Out, MCInstBuilder(Inst.Opc).addReg(DestReg).addReg(SrcReg).addImm(
2334                    Inst.Imm));
2335     }
2336 
2337     // Only the first instruction has X0 as its source.
2338     SrcReg = DestReg;
2339   }
2340 }
2341 
2342 void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
2343                                        const MCExpr *Symbol,
2344                                        RISCVMCExpr::VariantKind VKHi,
2345                                        unsigned SecondOpcode, SMLoc IDLoc,
2346                                        MCStreamer &Out) {
2347   // A pair of instructions for PC-relative addressing; expands to
2348   //   TmpLabel: AUIPC TmpReg, VKHi(symbol)
2349   //             OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
2350   MCContext &Ctx = getContext();
2351 
2352   MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
2353   Out.emitLabel(TmpLabel);
2354 
2355   const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
2356   emitToStreamer(
2357       Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
2358 
2359   const MCExpr *RefToLinkTmpLabel =
2360       RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
2361                           RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
2362 
2363   emitToStreamer(Out, MCInstBuilder(SecondOpcode)
2364                           .addOperand(DestReg)
2365                           .addOperand(TmpReg)
2366                           .addExpr(RefToLinkTmpLabel));
2367 }
2368 
2369 void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
2370                                           MCStreamer &Out) {
2371   // The load local address pseudo-instruction "lla" is used in PC-relative
2372   // addressing of local symbols:
2373   //   lla rdest, symbol
2374   // expands to
2375   //   TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
2376   //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
2377   MCOperand DestReg = Inst.getOperand(0);
2378   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2379   emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
2380                     RISCV::ADDI, IDLoc, Out);
2381 }
2382 
2383 void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
2384                                      MCStreamer &Out) {
2385   // The load address pseudo-instruction "la" is used in PC-relative and
2386   // GOT-indirect addressing of global symbols:
2387   //   la rdest, symbol
2388   // expands to either (for non-PIC)
2389   //   TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
2390   //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
2391   // or (for PIC)
2392   //   TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
2393   //             Lx rdest, %pcrel_lo(TmpLabel)(rdest)
2394   MCOperand DestReg = Inst.getOperand(0);
2395   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2396   unsigned SecondOpcode;
2397   RISCVMCExpr::VariantKind VKHi;
2398   if (ParserOptions.IsPicEnabled) {
2399     SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
2400     VKHi = RISCVMCExpr::VK_RISCV_GOT_HI;
2401   } else {
2402     SecondOpcode = RISCV::ADDI;
2403     VKHi = RISCVMCExpr::VK_RISCV_PCREL_HI;
2404   }
2405   emitAuipcInstPair(DestReg, DestReg, Symbol, VKHi, SecondOpcode, IDLoc, Out);
2406 }
2407 
2408 void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
2409                                           MCStreamer &Out) {
2410   // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
2411   // initial-exec TLS model addressing of global symbols:
2412   //   la.tls.ie rdest, symbol
2413   // expands to
2414   //   TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
2415   //             Lx rdest, %pcrel_lo(TmpLabel)(rdest)
2416   MCOperand DestReg = Inst.getOperand(0);
2417   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2418   unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
2419   emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
2420                     SecondOpcode, IDLoc, Out);
2421 }
2422 
2423 void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
2424                                           MCStreamer &Out) {
2425   // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
2426   // global-dynamic TLS model addressing of global symbols:
2427   //   la.tls.gd rdest, symbol
2428   // expands to
2429   //   TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
2430   //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
2431   MCOperand DestReg = Inst.getOperand(0);
2432   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2433   emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
2434                     RISCV::ADDI, IDLoc, Out);
2435 }
2436 
2437 void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
2438                                          SMLoc IDLoc, MCStreamer &Out,
2439                                          bool HasTmpReg) {
2440   // The load/store pseudo-instruction does a pc-relative load with
2441   // a symbol.
2442   //
2443   // The expansion looks like this
2444   //
2445   //   TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
2446   //             [S|L]X    rd, %pcrel_lo(TmpLabel)(tmp)
2447   unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
2448   MCOperand DestReg = Inst.getOperand(DestRegOpIdx);
2449   unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
2450   MCOperand TmpReg = Inst.getOperand(0);
2451   const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
2452   emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
2453                     Opcode, IDLoc, Out);
2454 }
2455 
2456 void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
2457                                       int64_t Width, SMLoc IDLoc,
2458                                       MCStreamer &Out) {
2459   // The sign/zero extend pseudo-instruction does two shifts, with the shift
2460   // amounts dependent on the XLEN.
2461   //
2462   // The expansion looks like this
2463   //
2464   //    SLLI rd, rs, XLEN - Width
2465   //    SR[A|R]I rd, rd, XLEN - Width
2466   MCOperand DestReg = Inst.getOperand(0);
2467   MCOperand SourceReg = Inst.getOperand(1);
2468 
2469   unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
2470   int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
2471 
2472   assert(ShAmt > 0 && "Shift amount must be non-zero.");
2473 
2474   emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
2475                           .addOperand(DestReg)
2476                           .addOperand(SourceReg)
2477                           .addImm(ShAmt));
2478 
2479   emitToStreamer(Out, MCInstBuilder(SecondOpcode)
2480                           .addOperand(DestReg)
2481                           .addOperand(DestReg)
2482                           .addImm(ShAmt));
2483 }
2484 
2485 void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
2486                                MCStreamer &Out) {
2487   if (Inst.getNumOperands() == 3) {
2488     // unmasked va >= x
2489     //
2490     //  pseudoinstruction: vmsge{u}.vx vd, va, x
2491     //  expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
2492     emitToStreamer(Out, MCInstBuilder(Opcode)
2493                             .addOperand(Inst.getOperand(0))
2494                             .addOperand(Inst.getOperand(1))
2495                             .addOperand(Inst.getOperand(2))
2496                             .addReg(RISCV::NoRegister));
2497     emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
2498                             .addOperand(Inst.getOperand(0))
2499                             .addOperand(Inst.getOperand(0))
2500                             .addOperand(Inst.getOperand(0)));
2501   } else if (Inst.getNumOperands() == 4) {
2502     // masked va >= x, vd != v0
2503     //
2504     //  pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
2505     //  expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
2506     assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
2507            "The destination register should not be V0.");
2508     emitToStreamer(Out, MCInstBuilder(Opcode)
2509                             .addOperand(Inst.getOperand(0))
2510                             .addOperand(Inst.getOperand(1))
2511                             .addOperand(Inst.getOperand(2))
2512                             .addOperand(Inst.getOperand(3)));
2513     emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
2514                             .addOperand(Inst.getOperand(0))
2515                             .addOperand(Inst.getOperand(0))
2516                             .addReg(RISCV::V0));
2517   } else if (Inst.getNumOperands() == 5 &&
2518              Inst.getOperand(0).getReg() == RISCV::V0) {
2519     // masked va >= x, vd == v0
2520     //
2521     //  pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
2522     //  expansion: vmslt{u}.vx vt, va, x;  vmandn.mm vd, vd, vt
2523     assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
2524            "The destination register should be V0.");
2525     assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
2526            "The temporary vector register should not be V0.");
2527     emitToStreamer(Out, MCInstBuilder(Opcode)
2528                             .addOperand(Inst.getOperand(1))
2529                             .addOperand(Inst.getOperand(2))
2530                             .addOperand(Inst.getOperand(3))
2531                             .addOperand(Inst.getOperand(4)));
2532     emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
2533                             .addOperand(Inst.getOperand(0))
2534                             .addOperand(Inst.getOperand(0))
2535                             .addOperand(Inst.getOperand(1)));
2536   } else if (Inst.getNumOperands() == 5) {
2537     // masked va >= x, any vd
2538     //
2539     // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
2540     // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt; vmandn.mm vd,
2541     // vd, v0; vmor.mm vd, vt, vd
2542     assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
2543            "The temporary vector register should not be V0.");
2544     emitToStreamer(Out, MCInstBuilder(Opcode)
2545                             .addOperand(Inst.getOperand(1))
2546                             .addOperand(Inst.getOperand(2))
2547                             .addOperand(Inst.getOperand(3))
2548                             .addReg(RISCV::NoRegister));
2549     emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
2550                             .addOperand(Inst.getOperand(1))
2551                             .addReg(RISCV::V0)
2552                             .addOperand(Inst.getOperand(1)));
2553     emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
2554                             .addOperand(Inst.getOperand(0))
2555                             .addOperand(Inst.getOperand(0))
2556                             .addReg(RISCV::V0));
2557     emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
2558                             .addOperand(Inst.getOperand(0))
2559                             .addOperand(Inst.getOperand(1))
2560                             .addOperand(Inst.getOperand(0)));
2561   }
2562 }
2563 
2564 bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
2565                                          OperandVector &Operands) {
2566   assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
2567   assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
2568   if (Inst.getOperand(2).getReg() != RISCV::X4) {
2569     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
2570     return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
2571                            "%tprel_add modifier");
2572   }
2573 
2574   return false;
2575 }
2576 
2577 std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
2578   return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
2579                                  llvm::SMLoc(), isRV64());
2580 }
2581 
2582 bool RISCVAsmParser::validateInstruction(MCInst &Inst,
2583                                          OperandVector &Operands) {
2584   if (Inst.getOpcode() == RISCV::PseudoVMSGEU_VX_M_T ||
2585       Inst.getOpcode() == RISCV::PseudoVMSGE_VX_M_T) {
2586     unsigned DestReg = Inst.getOperand(0).getReg();
2587     unsigned TempReg = Inst.getOperand(1).getReg();
2588     if (DestReg == TempReg) {
2589       SMLoc Loc = Operands.back()->getStartLoc();
2590       return Error(Loc, "The temporary vector register cannot be the same as "
2591                         "the destination register.");
2592     }
2593   }
2594 
2595   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
2596   RISCVII::VConstraintType Constraints =
2597       RISCVII::getConstraint(MCID.TSFlags);
2598   if (Constraints == RISCVII::NoConstraint)
2599     return false;
2600 
2601   unsigned DestReg = Inst.getOperand(0).getReg();
2602   // Operands[1] will be the first operand, DestReg.
2603   SMLoc Loc = Operands[1]->getStartLoc();
2604   if (Constraints & RISCVII::VS2Constraint) {
2605     unsigned CheckReg = Inst.getOperand(1).getReg();
2606     if (DestReg == CheckReg)
2607       return Error(Loc, "The destination vector register group cannot overlap"
2608                         " the source vector register group.");
2609   }
2610   if ((Constraints & RISCVII::VS1Constraint) && (Inst.getOperand(2).isReg())) {
2611     unsigned CheckReg = Inst.getOperand(2).getReg();
2612     if (DestReg == CheckReg)
2613       return Error(Loc, "The destination vector register group cannot overlap"
2614                         " the source vector register group.");
2615   }
2616   if ((Constraints & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
2617     // vadc, vsbc are special cases. These instructions have no mask register.
2618     // The destination register could not be V0.
2619     unsigned Opcode = Inst.getOpcode();
2620     if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
2621         Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
2622         Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
2623         Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
2624         Opcode == RISCV::VMERGE_VXM)
2625       return Error(Loc, "The destination vector register group cannot be V0.");
2626 
2627     // Regardless masked or unmasked version, the number of operands is the
2628     // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
2629     // actually. We need to check the last operand to ensure whether it is
2630     // masked or not.
2631     unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
2632     assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
2633            "Unexpected register for mask operand");
2634 
2635     if (DestReg == CheckReg)
2636       return Error(Loc, "The destination vector register group cannot overlap"
2637                         " the mask register.");
2638   }
2639   return false;
2640 }
2641 
2642 bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
2643                                         OperandVector &Operands,
2644                                         MCStreamer &Out) {
2645   Inst.setLoc(IDLoc);
2646 
2647   switch (Inst.getOpcode()) {
2648   default:
2649     break;
2650   case RISCV::PseudoLI: {
2651     MCRegister Reg = Inst.getOperand(0).getReg();
2652     const MCOperand &Op1 = Inst.getOperand(1);
2653     if (Op1.isExpr()) {
2654       // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
2655       // Just convert to an addi. This allows compatibility with gas.
2656       emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
2657                               .addReg(Reg)
2658                               .addReg(RISCV::X0)
2659                               .addExpr(Op1.getExpr()));
2660       return false;
2661     }
2662     int64_t Imm = Inst.getOperand(1).getImm();
2663     // On RV32 the immediate here can either be a signed or an unsigned
2664     // 32-bit number. Sign extension has to be performed to ensure that Imm
2665     // represents the expected signed 64-bit number.
2666     if (!isRV64())
2667       Imm = SignExtend64<32>(Imm);
2668     emitLoadImm(Reg, Imm, Out);
2669     return false;
2670   }
2671   case RISCV::PseudoLLA:
2672     emitLoadLocalAddress(Inst, IDLoc, Out);
2673     return false;
2674   case RISCV::PseudoLA:
2675     emitLoadAddress(Inst, IDLoc, Out);
2676     return false;
2677   case RISCV::PseudoLA_TLS_IE:
2678     emitLoadTLSIEAddress(Inst, IDLoc, Out);
2679     return false;
2680   case RISCV::PseudoLA_TLS_GD:
2681     emitLoadTLSGDAddress(Inst, IDLoc, Out);
2682     return false;
2683   case RISCV::PseudoLB:
2684     emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
2685     return false;
2686   case RISCV::PseudoLBU:
2687     emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
2688     return false;
2689   case RISCV::PseudoLH:
2690     emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
2691     return false;
2692   case RISCV::PseudoLHU:
2693     emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
2694     return false;
2695   case RISCV::PseudoLW:
2696     emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
2697     return false;
2698   case RISCV::PseudoLWU:
2699     emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
2700     return false;
2701   case RISCV::PseudoLD:
2702     emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
2703     return false;
2704   case RISCV::PseudoFLH:
2705     emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
2706     return false;
2707   case RISCV::PseudoFLW:
2708     emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
2709     return false;
2710   case RISCV::PseudoFLD:
2711     emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
2712     return false;
2713   case RISCV::PseudoSB:
2714     emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
2715     return false;
2716   case RISCV::PseudoSH:
2717     emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
2718     return false;
2719   case RISCV::PseudoSW:
2720     emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
2721     return false;
2722   case RISCV::PseudoSD:
2723     emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
2724     return false;
2725   case RISCV::PseudoFSH:
2726     emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
2727     return false;
2728   case RISCV::PseudoFSW:
2729     emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
2730     return false;
2731   case RISCV::PseudoFSD:
2732     emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
2733     return false;
2734   case RISCV::PseudoAddTPRel:
2735     if (checkPseudoAddTPRel(Inst, Operands))
2736       return true;
2737     break;
2738   case RISCV::PseudoSEXT_B:
2739     emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
2740     return false;
2741   case RISCV::PseudoSEXT_H:
2742     emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
2743     return false;
2744   case RISCV::PseudoZEXT_H:
2745     emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
2746     return false;
2747   case RISCV::PseudoZEXT_W:
2748     emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
2749     return false;
2750   case RISCV::PseudoVMSGEU_VX:
2751   case RISCV::PseudoVMSGEU_VX_M:
2752   case RISCV::PseudoVMSGEU_VX_M_T:
2753     emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
2754     return false;
2755   case RISCV::PseudoVMSGE_VX:
2756   case RISCV::PseudoVMSGE_VX_M:
2757   case RISCV::PseudoVMSGE_VX_M_T:
2758     emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
2759     return false;
2760   case RISCV::PseudoVMSGE_VI:
2761   case RISCV::PseudoVMSLT_VI: {
2762     // These instructions are signed and so is immediate so we can subtract one
2763     // and change the opcode.
2764     int64_t Imm = Inst.getOperand(2).getImm();
2765     unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
2766                                                              : RISCV::VMSLE_VI;
2767     emitToStreamer(Out, MCInstBuilder(Opc)
2768                             .addOperand(Inst.getOperand(0))
2769                             .addOperand(Inst.getOperand(1))
2770                             .addImm(Imm - 1)
2771                             .addOperand(Inst.getOperand(3)));
2772     return false;
2773   }
2774   case RISCV::PseudoVMSGEU_VI:
2775   case RISCV::PseudoVMSLTU_VI: {
2776     int64_t Imm = Inst.getOperand(2).getImm();
2777     // Unsigned comparisons are tricky because the immediate is signed. If the
2778     // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
2779     // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
2780     // vmsne v0, v1, v1 which is always false.
2781     if (Imm == 0) {
2782       unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
2783                          ? RISCV::VMSEQ_VV
2784                          : RISCV::VMSNE_VV;
2785       emitToStreamer(Out, MCInstBuilder(Opc)
2786                               .addOperand(Inst.getOperand(0))
2787                               .addOperand(Inst.getOperand(1))
2788                               .addOperand(Inst.getOperand(1))
2789                               .addOperand(Inst.getOperand(3)));
2790     } else {
2791       // Other immediate values can subtract one like signed.
2792       unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
2793                          ? RISCV::VMSGTU_VI
2794                          : RISCV::VMSLEU_VI;
2795       emitToStreamer(Out, MCInstBuilder(Opc)
2796                               .addOperand(Inst.getOperand(0))
2797                               .addOperand(Inst.getOperand(1))
2798                               .addImm(Imm - 1)
2799                               .addOperand(Inst.getOperand(3)));
2800     }
2801 
2802     return false;
2803   }
2804   }
2805 
2806   emitToStreamer(Out, Inst);
2807   return false;
2808 }
2809 
2810 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmParser() {
2811   RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
2812   RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
2813 }
2814