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