1//===-- RISCVAsmParser.cpp - Parse RISC-V 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/RISCVMCAsmInfo.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/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/MC/MCAssembler.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCExpr.h"
25#include "llvm/MC/MCInst.h"
26#include "llvm/MC/MCInstBuilder.h"
27#include "llvm/MC/MCInstrInfo.h"
28#include "llvm/MC/MCObjectFileInfo.h"
29#include "llvm/MC/MCParser/AsmLexer.h"
30#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31#include "llvm/MC/MCParser/MCTargetAsmParser.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSubtargetInfo.h"
35#include "llvm/MC/MCValue.h"
36#include "llvm/MC/TargetRegistry.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Compiler.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/RISCVAttributes.h"
42#include "llvm/TargetParser/RISCVISAInfo.h"
43
44#include <limits>
45#include <optional>
46
47using namespace llvm;
48
49#define DEBUG_TYPE "riscv-asm-parser"
50
51STATISTIC(RISCVNumInstrsCompressed,
52 "Number of RISC-V Compressed instructions emitted");
53
54static cl::opt<bool> AddBuildAttributes("riscv-add-build-attributes",
55 cl::init(Val: false));
56
57namespace llvm {
58extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
59} // namespace llvm
60
61namespace {
62struct RISCVOperand;
63
64struct ParserOptionsSet {
65 bool IsPicEnabled;
66};
67
68class RISCVAsmParser : public MCTargetAsmParser {
69 // This tracks the parsing of the 4 optional operands that make up the vtype
70 // portion of vset(i)vli instructions which are separated by commas.
71 enum class VTypeState {
72 SeenNothingYet,
73 SeenSew,
74 SeenLmul,
75 SeenTailPolicy,
76 SeenMaskPolicy,
77 };
78
79 SmallVector<FeatureBitset, 4> FeatureBitStack;
80
81 SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
82 ParserOptionsSet ParserOptions;
83
84 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
85 bool isRV64() const { return getSTI().hasFeature(Feature: RISCV::Feature64Bit); }
86 bool isRVE() const { return getSTI().hasFeature(Feature: RISCV::FeatureStdExtE); }
87 bool enableExperimentalExtension() const {
88 return getSTI().hasFeature(Feature: RISCV::Experimental);
89 }
90
91 RISCVTargetStreamer &getTargetStreamer() {
92 assert(getParser().getStreamer().getTargetStreamer() &&
93 "do not have a target streamer");
94 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
95 return static_cast<RISCVTargetStreamer &>(TS);
96 }
97
98 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
99 unsigned Kind) override;
100
101 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
102 int64_t Lower, int64_t Upper,
103 const Twine &Msg);
104 bool generateImmOutOfRangeError(SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
105 const Twine &Msg);
106
107 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
108 OperandVector &Operands, MCStreamer &Out,
109 uint64_t &ErrorInfo,
110 bool MatchingInlineAsm) override;
111
112 MCRegister matchRegisterNameHelper(StringRef Name) const;
113 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
114 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
115 SMLoc &EndLoc) override;
116
117 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
118 SMLoc NameLoc, OperandVector &Operands) override;
119
120 ParseStatus parseDirective(AsmToken DirectiveID) override;
121
122 bool parseVTypeToken(const AsmToken &Tok, VTypeState &State, unsigned &Sew,
123 unsigned &Lmul, bool &Fractional, bool &TailAgnostic,
124 bool &MaskAgnostic);
125 bool generateVTypeError(SMLoc ErrorLoc);
126
127 bool generateXSfmmVTypeError(SMLoc ErrorLoc);
128 // Helper to actually emit an instruction to the MCStreamer. Also, when
129 // possible, compression of the instruction is performed.
130 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
131
132 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
133 // synthesize the desired immediate value into the destination register.
134 void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
135
136 // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
137 // helpers such as emitLoadLocalAddress and emitLoadAddress.
138 void emitAuipcInstPair(MCRegister DestReg, MCRegister TmpReg,
139 const MCExpr *Symbol, RISCV::Specifier VKHi,
140 unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
141
142 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
143 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
144
145 // Helper to emit pseudo instruction "lga" used in GOT-rel addressing.
146 void emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
147
148 // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
149 void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
150
151 // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
152 // addressing.
153 void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
154
155 // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
156 // addressing.
157 void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
158
159 // Helper to emit pseudo load/store instruction with a symbol.
160 void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
161 MCStreamer &Out, bool HasTmpReg);
162
163 // Helper to emit pseudo sign/zero extend instruction.
164 void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
165 SMLoc IDLoc, MCStreamer &Out);
166
167 // Helper to emit pseudo vmsge{u}.vx instruction.
168 void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
169
170 // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
171 // Enforcing this using a restricted register class for the second input
172 // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
173 // 'add' is an overloaded mnemonic.
174 bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
175
176 // Checks that a PseudoTLSDESCCall is using x5/t0 in its output operand.
177 // Enforcing this using a restricted register class for the output
178 // operand of PseudoTLSDESCCall results in a poor diagnostic due to the fact
179 // 'jalr' is an overloaded mnemonic.
180 bool checkPseudoTLSDESCCall(MCInst &Inst, OperandVector &Operands);
181
182 // Check instruction constraints.
183 bool validateInstruction(MCInst &Inst, OperandVector &Operands);
184
185 /// Helper for processing MC instructions that have been successfully matched
186 /// by matchAndEmitInstruction. Modifications to the emitted instructions,
187 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
188 /// in this method.
189 bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
190 MCStreamer &Out);
191
192// Auto-generated instruction matching functions
193#define GET_ASSEMBLER_HEADER
194#include "RISCVGenAsmMatcher.inc"
195
196 ParseStatus parseCSRSystemRegister(OperandVector &Operands);
197 ParseStatus parseFPImm(OperandVector &Operands);
198 ParseStatus parseImmediate(OperandVector &Operands);
199 ParseStatus parseRegister(OperandVector &Operands, bool AllowParens = false);
200 ParseStatus parseMemOpBaseReg(OperandVector &Operands);
201 ParseStatus parseZeroOffsetMemOp(OperandVector &Operands);
202 ParseStatus parseOperandWithSpecifier(OperandVector &Operands);
203 ParseStatus parseBareSymbol(OperandVector &Operands);
204 ParseStatus parseCallSymbol(OperandVector &Operands);
205 ParseStatus parsePseudoJumpSymbol(OperandVector &Operands);
206 ParseStatus parseJALOffset(OperandVector &Operands);
207 ParseStatus parseVTypeI(OperandVector &Operands);
208 ParseStatus parseMaskReg(OperandVector &Operands);
209 ParseStatus parseInsnDirectiveOpcode(OperandVector &Operands);
210 ParseStatus parseInsnCDirectiveOpcode(OperandVector &Operands);
211 ParseStatus parseGPRAsFPR(OperandVector &Operands);
212 ParseStatus parseGPRAsFPR64(OperandVector &Operands);
213 ParseStatus parseGPRPairAsFPR64(OperandVector &Operands);
214 template <bool IsRV64Inst> ParseStatus parseGPRPair(OperandVector &Operands);
215 ParseStatus parseGPRPair(OperandVector &Operands, bool IsRV64Inst);
216 ParseStatus parseFRMArg(OperandVector &Operands);
217 ParseStatus parseFenceArg(OperandVector &Operands);
218 ParseStatus parseRegList(OperandVector &Operands, bool MustIncludeS0 = false);
219 ParseStatus parseRegListS0(OperandVector &Operands) {
220 return parseRegList(Operands, /*MustIncludeS0=*/true);
221 }
222
223 ParseStatus parseRegReg(OperandVector &Operands);
224 ParseStatus parseXSfmmVType(OperandVector &Operands);
225 ParseStatus parseRetval(OperandVector &Operands);
226 ParseStatus parseZcmpStackAdj(OperandVector &Operands,
227 bool ExpectNegative = false);
228 ParseStatus parseZcmpNegStackAdj(OperandVector &Operands) {
229 return parseZcmpStackAdj(Operands, /*ExpectNegative*/ true);
230 }
231
232 bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
233 bool parseExprWithSpecifier(const MCExpr *&Res, SMLoc &E);
234 bool parseDataExpr(const MCExpr *&Res) override;
235
236 bool parseDirectiveOption();
237 bool parseDirectiveAttribute();
238 bool parseDirectiveInsn(SMLoc L);
239 bool parseDirectiveVariantCC();
240
241 /// Helper to reset target features for a new arch string. It
242 /// also records the new arch string that is expanded by RISCVISAInfo
243 /// and reports error for invalid arch string.
244 bool resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
245 bool FromOptionDirective);
246
247 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
248 if (!(getSTI().hasFeature(Feature))) {
249 MCSubtargetInfo &STI = copySTI();
250 setAvailableFeatures(
251 ComputeAvailableFeatures(FB: STI.ToggleFeature(FS: FeatureString)));
252 }
253 }
254
255 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
256 if (getSTI().hasFeature(Feature)) {
257 MCSubtargetInfo &STI = copySTI();
258 setAvailableFeatures(
259 ComputeAvailableFeatures(FB: STI.ToggleFeature(FS: FeatureString)));
260 }
261 }
262
263 void pushFeatureBits() {
264 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
265 "These two stacks must be kept synchronized");
266 FeatureBitStack.push_back(Elt: getSTI().getFeatureBits());
267 ParserOptionsStack.push_back(Elt: ParserOptions);
268 }
269
270 bool popFeatureBits() {
271 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
272 "These two stacks must be kept synchronized");
273 if (FeatureBitStack.empty())
274 return true;
275
276 FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
277 copySTI().setFeatureBits(FeatureBits);
278 setAvailableFeatures(ComputeAvailableFeatures(FB: FeatureBits));
279
280 ParserOptions = ParserOptionsStack.pop_back_val();
281
282 return false;
283 }
284
285 std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
286 std::unique_ptr<RISCVOperand> defaultFRMArgOp() const;
287 std::unique_ptr<RISCVOperand> defaultFRMArgLegacyOp() const;
288
289public:
290 enum RISCVMatchResultTy : unsigned {
291 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
292#define GET_OPERAND_DIAGNOSTIC_TYPES
293#include "RISCVGenAsmMatcher.inc"
294#undef GET_OPERAND_DIAGNOSTIC_TYPES
295 };
296
297 static bool classifySymbolRef(const MCExpr *Expr, RISCV::Specifier &Kind);
298 static bool isSymbolDiff(const MCExpr *Expr);
299
300 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
301 const MCInstrInfo &MII, const MCTargetOptions &Options)
302 : MCTargetAsmParser(Options, STI, MII) {
303 MCAsmParserExtension::Initialize(Parser);
304
305 Parser.addAliasForDirective(Directive: ".half", Alias: ".2byte");
306 Parser.addAliasForDirective(Directive: ".hword", Alias: ".2byte");
307 Parser.addAliasForDirective(Directive: ".word", Alias: ".4byte");
308 Parser.addAliasForDirective(Directive: ".dword", Alias: ".8byte");
309 setAvailableFeatures(ComputeAvailableFeatures(FB: STI.getFeatureBits()));
310
311 auto ABIName = StringRef(Options.ABIName);
312 if (ABIName.ends_with(Suffix: "f") && !getSTI().hasFeature(Feature: RISCV::FeatureStdExtF)) {
313 errs() << "Hard-float 'f' ABI can't be used for a target that "
314 "doesn't support the F instruction set extension (ignoring "
315 "target-abi)\n";
316 } else if (ABIName.ends_with(Suffix: "d") &&
317 !getSTI().hasFeature(Feature: RISCV::FeatureStdExtD)) {
318 errs() << "Hard-float 'd' ABI can't be used for a target that "
319 "doesn't support the D instruction set extension (ignoring "
320 "target-abi)\n";
321 }
322
323 // Use computeTargetABI to check if ABIName is valid. If invalid, output
324 // error message.
325 RISCVABI::computeTargetABI(TT: STI.getTargetTriple(), FeatureBits: STI.getFeatureBits(),
326 ABIName);
327
328 const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
329 ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
330
331 if (AddBuildAttributes)
332 getTargetStreamer().emitTargetAttributes(STI, /*EmitStackAlign*/ false);
333 }
334};
335
336/// RISCVOperand - Instances of this class represent a parsed machine
337/// instruction
338struct RISCVOperand final : public MCParsedAsmOperand {
339
340 enum class KindTy {
341 Token,
342 Register,
343 Immediate,
344 FPImmediate,
345 SystemRegister,
346 VType,
347 FRM,
348 Fence,
349 RegList,
350 StackAdj,
351 RegReg,
352 } Kind;
353
354 struct RegOp {
355 MCRegister RegNum;
356 bool IsGPRAsFPR;
357 };
358
359 struct ImmOp {
360 const MCExpr *Val;
361 bool IsRV64;
362 };
363
364 struct FPImmOp {
365 uint64_t Val;
366 };
367
368 struct SysRegOp {
369 const char *Data;
370 unsigned Length;
371 unsigned Encoding;
372 // FIXME: Add the Encoding parsed fields as needed for checks,
373 // e.g.: read/write or user/supervisor/machine privileges.
374 };
375
376 struct VTypeOp {
377 unsigned Val;
378 };
379
380 struct FRMOp {
381 RISCVFPRndMode::RoundingMode FRM;
382 };
383
384 struct FenceOp {
385 unsigned Val;
386 };
387
388 struct RegListOp {
389 unsigned Encoding;
390 };
391
392 struct StackAdjOp {
393 unsigned Val;
394 };
395
396 struct RegRegOp {
397 MCRegister BaseReg;
398 MCRegister OffsetReg;
399 };
400
401 SMLoc StartLoc, EndLoc;
402 union {
403 StringRef Tok;
404 RegOp Reg;
405 ImmOp Imm;
406 FPImmOp FPImm;
407 SysRegOp SysReg;
408 VTypeOp VType;
409 FRMOp FRM;
410 FenceOp Fence;
411 RegListOp RegList;
412 StackAdjOp StackAdj;
413 RegRegOp RegReg;
414 };
415
416 RISCVOperand(KindTy K) : Kind(K) {}
417
418public:
419 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
420 Kind = o.Kind;
421 StartLoc = o.StartLoc;
422 EndLoc = o.EndLoc;
423 switch (Kind) {
424 case KindTy::Register:
425 Reg = o.Reg;
426 break;
427 case KindTy::Immediate:
428 Imm = o.Imm;
429 break;
430 case KindTy::FPImmediate:
431 FPImm = o.FPImm;
432 break;
433 case KindTy::Token:
434 Tok = o.Tok;
435 break;
436 case KindTy::SystemRegister:
437 SysReg = o.SysReg;
438 break;
439 case KindTy::VType:
440 VType = o.VType;
441 break;
442 case KindTy::FRM:
443 FRM = o.FRM;
444 break;
445 case KindTy::Fence:
446 Fence = o.Fence;
447 break;
448 case KindTy::RegList:
449 RegList = o.RegList;
450 break;
451 case KindTy::StackAdj:
452 StackAdj = o.StackAdj;
453 break;
454 case KindTy::RegReg:
455 RegReg = o.RegReg;
456 break;
457 }
458 }
459
460 bool isToken() const override { return Kind == KindTy::Token; }
461 bool isReg() const override { return Kind == KindTy::Register; }
462 bool isV0Reg() const {
463 return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
464 }
465 bool isAnyReg() const {
466 return Kind == KindTy::Register &&
467 (RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg: Reg.RegNum) ||
468 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg: Reg.RegNum) ||
469 RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg: Reg.RegNum));
470 }
471 bool isAnyRegC() const {
472 return Kind == KindTy::Register &&
473 (RISCVMCRegisterClasses[RISCV::GPRCRegClassID].contains(
474 Reg: Reg.RegNum) ||
475 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(
476 Reg: Reg.RegNum));
477 }
478 bool isImm() const override { return Kind == KindTy::Immediate; }
479 bool isMem() const override { return false; }
480 bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
481 bool isRegReg() const { return Kind == KindTy::RegReg; }
482 bool isRegList() const { return Kind == KindTy::RegList; }
483 bool isRegListS0() const {
484 return Kind == KindTy::RegList && RegList.Encoding != RISCVZC::RA;
485 }
486 bool isStackAdj() const { return Kind == KindTy::StackAdj; }
487
488 bool isGPR() const {
489 return Kind == KindTy::Register &&
490 RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg: Reg.RegNum);
491 }
492
493 bool isGPRPair() const {
494 return Kind == KindTy::Register &&
495 RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(
496 Reg: Reg.RegNum);
497 }
498
499 bool isGPRPairC() const {
500 return Kind == KindTy::Register &&
501 RISCVMCRegisterClasses[RISCV::GPRPairCRegClassID].contains(
502 Reg: Reg.RegNum);
503 }
504
505 bool isGPRPairNoX0() const {
506 return Kind == KindTy::Register &&
507 RISCVMCRegisterClasses[RISCV::GPRPairNoX0RegClassID].contains(
508 Reg: Reg.RegNum);
509 }
510
511 bool isGPRF16() const {
512 return Kind == KindTy::Register &&
513 RISCVMCRegisterClasses[RISCV::GPRF16RegClassID].contains(Reg: Reg.RegNum);
514 }
515
516 bool isGPRF32() const {
517 return Kind == KindTy::Register &&
518 RISCVMCRegisterClasses[RISCV::GPRF32RegClassID].contains(Reg: Reg.RegNum);
519 }
520
521 bool isGPRAsFPR() const { return isGPR() && Reg.IsGPRAsFPR; }
522 bool isGPRAsFPR16() const { return isGPRF16() && Reg.IsGPRAsFPR; }
523 bool isGPRAsFPR32() const { return isGPRF32() && Reg.IsGPRAsFPR; }
524 bool isGPRPairAsFPR64() const { return isGPRPair() && Reg.IsGPRAsFPR; }
525
526 static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm) {
527 if (auto CE = dyn_cast<MCConstantExpr>(Val: Expr)) {
528 Imm = CE->getValue();
529 return true;
530 }
531
532 return false;
533 }
534
535 // True if operand is a symbol with no modifiers, or a constant with no
536 // modifiers and isShiftedInt<N-1, 1>(Op).
537 template <int N> bool isBareSimmNLsb0() const {
538 if (!isImm())
539 return false;
540
541 int64_t Imm;
542 if (evaluateConstantImm(Expr: getImm(), Imm))
543 return isShiftedInt<N - 1, 1>(fixImmediateForRV32(Imm, IsRV64Imm: isRV64Imm()));
544
545 RISCV::Specifier VK = RISCV::S_None;
546 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
547 VK == RISCV::S_None;
548 }
549
550 // True if operand is a symbol with no modifiers, or a constant with no
551 // modifiers and isInt<N>(Op).
552 template <int N> bool isBareSimmN() const {
553 if (!isImm())
554 return false;
555
556 int64_t Imm;
557 if (evaluateConstantImm(Expr: getImm(), Imm))
558 return isInt<N>(fixImmediateForRV32(Imm, IsRV64Imm: isRV64Imm()));
559
560 RISCV::Specifier VK = RISCV::S_None;
561 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
562 VK == RISCV::S_None;
563 }
564
565 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
566
567 bool isBareSymbol() const {
568 int64_t Imm;
569 // Must be of 'immediate' type but not a constant.
570 if (!isImm() || evaluateConstantImm(Expr: getImm(), Imm))
571 return false;
572
573 RISCV::Specifier VK = RISCV::S_None;
574 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
575 VK == RISCV::S_None;
576 }
577
578 bool isCallSymbol() const {
579 int64_t Imm;
580 // Must be of 'immediate' type but not a constant.
581 if (!isImm() || evaluateConstantImm(Expr: getImm(), Imm))
582 return false;
583
584 RISCV::Specifier VK = RISCV::S_None;
585 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
586 VK == ELF::R_RISCV_CALL_PLT;
587 }
588
589 bool isPseudoJumpSymbol() const {
590 int64_t Imm;
591 // Must be of 'immediate' type but not a constant.
592 if (!isImm() || evaluateConstantImm(Expr: getImm(), Imm))
593 return false;
594
595 RISCV::Specifier VK = RISCV::S_None;
596 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
597 VK == ELF::R_RISCV_CALL_PLT;
598 }
599
600 bool isTPRelAddSymbol() const {
601 int64_t Imm;
602 // Must be of 'immediate' type but not a constant.
603 if (!isImm() || evaluateConstantImm(Expr: getImm(), Imm))
604 return false;
605
606 RISCV::Specifier VK = RISCV::S_None;
607 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
608 VK == ELF::R_RISCV_TPREL_ADD;
609 }
610
611 bool isTLSDESCCallSymbol() const {
612 int64_t Imm;
613 // Must be of 'immediate' type but not a constant.
614 if (!isImm() || evaluateConstantImm(Expr: getImm(), Imm))
615 return false;
616
617 RISCV::Specifier VK = RISCV::S_None;
618 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
619 VK == ELF::R_RISCV_TLSDESC_CALL;
620 }
621
622 bool isCSRSystemRegister() const { return isSystemRegister(); }
623
624 // If the last operand of the vsetvli/vsetvli instruction is a constant
625 // expression, KindTy is Immediate.
626 bool isVTypeI10() const {
627 if (Kind == KindTy::VType)
628 return true;
629 return isUImm<10>();
630 }
631 bool isVTypeI11() const {
632 if (Kind == KindTy::VType)
633 return true;
634 return isUImm<11>();
635 }
636
637 bool isXSfmmVType() const {
638 return Kind == KindTy::VType && RISCVVType::isValidXSfmmVType(VTypeI: VType.Val);
639 }
640
641 /// Return true if the operand is a valid for the fence instruction e.g.
642 /// ('iorw').
643 bool isFenceArg() const { return Kind == KindTy::Fence; }
644
645 /// Return true if the operand is a valid floating point rounding mode.
646 bool isFRMArg() const { return Kind == KindTy::FRM; }
647 bool isFRMArgLegacy() const { return Kind == KindTy::FRM; }
648 bool isRTZArg() const { return isFRMArg() && FRM.FRM == RISCVFPRndMode::RTZ; }
649
650 /// Return true if the operand is a valid fli.s floating-point immediate.
651 bool isLoadFPImm() const {
652 if (isImm())
653 return isUImm5();
654 if (Kind != KindTy::FPImmediate)
655 return false;
656 int Idx = RISCVLoadFPImm::getLoadFPImm(
657 FPImm: APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
658 // Don't allow decimal version of the minimum value. It is a different value
659 // for each supported data type.
660 return Idx >= 0 && Idx != 1;
661 }
662
663 bool isImmXLenLI() const {
664 int64_t Imm;
665 if (!isImm())
666 return false;
667 // Given only Imm, ensuring that the actually specified constant is either
668 // a signed or unsigned 64-bit number is unfortunately impossible.
669 if (evaluateConstantImm(Expr: getImm(), Imm))
670 return isRV64Imm() || (isInt<32>(x: Imm) || isUInt<32>(x: Imm));
671
672 return RISCVAsmParser::isSymbolDiff(Expr: getImm());
673 }
674
675 bool isImmXLenLI_Restricted() const {
676 int64_t Imm;
677 if (!isImm())
678 return false;
679 bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
680 // 'la imm' supports constant immediates only.
681 return IsConstantImm &&
682 (isRV64Imm() || (isInt<32>(x: Imm) || isUInt<32>(x: Imm)));
683 }
684
685 template <unsigned N> bool isUImm() const {
686 int64_t Imm;
687 if (!isImm())
688 return false;
689 bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
690 return IsConstantImm && isUInt<N>(Imm);
691 }
692
693 template <unsigned N, unsigned S> bool isUImmShifted() const {
694 int64_t Imm;
695 if (!isImm())
696 return false;
697 bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
698 return IsConstantImm && isShiftedUInt<N, S>(Imm);
699 }
700
701 template <class Pred> bool isUImmPred(Pred p) const {
702 int64_t Imm;
703 if (!isImm())
704 return false;
705 bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
706 return IsConstantImm && p(Imm);
707 }
708
709 bool isUImmLog2XLen() const {
710 if (isImm() && isRV64Imm())
711 return isUImm<6>();
712 return isUImm<5>();
713 }
714
715 bool isUImmLog2XLenNonZero() const {
716 if (isImm() && isRV64Imm())
717 return isUImmPred(p: [](int64_t Imm) { return Imm != 0 && isUInt<6>(x: Imm); });
718 return isUImmPred(p: [](int64_t Imm) { return Imm != 0 && isUInt<5>(x: Imm); });
719 }
720
721 bool isUImmLog2XLenHalf() const {
722 if (isImm() && isRV64Imm())
723 return isUImm<5>();
724 return isUImm<4>();
725 }
726
727 bool isUImm1() const { return isUImm<1>(); }
728 bool isUImm2() const { return isUImm<2>(); }
729 bool isUImm3() const { return isUImm<3>(); }
730 bool isUImm4() const { return isUImm<4>(); }
731 bool isUImm5() const { return isUImm<5>(); }
732 bool isUImm6() const { return isUImm<6>(); }
733 bool isUImm7() const { return isUImm<7>(); }
734 bool isUImm8() const { return isUImm<8>(); }
735 bool isUImm9() const { return isUImm<9>(); }
736 bool isUImm10() const { return isUImm<10>(); }
737 bool isUImm11() const { return isUImm<11>(); }
738 bool isUImm16() const { return isUImm<16>(); }
739 bool isUImm20() const { return isUImm<20>(); }
740 bool isUImm32() const { return isUImm<32>(); }
741 bool isUImm48() const { return isUImm<48>(); }
742 bool isUImm64() const { return isUImm<64>(); }
743
744 bool isUImm5NonZero() const {
745 return isUImmPred(p: [](int64_t Imm) { return Imm != 0 && isUInt<5>(x: Imm); });
746 }
747
748 bool isUImm5GT3() const {
749 return isUImmPred(p: [](int64_t Imm) { return isUInt<5>(x: Imm) && Imm > 3; });
750 }
751
752 bool isUImm5Plus1() const {
753 return isUImmPred(
754 p: [](int64_t Imm) { return Imm > 0 && isUInt<5>(x: Imm - 1); });
755 }
756
757 bool isUImm5GE6Plus1() const {
758 return isUImmPred(
759 p: [](int64_t Imm) { return Imm >= 6 && isUInt<5>(x: Imm - 1); });
760 }
761
762 bool isUImm5Slist() const {
763 return isUImmPred(p: [](int64_t Imm) {
764 return (Imm == 0) || (Imm == 1) || (Imm == 2) || (Imm == 4) ||
765 (Imm == 8) || (Imm == 16) || (Imm == 15) || (Imm == 31);
766 });
767 }
768
769 bool isUImm8GE32() const {
770 return isUImmPred(p: [](int64_t Imm) { return isUInt<8>(x: Imm) && Imm >= 32; });
771 }
772
773 bool isRnumArg() const {
774 return isUImmPred(
775 p: [](int64_t Imm) { return Imm >= INT64_C(0) && Imm <= INT64_C(10); });
776 }
777
778 bool isRnumArg_0_7() const {
779 return isUImmPred(
780 p: [](int64_t Imm) { return Imm >= INT64_C(0) && Imm <= INT64_C(7); });
781 }
782
783 bool isRnumArg_1_10() const {
784 return isUImmPred(
785 p: [](int64_t Imm) { return Imm >= INT64_C(1) && Imm <= INT64_C(10); });
786 }
787
788 bool isRnumArg_2_14() const {
789 return isUImmPred(
790 p: [](int64_t Imm) { return Imm >= INT64_C(2) && Imm <= INT64_C(14); });
791 }
792
793 template <unsigned N> bool isSImm() const {
794 int64_t Imm;
795 if (!isImm())
796 return false;
797 bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
798 return IsConstantImm && isInt<N>(fixImmediateForRV32(Imm, IsRV64Imm: isRV64Imm()));
799 }
800
801 template <class Pred> bool isSImmPred(Pred p) const {
802 int64_t Imm;
803 if (!isImm())
804 return false;
805 bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
806 return IsConstantImm && p(fixImmediateForRV32(Imm, IsRV64Imm: isRV64Imm()));
807 }
808
809 bool isSImm5() const { return isSImm<5>(); }
810 bool isSImm6() const { return isSImm<6>(); }
811 bool isSImm10() const { return isSImm<10>(); }
812 bool isSImm11() const { return isSImm<11>(); }
813 bool isSImm16() const { return isSImm<16>(); }
814 bool isSImm26() const { return isSImm<26>(); }
815
816 bool isSImm5NonZero() const {
817 return isSImmPred(p: [](int64_t Imm) { return Imm != 0 && isInt<5>(x: Imm); });
818 }
819
820 bool isSImm6NonZero() const {
821 return isSImmPred(p: [](int64_t Imm) { return Imm != 0 && isInt<6>(x: Imm); });
822 }
823
824 bool isCLUIImm() const {
825 return isUImmPred(p: [](int64_t Imm) {
826 return (isUInt<5>(x: Imm) && Imm != 0) || (Imm >= 0xfffe0 && Imm <= 0xfffff);
827 });
828 }
829
830 bool isUImm2Lsb0() const { return isUImmShifted<1, 1>(); }
831
832 bool isUImm5Lsb0() const { return isUImmShifted<4, 1>(); }
833
834 bool isUImm6Lsb0() const { return isUImmShifted<5, 1>(); }
835
836 bool isUImm7Lsb00() const { return isUImmShifted<5, 2>(); }
837
838 bool isUImm7Lsb000() const { return isUImmShifted<4, 3>(); }
839
840 bool isUImm8Lsb00() const { return isUImmShifted<6, 2>(); }
841
842 bool isUImm8Lsb000() const { return isUImmShifted<5, 3>(); }
843
844 bool isUImm9Lsb000() const { return isUImmShifted<6, 3>(); }
845
846 bool isUImm14Lsb00() const { return isUImmShifted<12, 2>(); }
847
848 bool isUImm10Lsb00NonZero() const {
849 return isUImmPred(
850 p: [](int64_t Imm) { return isShiftedUInt<8, 2>(x: Imm) && (Imm != 0); });
851 }
852
853 // If this a RV32 and the immediate is a uimm32, sign extend it to 32 bits.
854 // This allows writing 'addi a0, a0, 0xffffffff'.
855 static int64_t fixImmediateForRV32(int64_t Imm, bool IsRV64Imm) {
856 if (IsRV64Imm || !isUInt<32>(x: Imm))
857 return Imm;
858 return SignExtend64<32>(x: Imm);
859 }
860
861 bool isSImm12() const {
862 if (!isImm())
863 return false;
864
865 int64_t Imm;
866 if (evaluateConstantImm(Expr: getImm(), Imm))
867 return isInt<12>(x: fixImmediateForRV32(Imm, IsRV64Imm: isRV64Imm()));
868
869 RISCV::Specifier VK = RISCV::S_None;
870 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
871 (VK == RISCV::S_LO || VK == RISCV::S_PCREL_LO ||
872 VK == RISCV::S_TPREL_LO || VK == ELF::R_RISCV_TLSDESC_LOAD_LO12 ||
873 VK == ELF::R_RISCV_TLSDESC_ADD_LO12);
874 }
875
876 bool isSImm12Lsb00000() const {
877 return isSImmPred(p: [](int64_t Imm) { return isShiftedInt<7, 5>(x: Imm); });
878 }
879
880 bool isSImm10Lsb0000NonZero() const {
881 return isSImmPred(
882 p: [](int64_t Imm) { return Imm != 0 && isShiftedInt<6, 4>(x: Imm); });
883 }
884
885 bool isSImm16NonZero() const {
886 return isSImmPred(p: [](int64_t Imm) { return Imm != 0 && isInt<16>(x: Imm); });
887 }
888
889 bool isUImm16NonZero() const {
890 return isUImmPred(p: [](int64_t Imm) { return isUInt<16>(x: Imm) && Imm != 0; });
891 }
892
893 bool isSImm20LI() const {
894 if (!isImm())
895 return false;
896
897 int64_t Imm;
898 if (evaluateConstantImm(Expr: getImm(), Imm))
899 return isInt<20>(x: fixImmediateForRV32(Imm, IsRV64Imm: isRV64Imm()));
900
901 RISCV::Specifier VK = RISCV::S_None;
902 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
903 VK == RISCV::S_QC_ABS20;
904 }
905
906 bool isSImm10Unsigned() const { return isSImm<10>() || isUImm<10>(); }
907
908 bool isUImm20LUI() const {
909 if (!isImm())
910 return false;
911
912 int64_t Imm;
913 if (evaluateConstantImm(Expr: getImm(), Imm))
914 return isUInt<20>(x: Imm);
915
916 RISCV::Specifier VK = RISCV::S_None;
917 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
918 (VK == ELF::R_RISCV_HI20 || VK == ELF::R_RISCV_TPREL_HI20);
919 }
920
921 bool isUImm20AUIPC() const {
922 if (!isImm())
923 return false;
924
925 int64_t Imm;
926 if (evaluateConstantImm(Expr: getImm(), Imm))
927 return isUInt<20>(x: Imm);
928
929 RISCV::Specifier VK = RISCV::S_None;
930 return RISCVAsmParser::classifySymbolRef(Expr: getImm(), Kind&: VK) &&
931 (VK == ELF::R_RISCV_PCREL_HI20 || VK == ELF::R_RISCV_GOT_HI20 ||
932 VK == ELF::R_RISCV_TLS_GOT_HI20 || VK == ELF::R_RISCV_TLS_GD_HI20 ||
933 VK == ELF::R_RISCV_TLSDESC_HI20);
934 }
935
936 bool isImmZero() const {
937 return isUImmPred(p: [](int64_t Imm) { return 0 == Imm; });
938 }
939
940 bool isImmThree() const {
941 return isUImmPred(p: [](int64_t Imm) { return 3 == Imm; });
942 }
943
944 bool isImmFour() const {
945 return isUImmPred(p: [](int64_t Imm) { return 4 == Imm; });
946 }
947
948 bool isSImm5Plus1() const {
949 return isSImmPred(
950 p: [](int64_t Imm) { return Imm != INT64_MIN && isInt<5>(x: Imm - 1); });
951 }
952
953 bool isSImm18() const {
954 return isSImmPred(p: [](int64_t Imm) { return isInt<18>(x: Imm); });
955 }
956
957 bool isSImm18Lsb0() const {
958 return isSImmPred(p: [](int64_t Imm) { return isShiftedInt<17, 1>(x: Imm); });
959 }
960
961 bool isSImm19Lsb00() const {
962 return isSImmPred(p: [](int64_t Imm) { return isShiftedInt<17, 2>(x: Imm); });
963 }
964
965 bool isSImm20Lsb000() const {
966 return isSImmPred(p: [](int64_t Imm) { return isShiftedInt<17, 3>(x: Imm); });
967 }
968
969 bool isSImm32Lsb0() const {
970 return isSImmPred(p: [](int64_t Imm) { return isShiftedInt<31, 1>(x: Imm); });
971 }
972
973 /// getStartLoc - Gets location of the first token of this operand
974 SMLoc getStartLoc() const override { return StartLoc; }
975 /// getEndLoc - Gets location of the last token of this operand
976 SMLoc getEndLoc() const override { return EndLoc; }
977 /// True if this operand is for an RV64 instruction
978 bool isRV64Imm() const {
979 assert(Kind == KindTy::Immediate && "Invalid type access!");
980 return Imm.IsRV64;
981 }
982
983 MCRegister getReg() const override {
984 assert(Kind == KindTy::Register && "Invalid type access!");
985 return Reg.RegNum;
986 }
987
988 StringRef getSysReg() const {
989 assert(Kind == KindTy::SystemRegister && "Invalid type access!");
990 return StringRef(SysReg.Data, SysReg.Length);
991 }
992
993 const MCExpr *getImm() const {
994 assert(Kind == KindTy::Immediate && "Invalid type access!");
995 return Imm.Val;
996 }
997
998 uint64_t getFPConst() const {
999 assert(Kind == KindTy::FPImmediate && "Invalid type access!");
1000 return FPImm.Val;
1001 }
1002
1003 StringRef getToken() const {
1004 assert(Kind == KindTy::Token && "Invalid type access!");
1005 return Tok;
1006 }
1007
1008 unsigned getVType() const {
1009 assert(Kind == KindTy::VType && "Invalid type access!");
1010 return VType.Val;
1011 }
1012
1013 RISCVFPRndMode::RoundingMode getFRM() const {
1014 assert(Kind == KindTy::FRM && "Invalid type access!");
1015 return FRM.FRM;
1016 }
1017
1018 unsigned getFence() const {
1019 assert(Kind == KindTy::Fence && "Invalid type access!");
1020 return Fence.Val;
1021 }
1022
1023 void print(raw_ostream &OS, const MCAsmInfo &MAI) const override {
1024 auto RegName = [](MCRegister Reg) {
1025 if (Reg)
1026 return RISCVInstPrinter::getRegisterName(Reg);
1027 else
1028 return "noreg";
1029 };
1030
1031 switch (Kind) {
1032 case KindTy::Immediate:
1033 OS << "<imm: ";
1034 MAI.printExpr(OS, *Imm.Val);
1035 OS << ' ' << (Imm.IsRV64 ? "rv64" : "rv32") << '>';
1036 break;
1037 case KindTy::FPImmediate:
1038 OS << "<fpimm: " << FPImm.Val << ">";
1039 break;
1040 case KindTy::Register:
1041 OS << "<reg: " << RegName(Reg.RegNum) << " (" << Reg.RegNum
1042 << (Reg.IsGPRAsFPR ? ") GPRasFPR>" : ")>");
1043 break;
1044 case KindTy::Token:
1045 OS << "'" << getToken() << "'";
1046 break;
1047 case KindTy::SystemRegister:
1048 OS << "<sysreg: " << getSysReg() << " (" << SysReg.Encoding << ")>";
1049 break;
1050 case KindTy::VType:
1051 OS << "<vtype: ";
1052 RISCVVType::printVType(VType: getVType(), OS);
1053 OS << '>';
1054 break;
1055 case KindTy::FRM:
1056 OS << "<frm: ";
1057 roundingModeToString(RndMode: getFRM());
1058 OS << '>';
1059 break;
1060 case KindTy::Fence:
1061 OS << "<fence: ";
1062 OS << getFence();
1063 OS << '>';
1064 break;
1065 case KindTy::RegList:
1066 OS << "<reglist: ";
1067 RISCVZC::printRegList(RlistEncode: RegList.Encoding, OS);
1068 OS << '>';
1069 break;
1070 case KindTy::StackAdj:
1071 OS << "<stackadj: ";
1072 OS << StackAdj.Val;
1073 OS << '>';
1074 break;
1075 case KindTy::RegReg:
1076 OS << "<RegReg: BaseReg " << RegName(RegReg.BaseReg) << " OffsetReg "
1077 << RegName(RegReg.OffsetReg);
1078 break;
1079 }
1080 }
1081
1082 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S) {
1083 auto Op = std::make_unique<RISCVOperand>(args: KindTy::Token);
1084 Op->Tok = Str;
1085 Op->StartLoc = S;
1086 Op->EndLoc = S;
1087 return Op;
1088 }
1089
1090 static std::unique_ptr<RISCVOperand>
1091 createReg(MCRegister Reg, SMLoc S, SMLoc E, bool IsGPRAsFPR = false) {
1092 auto Op = std::make_unique<RISCVOperand>(args: KindTy::Register);
1093 Op->Reg.RegNum = Reg;
1094 Op->Reg.IsGPRAsFPR = IsGPRAsFPR;
1095 Op->StartLoc = S;
1096 Op->EndLoc = E;
1097 return Op;
1098 }
1099
1100 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
1101 SMLoc E, bool IsRV64) {
1102 auto Op = std::make_unique<RISCVOperand>(args: KindTy::Immediate);
1103 Op->Imm.Val = Val;
1104 Op->Imm.IsRV64 = IsRV64;
1105 Op->StartLoc = S;
1106 Op->EndLoc = E;
1107 return Op;
1108 }
1109
1110 static std::unique_ptr<RISCVOperand> createFPImm(uint64_t Val, SMLoc S) {
1111 auto Op = std::make_unique<RISCVOperand>(args: KindTy::FPImmediate);
1112 Op->FPImm.Val = Val;
1113 Op->StartLoc = S;
1114 Op->EndLoc = S;
1115 return Op;
1116 }
1117
1118 static std::unique_ptr<RISCVOperand> createSysReg(StringRef Str, SMLoc S,
1119 unsigned Encoding) {
1120 auto Op = std::make_unique<RISCVOperand>(args: KindTy::SystemRegister);
1121 Op->SysReg.Data = Str.data();
1122 Op->SysReg.Length = Str.size();
1123 Op->SysReg.Encoding = Encoding;
1124 Op->StartLoc = S;
1125 Op->EndLoc = S;
1126 return Op;
1127 }
1128
1129 static std::unique_ptr<RISCVOperand>
1130 createFRMArg(RISCVFPRndMode::RoundingMode FRM, SMLoc S) {
1131 auto Op = std::make_unique<RISCVOperand>(args: KindTy::FRM);
1132 Op->FRM.FRM = FRM;
1133 Op->StartLoc = S;
1134 Op->EndLoc = S;
1135 return Op;
1136 }
1137
1138 static std::unique_ptr<RISCVOperand> createFenceArg(unsigned Val, SMLoc S) {
1139 auto Op = std::make_unique<RISCVOperand>(args: KindTy::Fence);
1140 Op->Fence.Val = Val;
1141 Op->StartLoc = S;
1142 Op->EndLoc = S;
1143 return Op;
1144 }
1145
1146 static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S) {
1147 auto Op = std::make_unique<RISCVOperand>(args: KindTy::VType);
1148 Op->VType.Val = VTypeI;
1149 Op->StartLoc = S;
1150 Op->EndLoc = S;
1151 return Op;
1152 }
1153
1154 static std::unique_ptr<RISCVOperand> createRegList(unsigned RlistEncode,
1155 SMLoc S) {
1156 auto Op = std::make_unique<RISCVOperand>(args: KindTy::RegList);
1157 Op->RegList.Encoding = RlistEncode;
1158 Op->StartLoc = S;
1159 return Op;
1160 }
1161
1162 static std::unique_ptr<RISCVOperand>
1163 createRegReg(MCRegister BaseReg, MCRegister OffsetReg, SMLoc S) {
1164 auto Op = std::make_unique<RISCVOperand>(args: KindTy::RegReg);
1165 Op->RegReg.BaseReg = BaseReg;
1166 Op->RegReg.OffsetReg = OffsetReg;
1167 Op->StartLoc = S;
1168 Op->EndLoc = S;
1169 return Op;
1170 }
1171
1172 static std::unique_ptr<RISCVOperand> createStackAdj(unsigned StackAdj, SMLoc S) {
1173 auto Op = std::make_unique<RISCVOperand>(args: KindTy::StackAdj);
1174 Op->StackAdj.Val = StackAdj;
1175 Op->StartLoc = S;
1176 return Op;
1177 }
1178
1179 static void addExpr(MCInst &Inst, const MCExpr *Expr, bool IsRV64Imm) {
1180 assert(Expr && "Expr shouldn't be null!");
1181 int64_t Imm = 0;
1182 bool IsConstant = evaluateConstantImm(Expr, Imm);
1183
1184 if (IsConstant)
1185 Inst.addOperand(
1186 Op: MCOperand::createImm(Val: fixImmediateForRV32(Imm, IsRV64Imm)));
1187 else
1188 Inst.addOperand(Op: MCOperand::createExpr(Val: Expr));
1189 }
1190
1191 // Used by the TableGen Code
1192 void addRegOperands(MCInst &Inst, unsigned N) const {
1193 assert(N == 1 && "Invalid number of operands!");
1194 Inst.addOperand(Op: MCOperand::createReg(Reg: getReg()));
1195 }
1196
1197 void addImmOperands(MCInst &Inst, unsigned N) const {
1198 assert(N == 1 && "Invalid number of operands!");
1199 addExpr(Inst, Expr: getImm(), IsRV64Imm: isRV64Imm());
1200 }
1201
1202 void addFPImmOperands(MCInst &Inst, unsigned N) const {
1203 assert(N == 1 && "Invalid number of operands!");
1204 if (isImm()) {
1205 addExpr(Inst, Expr: getImm(), IsRV64Imm: isRV64Imm());
1206 return;
1207 }
1208
1209 int Imm = RISCVLoadFPImm::getLoadFPImm(
1210 FPImm: APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
1211 Inst.addOperand(Op: MCOperand::createImm(Val: Imm));
1212 }
1213
1214 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
1215 assert(N == 1 && "Invalid number of operands!");
1216 Inst.addOperand(Op: MCOperand::createImm(Val: Fence.Val));
1217 }
1218
1219 void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1220 assert(N == 1 && "Invalid number of operands!");
1221 Inst.addOperand(Op: MCOperand::createImm(Val: SysReg.Encoding));
1222 }
1223
1224 // Support non-canonical syntax:
1225 // "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
1226 // "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
1227 void addVTypeIOperands(MCInst &Inst, unsigned N) const {
1228 assert(N == 1 && "Invalid number of operands!");
1229 int64_t Imm = 0;
1230 if (Kind == KindTy::Immediate) {
1231 [[maybe_unused]] bool IsConstantImm = evaluateConstantImm(Expr: getImm(), Imm);
1232 assert(IsConstantImm && "Invalid VTypeI Operand!");
1233 } else {
1234 Imm = getVType();
1235 }
1236 Inst.addOperand(Op: MCOperand::createImm(Val: Imm));
1237 }
1238
1239 void addRegListOperands(MCInst &Inst, unsigned N) const {
1240 assert(N == 1 && "Invalid number of operands!");
1241 Inst.addOperand(Op: MCOperand::createImm(Val: RegList.Encoding));
1242 }
1243
1244 void addRegRegOperands(MCInst &Inst, unsigned N) const {
1245 assert(N == 2 && "Invalid number of operands!");
1246 Inst.addOperand(Op: MCOperand::createReg(Reg: RegReg.BaseReg));
1247 Inst.addOperand(Op: MCOperand::createReg(Reg: RegReg.OffsetReg));
1248 }
1249
1250 void addStackAdjOperands(MCInst &Inst, unsigned N) const {
1251 assert(N == 1 && "Invalid number of operands!");
1252 Inst.addOperand(Op: MCOperand::createImm(Val: StackAdj.Val));
1253 }
1254
1255 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
1256 assert(N == 1 && "Invalid number of operands!");
1257 Inst.addOperand(Op: MCOperand::createImm(Val: getFRM()));
1258 }
1259};
1260} // end anonymous namespace.
1261
1262#define GET_REGISTER_MATCHER
1263#define GET_SUBTARGET_FEATURE_NAME
1264#define GET_MATCHER_IMPLEMENTATION
1265#define GET_MNEMONIC_SPELL_CHECKER
1266#include "RISCVGenAsmMatcher.inc"
1267
1268static MCRegister convertFPR64ToFPR16(MCRegister Reg) {
1269 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1270 return Reg - RISCV::F0_D + RISCV::F0_H;
1271}
1272
1273static MCRegister convertFPR64ToFPR32(MCRegister Reg) {
1274 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1275 return Reg - RISCV::F0_D + RISCV::F0_F;
1276}
1277
1278static MCRegister convertFPR64ToFPR128(MCRegister Reg) {
1279 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1280 return Reg - RISCV::F0_D + RISCV::F0_Q;
1281}
1282
1283static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg,
1284 unsigned Kind) {
1285 unsigned RegClassID;
1286 if (Kind == MCK_VRM2)
1287 RegClassID = RISCV::VRM2RegClassID;
1288 else if (Kind == MCK_VRM4)
1289 RegClassID = RISCV::VRM4RegClassID;
1290 else if (Kind == MCK_VRM8)
1291 RegClassID = RISCV::VRM8RegClassID;
1292 else
1293 return MCRegister();
1294 return RI.getMatchingSuperReg(Reg, SubIdx: RISCV::sub_vrm1_0,
1295 RC: &RISCVMCRegisterClasses[RegClassID]);
1296}
1297
1298unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1299 unsigned Kind) {
1300 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
1301 if (!Op.isReg())
1302 return Match_InvalidOperand;
1303
1304 MCRegister Reg = Op.getReg();
1305 bool IsRegFPR64 =
1306 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
1307 bool IsRegFPR64C =
1308 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
1309 bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
1310
1311 if (IsRegFPR64 && Kind == MCK_FPR128) {
1312 Op.Reg.RegNum = convertFPR64ToFPR128(Reg);
1313 return Match_Success;
1314 }
1315 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
1316 // register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
1317 if ((IsRegFPR64 && Kind == MCK_FPR32) ||
1318 (IsRegFPR64C && Kind == MCK_FPR32C)) {
1319 Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
1320 return Match_Success;
1321 }
1322 // As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
1323 // register from FPR64 to FPR16 if necessary.
1324 if (IsRegFPR64 && Kind == MCK_FPR16) {
1325 Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
1326 return Match_Success;
1327 }
1328 if (Kind == MCK_GPRAsFPR16 && Op.isGPRAsFPR()) {
1329 Op.Reg.RegNum = Reg - RISCV::X0 + RISCV::X0_H;
1330 return Match_Success;
1331 }
1332 if (Kind == MCK_GPRAsFPR32 && Op.isGPRAsFPR()) {
1333 Op.Reg.RegNum = Reg - RISCV::X0 + RISCV::X0_W;
1334 return Match_Success;
1335 }
1336
1337 // There are some GPRF64AsFPR instructions that have no RV32 equivalent. We
1338 // reject them at parsing thinking we should match as GPRPairAsFPR for RV32.
1339 // So we explicitly accept them here for RV32 to allow the generic code to
1340 // report that the instruction requires RV64.
1341 if (RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg) &&
1342 Kind == MCK_GPRF64AsFPR && STI->hasFeature(Feature: RISCV::FeatureStdExtZdinx) &&
1343 !isRV64())
1344 return Match_Success;
1345
1346 // As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
1347 // the register from VR to VRM2/VRM4/VRM8 if necessary.
1348 if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
1349 Op.Reg.RegNum = convertVRToVRMx(RI: *getContext().getRegisterInfo(), Reg, Kind);
1350 if (!Op.Reg.RegNum)
1351 return Match_InvalidOperand;
1352 return Match_Success;
1353 }
1354 return Match_InvalidOperand;
1355}
1356
1357bool RISCVAsmParser::generateImmOutOfRangeError(
1358 SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
1359 const Twine &Msg = "immediate must be an integer in the range") {
1360 return Error(L: ErrorLoc, Msg: Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
1361}
1362
1363bool RISCVAsmParser::generateImmOutOfRangeError(
1364 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
1365 const Twine &Msg = "immediate must be an integer in the range") {
1366 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1367 return generateImmOutOfRangeError(ErrorLoc, Lower, Upper, Msg);
1368}
1369
1370bool RISCVAsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1371 OperandVector &Operands,
1372 MCStreamer &Out,
1373 uint64_t &ErrorInfo,
1374 bool MatchingInlineAsm) {
1375 MCInst Inst;
1376 FeatureBitset MissingFeatures;
1377
1378 auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
1379 matchingInlineAsm: MatchingInlineAsm);
1380 switch (Result) {
1381 default:
1382 break;
1383 case Match_Success:
1384 if (validateInstruction(Inst, Operands))
1385 return true;
1386 return processInstruction(Inst, IDLoc, Operands, Out);
1387 case Match_MissingFeature: {
1388 assert(MissingFeatures.any() && "Unknown missing features!");
1389 bool FirstFeature = true;
1390 std::string Msg = "instruction requires the following:";
1391 for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
1392 if (MissingFeatures[i]) {
1393 Msg += FirstFeature ? " " : ", ";
1394 Msg += getSubtargetFeatureName(Val: i);
1395 FirstFeature = false;
1396 }
1397 }
1398 return Error(L: IDLoc, Msg);
1399 }
1400 case Match_MnemonicFail: {
1401 FeatureBitset FBS = ComputeAvailableFeatures(FB: getSTI().getFeatureBits());
1402 std::string Suggestion = RISCVMnemonicSpellCheck(
1403 S: ((RISCVOperand &)*Operands[0]).getToken(), FBS, VariantID: 0);
1404 return Error(L: IDLoc, Msg: "unrecognized instruction mnemonic" + Suggestion);
1405 }
1406 case Match_InvalidOperand: {
1407 SMLoc ErrorLoc = IDLoc;
1408 if (ErrorInfo != ~0ULL) {
1409 if (ErrorInfo >= Operands.size())
1410 return Error(L: ErrorLoc, Msg: "too few operands for instruction");
1411
1412 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1413 if (ErrorLoc == SMLoc())
1414 ErrorLoc = IDLoc;
1415 }
1416 return Error(L: ErrorLoc, Msg: "invalid operand for instruction");
1417 }
1418 }
1419
1420 // Handle the case when the error message is of specific type
1421 // other than the generic Match_InvalidOperand, and the
1422 // corresponding operand is missing.
1423 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
1424 SMLoc ErrorLoc = IDLoc;
1425 if (ErrorInfo != ~0ULL && ErrorInfo >= Operands.size())
1426 return Error(L: ErrorLoc, Msg: "too few operands for instruction");
1427 }
1428
1429 switch (Result) {
1430 default:
1431 break;
1432 case Match_InvalidImmXLenLI:
1433 if (isRV64()) {
1434 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1435 return Error(L: ErrorLoc, Msg: "operand must be a constant 64-bit integer");
1436 }
1437 return generateImmOutOfRangeError(Operands, ErrorInfo,
1438 Lower: std::numeric_limits<int32_t>::min(),
1439 Upper: std::numeric_limits<uint32_t>::max());
1440 case Match_InvalidImmXLenLI_Restricted:
1441 if (isRV64()) {
1442 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1443 return Error(L: ErrorLoc, Msg: "operand either must be a constant 64-bit integer "
1444 "or a bare symbol name");
1445 }
1446 return generateImmOutOfRangeError(
1447 Operands, ErrorInfo, Lower: std::numeric_limits<int32_t>::min(),
1448 Upper: std::numeric_limits<uint32_t>::max(),
1449 Msg: "operand either must be a bare symbol name or an immediate integer in "
1450 "the range");
1451 case Match_InvalidUImmLog2XLen:
1452 if (isRV64())
1453 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 6) - 1);
1454 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 5) - 1);
1455 case Match_InvalidUImmLog2XLenNonZero:
1456 if (isRV64())
1457 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 1, Upper: (1 << 6) - 1);
1458 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 1, Upper: (1 << 5) - 1);
1459 case Match_InvalidUImm1:
1460 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 1) - 1);
1461 case Match_InvalidUImm2:
1462 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 2) - 1);
1463 case Match_InvalidUImm2Lsb0:
1464 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: 2,
1465 Msg: "immediate must be one of");
1466 case Match_InvalidUImm3:
1467 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 3) - 1);
1468 case Match_InvalidUImm4:
1469 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 4) - 1);
1470 case Match_InvalidUImm5:
1471 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 5) - 1);
1472 case Match_InvalidUImm5NonZero:
1473 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 1, Upper: (1 << 5) - 1);
1474 case Match_InvalidUImm5GT3:
1475 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 4, Upper: (1 << 5) - 1);
1476 case Match_InvalidUImm5Plus1:
1477 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 1, Upper: (1 << 5));
1478 case Match_InvalidUImm5GE6Plus1:
1479 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 6, Upper: (1 << 5));
1480 case Match_InvalidUImm5Slist: {
1481 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1482 return Error(L: ErrorLoc,
1483 Msg: "immediate must be one of: 0, 1, 2, 4, 8, 15, 16, 31");
1484 }
1485 case Match_InvalidUImm6:
1486 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 6) - 1);
1487 case Match_InvalidUImm7:
1488 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 7) - 1);
1489 case Match_InvalidUImm8:
1490 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 8) - 1);
1491 case Match_InvalidUImm8GE32:
1492 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 32, Upper: (1 << 8) - 1);
1493 case Match_InvalidSImm5:
1494 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 4),
1495 Upper: (1 << 4) - 1);
1496 case Match_InvalidSImm5NonZero:
1497 return generateImmOutOfRangeError(
1498 Operands, ErrorInfo, Lower: -(1 << 4), Upper: (1 << 4) - 1,
1499 Msg: "immediate must be non-zero in the range");
1500 case Match_InvalidSImm6:
1501 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 5),
1502 Upper: (1 << 5) - 1);
1503 case Match_InvalidSImm6NonZero:
1504 return generateImmOutOfRangeError(
1505 Operands, ErrorInfo, Lower: -(1 << 5), Upper: (1 << 5) - 1,
1506 Msg: "immediate must be non-zero in the range");
1507 case Match_InvalidCLUIImm:
1508 return generateImmOutOfRangeError(
1509 Operands, ErrorInfo, Lower: 1, Upper: (1 << 5) - 1,
1510 Msg: "immediate must be in [0xfffe0, 0xfffff] or");
1511 case Match_InvalidUImm5Lsb0:
1512 return generateImmOutOfRangeError(
1513 Operands, ErrorInfo, Lower: 0, Upper: (1 << 5) - 2,
1514 Msg: "immediate must be a multiple of 2 bytes in the range");
1515 case Match_InvalidUImm6Lsb0:
1516 return generateImmOutOfRangeError(
1517 Operands, ErrorInfo, Lower: 0, Upper: (1 << 6) - 2,
1518 Msg: "immediate must be a multiple of 2 bytes in the range");
1519 case Match_InvalidUImm7Lsb00:
1520 return generateImmOutOfRangeError(
1521 Operands, ErrorInfo, Lower: 0, Upper: (1 << 7) - 4,
1522 Msg: "immediate must be a multiple of 4 bytes in the range");
1523 case Match_InvalidUImm8Lsb00:
1524 return generateImmOutOfRangeError(
1525 Operands, ErrorInfo, Lower: 0, Upper: (1 << 8) - 4,
1526 Msg: "immediate must be a multiple of 4 bytes in the range");
1527 case Match_InvalidUImm8Lsb000:
1528 return generateImmOutOfRangeError(
1529 Operands, ErrorInfo, Lower: 0, Upper: (1 << 8) - 8,
1530 Msg: "immediate must be a multiple of 8 bytes in the range");
1531 case Match_InvalidUImm9:
1532 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 9) - 1,
1533 Msg: "immediate offset must be in the range");
1534 case Match_InvalidBareSImm9Lsb0:
1535 return generateImmOutOfRangeError(
1536 Operands, ErrorInfo, Lower: -(1 << 8), Upper: (1 << 8) - 2,
1537 Msg: "immediate must be a multiple of 2 bytes in the range");
1538 case Match_InvalidUImm9Lsb000:
1539 return generateImmOutOfRangeError(
1540 Operands, ErrorInfo, Lower: 0, Upper: (1 << 9) - 8,
1541 Msg: "immediate must be a multiple of 8 bytes in the range");
1542 case Match_InvalidSImm10:
1543 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 9),
1544 Upper: (1 << 9) - 1);
1545 case Match_InvalidSImm10Unsigned:
1546 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 9),
1547 Upper: (1 << 10) - 1);
1548 case Match_InvalidUImm10Lsb00NonZero:
1549 return generateImmOutOfRangeError(
1550 Operands, ErrorInfo, Lower: 4, Upper: (1 << 10) - 4,
1551 Msg: "immediate must be a multiple of 4 bytes in the range");
1552 case Match_InvalidSImm10Lsb0000NonZero:
1553 return generateImmOutOfRangeError(
1554 Operands, ErrorInfo, Lower: -(1 << 9), Upper: (1 << 9) - 16,
1555 Msg: "immediate must be a multiple of 16 bytes and non-zero in the range");
1556 case Match_InvalidSImm11:
1557 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 10),
1558 Upper: (1 << 10) - 1);
1559 case Match_InvalidBareSImm11Lsb0:
1560 return generateImmOutOfRangeError(
1561 Operands, ErrorInfo, Lower: -(1 << 10), Upper: (1 << 10) - 2,
1562 Msg: "immediate must be a multiple of 2 bytes in the range");
1563 case Match_InvalidUImm10:
1564 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 10) - 1);
1565 case Match_InvalidUImm11:
1566 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 11) - 1);
1567 case Match_InvalidUImm14Lsb00:
1568 return generateImmOutOfRangeError(
1569 Operands, ErrorInfo, Lower: 0, Upper: (1 << 14) - 4,
1570 Msg: "immediate must be a multiple of 4 bytes in the range");
1571 case Match_InvalidUImm16NonZero:
1572 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 1, Upper: (1 << 16) - 1);
1573 case Match_InvalidSImm12:
1574 return generateImmOutOfRangeError(
1575 Operands, ErrorInfo, Lower: -(1 << 11), Upper: (1 << 11) - 1,
1576 Msg: "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo specifier or an "
1577 "integer in the range");
1578 case Match_InvalidBareSImm12Lsb0:
1579 return generateImmOutOfRangeError(
1580 Operands, ErrorInfo, Lower: -(1 << 11), Upper: (1 << 11) - 2,
1581 Msg: "immediate must be a multiple of 2 bytes in the range");
1582 case Match_InvalidSImm12Lsb00000:
1583 return generateImmOutOfRangeError(
1584 Operands, ErrorInfo, Lower: -(1 << 11), Upper: (1 << 11) - 32,
1585 Msg: "immediate must be a multiple of 32 bytes in the range");
1586 case Match_InvalidBareSImm13Lsb0:
1587 return generateImmOutOfRangeError(
1588 Operands, ErrorInfo, Lower: -(1 << 12), Upper: (1 << 12) - 2,
1589 Msg: "immediate must be a multiple of 2 bytes in the range");
1590 case Match_InvalidSImm16:
1591 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 15),
1592 Upper: (1 << 15) - 1);
1593 case Match_InvalidSImm16NonZero:
1594 return generateImmOutOfRangeError(
1595 Operands, ErrorInfo, Lower: -(1 << 15), Upper: (1 << 15) - 1,
1596 Msg: "immediate must be non-zero in the range");
1597 case Match_InvalidSImm20LI:
1598 return generateImmOutOfRangeError(
1599 Operands, ErrorInfo, Lower: -(1 << 19), Upper: (1 << 19) - 1,
1600 Msg: "operand must be a symbol with a %qc.abs20 specifier or an integer "
1601 " in the range");
1602 case Match_InvalidUImm20LUI:
1603 return generateImmOutOfRangeError(
1604 Operands, ErrorInfo, Lower: 0, Upper: (1 << 20) - 1,
1605 Msg: "operand must be a symbol with "
1606 "%hi/%tprel_hi specifier or an integer in "
1607 "the range");
1608 case Match_InvalidUImm20:
1609 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 20) - 1);
1610 case Match_InvalidUImm20AUIPC:
1611 return generateImmOutOfRangeError(
1612 Operands, ErrorInfo, Lower: 0, Upper: (1 << 20) - 1,
1613 Msg: "operand must be a symbol with a "
1614 "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi specifier "
1615 "or "
1616 "an integer in the range");
1617 case Match_InvalidBareSImm21Lsb0:
1618 return generateImmOutOfRangeError(
1619 Operands, ErrorInfo, Lower: -(1 << 20), Upper: (1 << 20) - 2,
1620 Msg: "immediate must be a multiple of 2 bytes in the range");
1621 case Match_InvalidCSRSystemRegister: {
1622 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: (1 << 12) - 1,
1623 Msg: "operand must be a valid system register "
1624 "name or an integer in the range");
1625 }
1626 case Match_InvalidVTypeI: {
1627 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1628 return generateVTypeError(ErrorLoc);
1629 }
1630 case Match_InvalidSImm5Plus1: {
1631 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 4) + 1,
1632 Upper: (1 << 4),
1633 Msg: "immediate must be in the range");
1634 }
1635 case Match_InvalidSImm18:
1636 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 17),
1637 Upper: (1 << 17) - 1);
1638 case Match_InvalidSImm18Lsb0:
1639 return generateImmOutOfRangeError(
1640 Operands, ErrorInfo, Lower: -(1 << 17), Upper: (1 << 17) - 2,
1641 Msg: "immediate must be a multiple of 2 bytes in the range");
1642 case Match_InvalidSImm19Lsb00:
1643 return generateImmOutOfRangeError(
1644 Operands, ErrorInfo, Lower: -(1 << 18), Upper: (1 << 18) - 4,
1645 Msg: "immediate must be a multiple of 4 bytes in the range");
1646 case Match_InvalidSImm20Lsb000:
1647 return generateImmOutOfRangeError(
1648 Operands, ErrorInfo, Lower: -(1 << 19), Upper: (1 << 19) - 8,
1649 Msg: "immediate must be a multiple of 8 bytes in the range");
1650 case Match_InvalidSImm26:
1651 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: -(1 << 25),
1652 Upper: (1 << 25) - 1);
1653 case Match_InvalidBareSImm32:
1654 return generateImmOutOfRangeError(Operands, ErrorInfo,
1655 Lower: std::numeric_limits<int32_t>::min(),
1656 Upper: std::numeric_limits<uint32_t>::max());
1657 case Match_InvalidBareSImm32Lsb0:
1658 return generateImmOutOfRangeError(
1659 Operands, ErrorInfo, Lower: std::numeric_limits<int32_t>::min(),
1660 Upper: std::numeric_limits<int32_t>::max() - 1,
1661 Msg: "operand must be a multiple of 2 bytes in the range");
1662 case Match_InvalidRnumArg: {
1663 return generateImmOutOfRangeError(Operands, ErrorInfo, Lower: 0, Upper: 10);
1664 }
1665 case Match_InvalidStackAdj: {
1666 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1667 return Error(
1668 L: ErrorLoc,
1669 Msg: "stack adjustment is invalid for this instruction and register list");
1670 }
1671 }
1672
1673 if (const char *MatchDiag = getMatchKindDiag(MatchResult: (RISCVMatchResultTy)Result)) {
1674 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1675 return Error(L: ErrorLoc, Msg: MatchDiag);
1676 }
1677
1678 llvm_unreachable("Unknown match type detected!");
1679}
1680
1681// Attempts to match Name as a register (either using the default name or
1682// alternative ABI names), returning the matching register. Upon failure,
1683// returns a non-valid MCRegister. If IsRVE, then registers x16-x31 will be
1684// rejected.
1685MCRegister RISCVAsmParser::matchRegisterNameHelper(StringRef Name) const {
1686 MCRegister Reg = MatchRegisterName(Name);
1687 // The 16-/32-/128- and 64-bit FPRs have the same asm name. Check
1688 // that the initial match always matches the 64-bit variant, and
1689 // not the 16/32/128-bit one.
1690 assert(!(Reg >= RISCV::F0_H && Reg <= RISCV::F31_H));
1691 assert(!(Reg >= RISCV::F0_F && Reg <= RISCV::F31_F));
1692 assert(!(Reg >= RISCV::F0_Q && Reg <= RISCV::F31_Q));
1693 // The default FPR register class is based on the tablegen enum ordering.
1694 static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1695 static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1696 static_assert(RISCV::F0_D < RISCV::F0_Q, "FPR matching must be updated");
1697 if (!Reg)
1698 Reg = MatchRegisterAltName(Name);
1699 if (isRVE() && Reg >= RISCV::X16 && Reg <= RISCV::X31)
1700 Reg = MCRegister();
1701 return Reg;
1702}
1703
1704bool RISCVAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1705 SMLoc &EndLoc) {
1706 if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
1707 return Error(L: StartLoc, Msg: "invalid register name");
1708 return false;
1709}
1710
1711ParseStatus RISCVAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1712 SMLoc &EndLoc) {
1713 const AsmToken &Tok = getParser().getTok();
1714 StartLoc = Tok.getLoc();
1715 EndLoc = Tok.getEndLoc();
1716 StringRef Name = getLexer().getTok().getIdentifier();
1717
1718 Reg = matchRegisterNameHelper(Name);
1719 if (!Reg)
1720 return ParseStatus::NoMatch;
1721
1722 getParser().Lex(); // Eat identifier token.
1723 return ParseStatus::Success;
1724}
1725
1726ParseStatus RISCVAsmParser::parseRegister(OperandVector &Operands,
1727 bool AllowParens) {
1728 SMLoc FirstS = getLoc();
1729 bool HadParens = false;
1730 AsmToken LParen;
1731
1732 // If this is an LParen and a parenthesised register name is allowed, parse it
1733 // atomically.
1734 if (AllowParens && getLexer().is(K: AsmToken::LParen)) {
1735 AsmToken Buf[2];
1736 size_t ReadCount = getLexer().peekTokens(Buf);
1737 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1738 HadParens = true;
1739 LParen = getParser().getTok();
1740 getParser().Lex(); // Eat '('
1741 }
1742 }
1743
1744 switch (getLexer().getKind()) {
1745 default:
1746 if (HadParens)
1747 getLexer().UnLex(Token: LParen);
1748 return ParseStatus::NoMatch;
1749 case AsmToken::Identifier:
1750 StringRef Name = getLexer().getTok().getIdentifier();
1751 MCRegister Reg = matchRegisterNameHelper(Name);
1752
1753 if (!Reg) {
1754 if (HadParens)
1755 getLexer().UnLex(Token: LParen);
1756 return ParseStatus::NoMatch;
1757 }
1758 if (HadParens)
1759 Operands.push_back(Elt: RISCVOperand::createToken(Str: "(", S: FirstS));
1760 SMLoc S = getLoc();
1761 SMLoc E = getTok().getEndLoc();
1762 getLexer().Lex();
1763 Operands.push_back(Elt: RISCVOperand::createReg(Reg, S, E));
1764 }
1765
1766 if (HadParens) {
1767 getParser().Lex(); // Eat ')'
1768 Operands.push_back(Elt: RISCVOperand::createToken(Str: ")", S: getLoc()));
1769 }
1770
1771 return ParseStatus::Success;
1772}
1773
1774ParseStatus RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
1775 SMLoc S = getLoc();
1776 SMLoc E;
1777 const MCExpr *Res;
1778
1779 switch (getLexer().getKind()) {
1780 default:
1781 return ParseStatus::NoMatch;
1782 case AsmToken::LParen:
1783 case AsmToken::Minus:
1784 case AsmToken::Plus:
1785 case AsmToken::Exclaim:
1786 case AsmToken::Tilde:
1787 case AsmToken::Integer:
1788 case AsmToken::String: {
1789 if (getParser().parseExpression(Res, EndLoc&: E))
1790 return ParseStatus::Failure;
1791
1792 auto *CE = dyn_cast<MCConstantExpr>(Val: Res);
1793 if (CE) {
1794 int64_t Imm = CE->getValue();
1795 if (isUInt<7>(x: Imm)) {
1796 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
1797 return ParseStatus::Success;
1798 }
1799 }
1800
1801 break;
1802 }
1803 case AsmToken::Identifier: {
1804 StringRef Identifier;
1805 if (getParser().parseIdentifier(Res&: Identifier))
1806 return ParseStatus::Failure;
1807
1808 auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Name: Identifier);
1809 if (Opcode) {
1810 assert(isUInt<7>(Opcode->Value) && (Opcode->Value & 0x3) == 3 &&
1811 "Unexpected opcode");
1812 Res = MCConstantExpr::create(Value: Opcode->Value, Ctx&: getContext());
1813 E = SMLoc::getFromPointer(Ptr: S.getPointer() + Identifier.size());
1814 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
1815 return ParseStatus::Success;
1816 }
1817
1818 break;
1819 }
1820 case AsmToken::Percent:
1821 break;
1822 }
1823
1824 return generateImmOutOfRangeError(
1825 ErrorLoc: S, Lower: 0, Upper: 127,
1826 Msg: "opcode must be a valid opcode name or an immediate in the range");
1827}
1828
1829ParseStatus RISCVAsmParser::parseInsnCDirectiveOpcode(OperandVector &Operands) {
1830 SMLoc S = getLoc();
1831 SMLoc E;
1832 const MCExpr *Res;
1833
1834 switch (getLexer().getKind()) {
1835 default:
1836 return ParseStatus::NoMatch;
1837 case AsmToken::LParen:
1838 case AsmToken::Minus:
1839 case AsmToken::Plus:
1840 case AsmToken::Exclaim:
1841 case AsmToken::Tilde:
1842 case AsmToken::Integer:
1843 case AsmToken::String: {
1844 if (getParser().parseExpression(Res, EndLoc&: E))
1845 return ParseStatus::Failure;
1846
1847 auto *CE = dyn_cast<MCConstantExpr>(Val: Res);
1848 if (CE) {
1849 int64_t Imm = CE->getValue();
1850 if (Imm >= 0 && Imm <= 2) {
1851 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
1852 return ParseStatus::Success;
1853 }
1854 }
1855
1856 break;
1857 }
1858 case AsmToken::Identifier: {
1859 StringRef Identifier;
1860 if (getParser().parseIdentifier(Res&: Identifier))
1861 return ParseStatus::Failure;
1862
1863 unsigned Opcode;
1864 if (Identifier == "C0")
1865 Opcode = 0;
1866 else if (Identifier == "C1")
1867 Opcode = 1;
1868 else if (Identifier == "C2")
1869 Opcode = 2;
1870 else
1871 break;
1872
1873 Res = MCConstantExpr::create(Value: Opcode, Ctx&: getContext());
1874 E = SMLoc::getFromPointer(Ptr: S.getPointer() + Identifier.size());
1875 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
1876 return ParseStatus::Success;
1877 }
1878 case AsmToken::Percent: {
1879 // Discard operand with modifier.
1880 break;
1881 }
1882 }
1883
1884 return generateImmOutOfRangeError(
1885 ErrorLoc: S, Lower: 0, Upper: 2,
1886 Msg: "opcode must be a valid opcode name or an immediate in the range");
1887}
1888
1889ParseStatus RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1890 SMLoc S = getLoc();
1891 const MCExpr *Res;
1892
1893 auto SysRegFromConstantInt = [this](const MCExpr *E, SMLoc S) {
1894 if (auto *CE = dyn_cast<MCConstantExpr>(Val: E)) {
1895 int64_t Imm = CE->getValue();
1896 if (isUInt<12>(x: Imm)) {
1897 auto Range = RISCVSysReg::lookupSysRegByEncoding(Encoding: Imm);
1898 // Accept an immediate representing a named Sys Reg if it satisfies the
1899 // the required features.
1900 for (auto &Reg : Range) {
1901 if (Reg.IsAltName || Reg.IsDeprecatedName)
1902 continue;
1903 if (Reg.haveRequiredFeatures(ActiveFeatures: STI->getFeatureBits()))
1904 return RISCVOperand::createSysReg(Str: Reg.Name, S, Encoding: Imm);
1905 }
1906 // Accept an immediate representing an un-named Sys Reg if the range is
1907 // valid, regardless of the required features.
1908 return RISCVOperand::createSysReg(Str: "", S, Encoding: Imm);
1909 }
1910 }
1911 return std::unique_ptr<RISCVOperand>();
1912 };
1913
1914 switch (getLexer().getKind()) {
1915 default:
1916 return ParseStatus::NoMatch;
1917 case AsmToken::LParen:
1918 case AsmToken::Minus:
1919 case AsmToken::Plus:
1920 case AsmToken::Exclaim:
1921 case AsmToken::Tilde:
1922 case AsmToken::Integer:
1923 case AsmToken::String: {
1924 if (getParser().parseExpression(Res))
1925 return ParseStatus::Failure;
1926
1927 if (auto SysOpnd = SysRegFromConstantInt(Res, S)) {
1928 Operands.push_back(Elt: std::move(SysOpnd));
1929 return ParseStatus::Success;
1930 }
1931
1932 return generateImmOutOfRangeError(ErrorLoc: S, Lower: 0, Upper: (1 << 12) - 1);
1933 }
1934 case AsmToken::Identifier: {
1935 StringRef Identifier;
1936 if (getParser().parseIdentifier(Res&: Identifier))
1937 return ParseStatus::Failure;
1938
1939 const auto *SysReg = RISCVSysReg::lookupSysRegByName(Name: Identifier);
1940
1941 if (SysReg) {
1942 if (SysReg->IsDeprecatedName) {
1943 // Lookup the undeprecated name.
1944 auto Range = RISCVSysReg::lookupSysRegByEncoding(Encoding: SysReg->Encoding);
1945 for (auto &Reg : Range) {
1946 if (Reg.IsAltName || Reg.IsDeprecatedName)
1947 continue;
1948 Warning(L: S, Msg: "'" + Identifier + "' is a deprecated alias for '" +
1949 Reg.Name + "'");
1950 }
1951 }
1952
1953 // Accept a named Sys Reg if the required features are present.
1954 const auto &FeatureBits = getSTI().getFeatureBits();
1955 if (!SysReg->haveRequiredFeatures(ActiveFeatures: FeatureBits)) {
1956 const auto *Feature = llvm::find_if(Range: RISCVFeatureKV, P: [&](auto Feature) {
1957 return SysReg->FeaturesRequired[Feature.Value];
1958 });
1959 auto ErrorMsg = std::string("system register '") + SysReg->Name + "' ";
1960 if (SysReg->IsRV32Only && FeatureBits[RISCV::Feature64Bit]) {
1961 ErrorMsg += "is RV32 only";
1962 if (Feature != std::end(arr: RISCVFeatureKV))
1963 ErrorMsg += " and ";
1964 }
1965 if (Feature != std::end(arr: RISCVFeatureKV)) {
1966 ErrorMsg +=
1967 "requires '" + std::string(Feature->Key) + "' to be enabled";
1968 }
1969
1970 return Error(L: S, Msg: ErrorMsg);
1971 }
1972 Operands.push_back(
1973 Elt: RISCVOperand::createSysReg(Str: Identifier, S, Encoding: SysReg->Encoding));
1974 return ParseStatus::Success;
1975 }
1976
1977 // Accept a symbol name that evaluates to an absolute value.
1978 MCSymbol *Sym = getContext().lookupSymbol(Name: Identifier);
1979 if (Sym && Sym->isVariable()) {
1980 // Pass false for SetUsed, since redefining the value later does not
1981 // affect this instruction.
1982 if (auto SysOpnd = SysRegFromConstantInt(Sym->getVariableValue(), S)) {
1983 Operands.push_back(Elt: std::move(SysOpnd));
1984 return ParseStatus::Success;
1985 }
1986 }
1987
1988 return generateImmOutOfRangeError(ErrorLoc: S, Lower: 0, Upper: (1 << 12) - 1,
1989 Msg: "operand must be a valid system register "
1990 "name or an integer in the range");
1991 }
1992 case AsmToken::Percent: {
1993 // Discard operand with modifier.
1994 return generateImmOutOfRangeError(ErrorLoc: S, Lower: 0, Upper: (1 << 12) - 1);
1995 }
1996 }
1997
1998 return ParseStatus::NoMatch;
1999}
2000
2001ParseStatus RISCVAsmParser::parseFPImm(OperandVector &Operands) {
2002 SMLoc S = getLoc();
2003
2004 // Parse special floats (inf/nan/min) representation.
2005 if (getTok().is(K: AsmToken::Identifier)) {
2006 StringRef Identifier = getTok().getIdentifier();
2007 if (Identifier.compare_insensitive(RHS: "inf") == 0) {
2008 Operands.push_back(
2009 Elt: RISCVOperand::createImm(Val: MCConstantExpr::create(Value: 30, Ctx&: getContext()), S,
2010 E: getTok().getEndLoc(), IsRV64: isRV64()));
2011 } else if (Identifier.compare_insensitive(RHS: "nan") == 0) {
2012 Operands.push_back(
2013 Elt: RISCVOperand::createImm(Val: MCConstantExpr::create(Value: 31, Ctx&: getContext()), S,
2014 E: getTok().getEndLoc(), IsRV64: isRV64()));
2015 } else if (Identifier.compare_insensitive(RHS: "min") == 0) {
2016 Operands.push_back(
2017 Elt: RISCVOperand::createImm(Val: MCConstantExpr::create(Value: 1, Ctx&: getContext()), S,
2018 E: getTok().getEndLoc(), IsRV64: isRV64()));
2019 } else {
2020 return TokError(Msg: "invalid floating point literal");
2021 }
2022
2023 Lex(); // Eat the token.
2024
2025 return ParseStatus::Success;
2026 }
2027
2028 // Handle negation, as that still comes through as a separate token.
2029 bool IsNegative = parseOptionalToken(T: AsmToken::Minus);
2030
2031 const AsmToken &Tok = getTok();
2032 if (!Tok.is(K: AsmToken::Real))
2033 return TokError(Msg: "invalid floating point immediate");
2034
2035 // Parse FP representation.
2036 APFloat RealVal(APFloat::IEEEdouble());
2037 auto StatusOrErr =
2038 RealVal.convertFromString(Tok.getString(), APFloat::rmTowardZero);
2039 if (errorToBool(Err: StatusOrErr.takeError()))
2040 return TokError(Msg: "invalid floating point representation");
2041
2042 if (IsNegative)
2043 RealVal.changeSign();
2044
2045 Operands.push_back(Elt: RISCVOperand::createFPImm(
2046 Val: RealVal.bitcastToAPInt().getZExtValue(), S));
2047
2048 Lex(); // Eat the token.
2049
2050 return ParseStatus::Success;
2051}
2052
2053ParseStatus RISCVAsmParser::parseImmediate(OperandVector &Operands) {
2054 SMLoc S = getLoc();
2055 SMLoc E;
2056 const MCExpr *Res;
2057
2058 switch (getLexer().getKind()) {
2059 default:
2060 return ParseStatus::NoMatch;
2061 case AsmToken::LParen:
2062 case AsmToken::Dot:
2063 case AsmToken::Minus:
2064 case AsmToken::Plus:
2065 case AsmToken::Exclaim:
2066 case AsmToken::Tilde:
2067 case AsmToken::Integer:
2068 case AsmToken::String:
2069 case AsmToken::Identifier:
2070 if (getParser().parseExpression(Res, EndLoc&: E))
2071 return ParseStatus::Failure;
2072 break;
2073 case AsmToken::Percent:
2074 return parseOperandWithSpecifier(Operands);
2075 }
2076
2077 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
2078 return ParseStatus::Success;
2079}
2080
2081ParseStatus RISCVAsmParser::parseOperandWithSpecifier(OperandVector &Operands) {
2082 SMLoc S = getLoc();
2083 SMLoc E;
2084
2085 if (parseToken(T: AsmToken::Percent, Msg: "expected '%' relocation specifier"))
2086 return ParseStatus::Failure;
2087 const MCExpr *Expr = nullptr;
2088 bool Failed = parseExprWithSpecifier(Res&: Expr, E);
2089 if (!Failed)
2090 Operands.push_back(Elt: RISCVOperand::createImm(Val: Expr, S, E, IsRV64: isRV64()));
2091 return Failed;
2092}
2093
2094bool RISCVAsmParser::parseExprWithSpecifier(const MCExpr *&Res, SMLoc &E) {
2095 if (getLexer().getKind() != AsmToken::Identifier)
2096 return Error(L: getLoc(), Msg: "expected '%' relocation specifier");
2097 StringRef Identifier = getParser().getTok().getIdentifier();
2098 auto Spec = RISCV::parseSpecifierName(name: Identifier);
2099 if (!Spec)
2100 return Error(L: getLoc(), Msg: "invalid relocation specifier");
2101
2102 getParser().Lex(); // Eat the identifier
2103 if (parseToken(T: AsmToken::LParen, Msg: "expected '('"))
2104 return true;
2105
2106 const MCExpr *SubExpr;
2107 if (getParser().parseParenExpression(Res&: SubExpr, EndLoc&: E))
2108 return true;
2109
2110 Res = MCSpecifierExpr::create(Expr: SubExpr, S: Spec, Ctx&: getContext(), Loc: SubExpr->getLoc());
2111 return false;
2112}
2113
2114bool RISCVAsmParser::parseDataExpr(const MCExpr *&Res) {
2115 SMLoc E;
2116 if (parseOptionalToken(T: AsmToken::Percent))
2117 return parseExprWithSpecifier(Res, E);
2118 return getParser().parseExpression(Res);
2119}
2120
2121ParseStatus RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
2122 SMLoc S = getLoc();
2123 const MCExpr *Res;
2124
2125 if (getLexer().getKind() != AsmToken::Identifier)
2126 return ParseStatus::NoMatch;
2127
2128 StringRef Identifier;
2129 AsmToken Tok = getLexer().getTok();
2130
2131 if (getParser().parseIdentifier(Res&: Identifier))
2132 return ParseStatus::Failure;
2133
2134 SMLoc E = SMLoc::getFromPointer(Ptr: S.getPointer() + Identifier.size());
2135
2136 MCSymbol *Sym = getContext().getOrCreateSymbol(Name: Identifier);
2137
2138 if (Sym->isVariable()) {
2139 const MCExpr *V = Sym->getVariableValue();
2140 if (!isa<MCSymbolRefExpr>(Val: V)) {
2141 getLexer().UnLex(Token: Tok); // Put back if it's not a bare symbol.
2142 return ParseStatus::NoMatch;
2143 }
2144 Res = V;
2145 } else
2146 Res = MCSymbolRefExpr::create(Symbol: Sym, Ctx&: getContext());
2147
2148 MCBinaryExpr::Opcode Opcode;
2149 switch (getLexer().getKind()) {
2150 default:
2151 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
2152 return ParseStatus::Success;
2153 case AsmToken::Plus:
2154 Opcode = MCBinaryExpr::Add;
2155 getLexer().Lex();
2156 break;
2157 case AsmToken::Minus:
2158 Opcode = MCBinaryExpr::Sub;
2159 getLexer().Lex();
2160 break;
2161 }
2162
2163 const MCExpr *Expr;
2164 if (getParser().parseExpression(Res&: Expr, EndLoc&: E))
2165 return ParseStatus::Failure;
2166 Res = MCBinaryExpr::create(Op: Opcode, LHS: Res, RHS: Expr, Ctx&: getContext());
2167 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
2168 return ParseStatus::Success;
2169}
2170
2171ParseStatus RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
2172 SMLoc S = getLoc();
2173 const MCExpr *Res;
2174
2175 if (getLexer().getKind() != AsmToken::Identifier)
2176 return ParseStatus::NoMatch;
2177 std::string Identifier(getTok().getIdentifier());
2178
2179 if (getLexer().peekTok().is(K: AsmToken::At)) {
2180 Lex();
2181 Lex();
2182 StringRef PLT;
2183 SMLoc Loc = getLoc();
2184 if (getParser().parseIdentifier(Res&: PLT) || PLT != "plt")
2185 return Error(L: Loc, Msg: "@ (except the deprecated/ignored @plt) is disallowed");
2186 } else if (!getLexer().peekTok().is(K: AsmToken::EndOfStatement)) {
2187 // Avoid parsing the register in `call rd, foo` as a call symbol.
2188 return ParseStatus::NoMatch;
2189 } else {
2190 Lex();
2191 }
2192
2193 SMLoc E = SMLoc::getFromPointer(Ptr: S.getPointer() + Identifier.size());
2194 RISCV::Specifier Kind = ELF::R_RISCV_CALL_PLT;
2195
2196 MCSymbol *Sym = getContext().getOrCreateSymbol(Name: Identifier);
2197 Res = MCSymbolRefExpr::create(Symbol: Sym, Ctx&: getContext());
2198 Res = MCSpecifierExpr::create(Expr: Res, S: Kind, Ctx&: getContext());
2199 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
2200 return ParseStatus::Success;
2201}
2202
2203ParseStatus RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
2204 SMLoc S = getLoc();
2205 SMLoc E;
2206 const MCExpr *Res;
2207
2208 if (getParser().parseExpression(Res, EndLoc&: E))
2209 return ParseStatus::Failure;
2210
2211 if (Res->getKind() != MCExpr::ExprKind::SymbolRef)
2212 return Error(L: S, Msg: "operand must be a valid jump target");
2213
2214 Res = MCSpecifierExpr::create(Expr: Res, S: ELF::R_RISCV_CALL_PLT, Ctx&: getContext());
2215 Operands.push_back(Elt: RISCVOperand::createImm(Val: Res, S, E, IsRV64: isRV64()));
2216 return ParseStatus::Success;
2217}
2218
2219ParseStatus RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
2220 // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
2221 // both being acceptable forms. When parsing `jal ra, foo` this function
2222 // will be called for the `ra` register operand in an attempt to match the
2223 // single-operand alias. parseJALOffset must fail for this case. It would
2224 // seem logical to try parse the operand using parseImmediate and return
2225 // NoMatch if the next token is a comma (meaning we must be parsing a jal in
2226 // the second form rather than the first). We can't do this as there's no
2227 // way of rewinding the lexer state. Instead, return NoMatch if this operand
2228 // is an identifier and is followed by a comma.
2229 if (getLexer().is(K: AsmToken::Identifier) &&
2230 getLexer().peekTok().is(K: AsmToken::Comma))
2231 return ParseStatus::NoMatch;
2232
2233 return parseImmediate(Operands);
2234}
2235
2236bool RISCVAsmParser::parseVTypeToken(const AsmToken &Tok, VTypeState &State,
2237 unsigned &Sew, unsigned &Lmul,
2238 bool &Fractional, bool &TailAgnostic,
2239 bool &MaskAgnostic) {
2240 if (Tok.isNot(K: AsmToken::Identifier))
2241 return true;
2242
2243 StringRef Identifier = Tok.getIdentifier();
2244 if (State < VTypeState::SeenSew && Identifier.consume_front(Prefix: "e")) {
2245 if (Identifier.getAsInteger(Radix: 10, Result&: Sew))
2246 return true;
2247 if (!RISCVVType::isValidSEW(SEW: Sew))
2248 return true;
2249
2250 State = VTypeState::SeenSew;
2251 return false;
2252 }
2253
2254 if (State < VTypeState::SeenLmul && Identifier.consume_front(Prefix: "m")) {
2255 // Might arrive here if lmul and tail policy unspecified, if so we're
2256 // parsing a MaskPolicy not an LMUL.
2257 if (Identifier == "a" || Identifier == "u") {
2258 MaskAgnostic = (Identifier == "a");
2259 State = VTypeState::SeenMaskPolicy;
2260 return false;
2261 }
2262
2263 Fractional = Identifier.consume_front(Prefix: "f");
2264 if (Identifier.getAsInteger(Radix: 10, Result&: Lmul))
2265 return true;
2266 if (!RISCVVType::isValidLMUL(LMUL: Lmul, Fractional))
2267 return true;
2268
2269 if (Fractional) {
2270 unsigned ELEN = STI->hasFeature(Feature: RISCV::FeatureStdExtZve64x) ? 64 : 32;
2271 unsigned MinLMUL = ELEN / 8;
2272 if (Lmul > MinLMUL)
2273 Warning(L: Tok.getLoc(),
2274 Msg: "use of vtype encodings with LMUL < SEWMIN/ELEN == mf" +
2275 Twine(MinLMUL) + " is reserved");
2276 }
2277
2278 State = VTypeState::SeenLmul;
2279 return false;
2280 }
2281
2282 if (State < VTypeState::SeenTailPolicy && Identifier.starts_with(Prefix: "t")) {
2283 if (Identifier == "ta")
2284 TailAgnostic = true;
2285 else if (Identifier == "tu")
2286 TailAgnostic = false;
2287 else
2288 return true;
2289
2290 State = VTypeState::SeenTailPolicy;
2291 return false;
2292 }
2293
2294 if (State < VTypeState::SeenMaskPolicy && Identifier.starts_with(Prefix: "m")) {
2295 if (Identifier == "ma")
2296 MaskAgnostic = true;
2297 else if (Identifier == "mu")
2298 MaskAgnostic = false;
2299 else
2300 return true;
2301
2302 State = VTypeState::SeenMaskPolicy;
2303 return false;
2304 }
2305
2306 return true;
2307}
2308
2309ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2310 SMLoc S = getLoc();
2311
2312 // Default values
2313 unsigned Sew = 8;
2314 unsigned Lmul = 1;
2315 bool Fractional = false;
2316 bool TailAgnostic = false;
2317 bool MaskAgnostic = false;
2318
2319 VTypeState State = VTypeState::SeenNothingYet;
2320 do {
2321 if (parseVTypeToken(Tok: getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2322 MaskAgnostic)) {
2323 // The first time, errors return NoMatch rather than Failure
2324 if (State == VTypeState::SeenNothingYet)
2325 return ParseStatus::NoMatch;
2326 break;
2327 }
2328
2329 getLexer().Lex();
2330 } while (parseOptionalToken(T: AsmToken::Comma));
2331
2332 if (!getLexer().is(K: AsmToken::EndOfStatement) ||
2333 State == VTypeState::SeenNothingYet)
2334 return generateVTypeError(ErrorLoc: S);
2335
2336 RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(LMUL: Lmul, Fractional);
2337 if (Fractional) {
2338 unsigned ELEN = STI->hasFeature(Feature: RISCV::FeatureStdExtZve64x) ? 64 : 32;
2339 unsigned MaxSEW = ELEN / Lmul;
2340 // If MaxSEW < 8, we should have printed warning about reserved LMUL.
2341 if (MaxSEW >= 8 && Sew > MaxSEW)
2342 Warning(L: S, Msg: "use of vtype encodings with SEW > " + Twine(MaxSEW) +
2343 " and LMUL == mf" + Twine(Lmul) +
2344 " may not be compatible with all RVV implementations");
2345 }
2346
2347 unsigned VTypeI =
2348 RISCVVType::encodeVTYPE(VLMUL, SEW: Sew, TailAgnostic, MaskAgnostic);
2349 Operands.push_back(Elt: RISCVOperand::createVType(VTypeI, S));
2350 return ParseStatus::Success;
2351}
2352
2353bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2354 return Error(
2355 L: ErrorLoc,
2356 Msg: "operand must be "
2357 "e[8|16|32|64],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2358}
2359
2360ParseStatus RISCVAsmParser::parseXSfmmVType(OperandVector &Operands) {
2361 SMLoc S = getLoc();
2362
2363 unsigned Widen = 0;
2364 unsigned SEW = 0;
2365 bool AltFmt = false;
2366 StringRef Identifier;
2367
2368 if (getTok().isNot(K: AsmToken::Identifier))
2369 goto Fail;
2370
2371 Identifier = getTok().getIdentifier();
2372
2373 if (!Identifier.consume_front(Prefix: "e"))
2374 goto Fail;
2375
2376 if (Identifier.getAsInteger(Radix: 10, Result&: SEW)) {
2377 if (Identifier != "16alt")
2378 goto Fail;
2379
2380 AltFmt = true;
2381 SEW = 16;
2382 }
2383 if (!RISCVVType::isValidSEW(SEW))
2384 goto Fail;
2385
2386 Lex();
2387
2388 if (!parseOptionalToken(T: AsmToken::Comma))
2389 goto Fail;
2390
2391 if (getTok().isNot(K: AsmToken::Identifier))
2392 goto Fail;
2393
2394 Identifier = getTok().getIdentifier();
2395
2396 if (!Identifier.consume_front(Prefix: "w"))
2397 goto Fail;
2398 if (Identifier.getAsInteger(Radix: 10, Result&: Widen))
2399 goto Fail;
2400 if (Widen != 1 && Widen != 2 && Widen != 4)
2401 goto Fail;
2402
2403 Lex();
2404
2405 if (getLexer().is(K: AsmToken::EndOfStatement)) {
2406 Operands.push_back(Elt: RISCVOperand::createVType(
2407 VTypeI: RISCVVType::encodeXSfmmVType(SEW, Widen, AltFmt), S));
2408 return ParseStatus::Success;
2409 }
2410
2411Fail:
2412 return generateXSfmmVTypeError(ErrorLoc: S);
2413}
2414
2415bool RISCVAsmParser::generateXSfmmVTypeError(SMLoc ErrorLoc) {
2416 return Error(L: ErrorLoc, Msg: "operand must be e[8|16|16alt|32|64],w[1|2|4]");
2417}
2418
2419ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2420 if (getLexer().isNot(K: AsmToken::Identifier))
2421 return ParseStatus::NoMatch;
2422
2423 StringRef Name = getLexer().getTok().getIdentifier();
2424 if (!Name.consume_back(Suffix: ".t"))
2425 return Error(L: getLoc(), Msg: "expected '.t' suffix");
2426 MCRegister Reg = matchRegisterNameHelper(Name);
2427
2428 if (!Reg)
2429 return ParseStatus::NoMatch;
2430 if (Reg != RISCV::V0)
2431 return ParseStatus::NoMatch;
2432 SMLoc S = getLoc();
2433 SMLoc E = getTok().getEndLoc();
2434 getLexer().Lex();
2435 Operands.push_back(Elt: RISCVOperand::createReg(Reg, S, E));
2436 return ParseStatus::Success;
2437}
2438
2439ParseStatus RISCVAsmParser::parseGPRAsFPR64(OperandVector &Operands) {
2440 if (!isRV64() || getSTI().hasFeature(Feature: RISCV::FeatureStdExtF))
2441 return ParseStatus::NoMatch;
2442
2443 return parseGPRAsFPR(Operands);
2444}
2445
2446ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
2447 if (getLexer().isNot(K: AsmToken::Identifier))
2448 return ParseStatus::NoMatch;
2449
2450 StringRef Name = getLexer().getTok().getIdentifier();
2451 MCRegister Reg = matchRegisterNameHelper(Name);
2452
2453 if (!Reg)
2454 return ParseStatus::NoMatch;
2455 SMLoc S = getLoc();
2456 SMLoc E = getTok().getEndLoc();
2457 getLexer().Lex();
2458 Operands.push_back(Elt: RISCVOperand::createReg(
2459 Reg, S, E, IsGPRAsFPR: !getSTI().hasFeature(Feature: RISCV::FeatureStdExtF)));
2460 return ParseStatus::Success;
2461}
2462
2463ParseStatus RISCVAsmParser::parseGPRPairAsFPR64(OperandVector &Operands) {
2464 if (isRV64() || getSTI().hasFeature(Feature: RISCV::FeatureStdExtF))
2465 return ParseStatus::NoMatch;
2466
2467 if (getLexer().isNot(K: AsmToken::Identifier))
2468 return ParseStatus::NoMatch;
2469
2470 StringRef Name = getLexer().getTok().getIdentifier();
2471 MCRegister Reg = matchRegisterNameHelper(Name);
2472
2473 if (!Reg)
2474 return ParseStatus::NoMatch;
2475
2476 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg))
2477 return ParseStatus::NoMatch;
2478
2479 if ((Reg - RISCV::X0) & 1) {
2480 // Only report the even register error if we have at least Zfinx so we know
2481 // some FP is enabled. We already checked F earlier.
2482 if (getSTI().hasFeature(Feature: RISCV::FeatureStdExtZfinx))
2483 return TokError(Msg: "double precision floating point operands must use even "
2484 "numbered X register");
2485 return ParseStatus::NoMatch;
2486 }
2487
2488 SMLoc S = getLoc();
2489 SMLoc E = getTok().getEndLoc();
2490 getLexer().Lex();
2491
2492 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2493 MCRegister Pair = RI->getMatchingSuperReg(
2494 Reg, SubIdx: RISCV::sub_gpr_even,
2495 RC: &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2496 Operands.push_back(Elt: RISCVOperand::createReg(Reg: Pair, S, E, /*isGPRAsFPR=*/IsGPRAsFPR: true));
2497 return ParseStatus::Success;
2498}
2499
2500template <bool IsRV64>
2501ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
2502 return parseGPRPair(Operands, IsRV64Inst: IsRV64);
2503}
2504
2505ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
2506 bool IsRV64Inst) {
2507 // If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
2508 // RV64 as it will prevent matching the RV64 version of the same instruction
2509 // that doesn't use a GPRPair.
2510 // If this is an RV64 GPRPair instruction, there is no RV32 version so we can
2511 // still parse as a pair.
2512 if (!IsRV64Inst && isRV64())
2513 return ParseStatus::NoMatch;
2514
2515 if (getLexer().isNot(K: AsmToken::Identifier))
2516 return ParseStatus::NoMatch;
2517
2518 StringRef Name = getLexer().getTok().getIdentifier();
2519 MCRegister Reg = matchRegisterNameHelper(Name);
2520
2521 if (!Reg)
2522 return ParseStatus::NoMatch;
2523
2524 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg))
2525 return ParseStatus::NoMatch;
2526
2527 if ((Reg - RISCV::X0) & 1)
2528 return TokError(Msg: "register must be even");
2529
2530 SMLoc S = getLoc();
2531 SMLoc E = getTok().getEndLoc();
2532 getLexer().Lex();
2533
2534 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2535 MCRegister Pair = RI->getMatchingSuperReg(
2536 Reg, SubIdx: RISCV::sub_gpr_even,
2537 RC: &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2538 Operands.push_back(Elt: RISCVOperand::createReg(Reg: Pair, S, E));
2539 return ParseStatus::Success;
2540}
2541
2542ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2543 if (getLexer().isNot(K: AsmToken::Identifier))
2544 return TokError(
2545 Msg: "operand must be a valid floating point rounding mode mnemonic");
2546
2547 StringRef Str = getLexer().getTok().getIdentifier();
2548 RISCVFPRndMode::RoundingMode FRM = RISCVFPRndMode::stringToRoundingMode(Str);
2549
2550 if (FRM == RISCVFPRndMode::Invalid)
2551 return TokError(
2552 Msg: "operand must be a valid floating point rounding mode mnemonic");
2553
2554 Operands.push_back(Elt: RISCVOperand::createFRMArg(FRM, S: getLoc()));
2555 Lex(); // Eat identifier token.
2556 return ParseStatus::Success;
2557}
2558
2559ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2560 const AsmToken &Tok = getLexer().getTok();
2561
2562 if (Tok.is(K: AsmToken::Integer)) {
2563 if (Tok.getIntVal() != 0)
2564 goto ParseFail;
2565
2566 Operands.push_back(Elt: RISCVOperand::createFenceArg(Val: 0, S: getLoc()));
2567 Lex();
2568 return ParseStatus::Success;
2569 }
2570
2571 if (Tok.is(K: AsmToken::Identifier)) {
2572 StringRef Str = Tok.getIdentifier();
2573
2574 // Letters must be unique, taken from 'iorw', and in ascending order. This
2575 // holds as long as each individual character is one of 'iorw' and is
2576 // greater than the previous character.
2577 unsigned Imm = 0;
2578 bool Valid = true;
2579 char Prev = '\0';
2580 for (char c : Str) {
2581 switch (c) {
2582 default:
2583 Valid = false;
2584 break;
2585 case 'i':
2586 Imm |= RISCVFenceField::I;
2587 break;
2588 case 'o':
2589 Imm |= RISCVFenceField::O;
2590 break;
2591 case 'r':
2592 Imm |= RISCVFenceField::R;
2593 break;
2594 case 'w':
2595 Imm |= RISCVFenceField::W;
2596 break;
2597 }
2598
2599 if (c <= Prev) {
2600 Valid = false;
2601 break;
2602 }
2603 Prev = c;
2604 }
2605
2606 if (!Valid)
2607 goto ParseFail;
2608
2609 Operands.push_back(Elt: RISCVOperand::createFenceArg(Val: Imm, S: getLoc()));
2610 Lex();
2611 return ParseStatus::Success;
2612 }
2613
2614ParseFail:
2615 return TokError(Msg: "operand must be formed of letters selected in-order from "
2616 "'iorw' or be 0");
2617}
2618
2619ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2620 if (parseToken(T: AsmToken::LParen, Msg: "expected '('"))
2621 return ParseStatus::Failure;
2622 Operands.push_back(Elt: RISCVOperand::createToken(Str: "(", S: getLoc()));
2623
2624 if (!parseRegister(Operands).isSuccess())
2625 return Error(L: getLoc(), Msg: "expected register");
2626
2627 if (parseToken(T: AsmToken::RParen, Msg: "expected ')'"))
2628 return ParseStatus::Failure;
2629 Operands.push_back(Elt: RISCVOperand::createToken(Str: ")", S: getLoc()));
2630
2631 return ParseStatus::Success;
2632}
2633
2634ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2635 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2636 // as one of their register operands, such as `(a0)`. This just denotes that
2637 // the register (in this case `a0`) contains a memory address.
2638 //
2639 // Normally, we would be able to parse these by putting the parens into the
2640 // instruction string. However, GNU as also accepts a zero-offset memory
2641 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2642 // with parseImmediate followed by parseMemOpBaseReg, but these instructions
2643 // do not accept an immediate operand, and we do not want to add a "dummy"
2644 // operand that is silently dropped.
2645 //
2646 // Instead, we use this custom parser. This will: allow (and discard) an
2647 // offset if it is zero; require (and discard) parentheses; and add only the
2648 // parsed register operand to `Operands`.
2649 //
2650 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2651 // which will only print the register surrounded by parentheses (which GNU as
2652 // also uses as its canonical representation for these operands).
2653 std::unique_ptr<RISCVOperand> OptionalImmOp;
2654
2655 if (getLexer().isNot(K: AsmToken::LParen)) {
2656 // Parse an Integer token. We do not accept arbitrary constant expressions
2657 // in the offset field (because they may include parens, which complicates
2658 // parsing a lot).
2659 int64_t ImmVal;
2660 SMLoc ImmStart = getLoc();
2661 if (getParser().parseIntToken(V&: ImmVal,
2662 ErrMsg: "expected '(' or optional integer offset"))
2663 return ParseStatus::Failure;
2664
2665 // Create a RISCVOperand for checking later (so the error messages are
2666 // nicer), but we don't add it to Operands.
2667 SMLoc ImmEnd = getLoc();
2668 OptionalImmOp =
2669 RISCVOperand::createImm(Val: MCConstantExpr::create(Value: ImmVal, Ctx&: getContext()),
2670 S: ImmStart, E: ImmEnd, IsRV64: isRV64());
2671 }
2672
2673 if (parseToken(T: AsmToken::LParen,
2674 Msg: OptionalImmOp ? "expected '(' after optional integer offset"
2675 : "expected '(' or optional integer offset"))
2676 return ParseStatus::Failure;
2677
2678 if (!parseRegister(Operands).isSuccess())
2679 return Error(L: getLoc(), Msg: "expected register");
2680
2681 if (parseToken(T: AsmToken::RParen, Msg: "expected ')'"))
2682 return ParseStatus::Failure;
2683
2684 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2685 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2686 return Error(
2687 L: OptionalImmOp->getStartLoc(), Msg: "optional integer offset must be 0",
2688 Range: SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2689
2690 return ParseStatus::Success;
2691}
2692
2693ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2694 // RR : a2(a1)
2695 if (getLexer().getKind() != AsmToken::Identifier)
2696 return ParseStatus::NoMatch;
2697
2698 SMLoc S = getLoc();
2699 StringRef OffsetRegName = getLexer().getTok().getIdentifier();
2700 MCRegister OffsetReg = matchRegisterNameHelper(Name: OffsetRegName);
2701 if (!OffsetReg ||
2702 !RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg: OffsetReg))
2703 return Error(L: getLoc(), Msg: "expected GPR register");
2704 getLexer().Lex();
2705
2706 if (parseToken(T: AsmToken::LParen, Msg: "expected '(' or invalid operand"))
2707 return ParseStatus::Failure;
2708
2709 if (getLexer().getKind() != AsmToken::Identifier)
2710 return Error(L: getLoc(), Msg: "expected GPR register");
2711
2712 StringRef BaseRegName = getLexer().getTok().getIdentifier();
2713 MCRegister BaseReg = matchRegisterNameHelper(Name: BaseRegName);
2714 if (!BaseReg ||
2715 !RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg: BaseReg))
2716 return Error(L: getLoc(), Msg: "expected GPR register");
2717 getLexer().Lex();
2718
2719 if (parseToken(T: AsmToken::RParen, Msg: "expected ')'"))
2720 return ParseStatus::Failure;
2721
2722 Operands.push_back(Elt: RISCVOperand::createRegReg(BaseReg, OffsetReg, S));
2723
2724 return ParseStatus::Success;
2725}
2726
2727// RegList: {ra [, s0[-sN]]}
2728// XRegList: {x1 [, x8[-x9][, x18[-xN]]]}
2729
2730// When MustIncludeS0 = true (not the default) (used for `qc.cm.pushfp`) which
2731// must include `fp`/`s0` in the list:
2732// RegList: {ra, s0[-sN]}
2733// XRegList: {x1, x8[-x9][, x18[-xN]]}
2734ParseStatus RISCVAsmParser::parseRegList(OperandVector &Operands,
2735 bool MustIncludeS0) {
2736 if (getTok().isNot(K: AsmToken::LCurly))
2737 return ParseStatus::NoMatch;
2738
2739 SMLoc S = getLoc();
2740
2741 Lex();
2742
2743 bool UsesXRegs;
2744 MCRegister RegEnd;
2745 do {
2746 if (getTok().isNot(K: AsmToken::Identifier))
2747 return Error(L: getLoc(), Msg: "invalid register");
2748
2749 StringRef RegName = getTok().getIdentifier();
2750 MCRegister Reg = matchRegisterNameHelper(Name: RegName);
2751 if (!Reg)
2752 return Error(L: getLoc(), Msg: "invalid register");
2753
2754 if (!RegEnd) {
2755 UsesXRegs = RegName[0] == 'x';
2756 if (Reg != RISCV::X1)
2757 return Error(L: getLoc(), Msg: "register list must start from 'ra' or 'x1'");
2758 } else if (RegEnd == RISCV::X1) {
2759 if (Reg != RISCV::X8 || (UsesXRegs != (RegName[0] == 'x')))
2760 return Error(L: getLoc(), Msg: Twine("register must be '") +
2761 (UsesXRegs ? "x8" : "s0") + "'");
2762 } else if (RegEnd == RISCV::X9 && UsesXRegs) {
2763 if (Reg != RISCV::X18 || (RegName[0] != 'x'))
2764 return Error(L: getLoc(), Msg: "register must be 'x18'");
2765 } else {
2766 return Error(L: getLoc(), Msg: "too many register ranges");
2767 }
2768
2769 RegEnd = Reg;
2770
2771 Lex();
2772
2773 SMLoc MinusLoc = getLoc();
2774 if (parseOptionalToken(T: AsmToken::Minus)) {
2775 if (RegEnd == RISCV::X1)
2776 return Error(L: MinusLoc, Msg: Twine("register '") + (UsesXRegs ? "x1" : "ra") +
2777 "' cannot start a multiple register range");
2778
2779 if (getTok().isNot(K: AsmToken::Identifier))
2780 return Error(L: getLoc(), Msg: "invalid register");
2781
2782 StringRef RegName = getTok().getIdentifier();
2783 MCRegister Reg = matchRegisterNameHelper(Name: RegName);
2784 if (!Reg)
2785 return Error(L: getLoc(), Msg: "invalid register");
2786
2787 if (RegEnd == RISCV::X8) {
2788 if ((Reg != RISCV::X9 &&
2789 (UsesXRegs || Reg < RISCV::X18 || Reg > RISCV::X27)) ||
2790 (UsesXRegs != (RegName[0] == 'x'))) {
2791 if (UsesXRegs)
2792 return Error(L: getLoc(), Msg: "register must be 'x9'");
2793 return Error(L: getLoc(), Msg: "register must be in the range 's1' to 's11'");
2794 }
2795 } else if (RegEnd == RISCV::X18) {
2796 if (Reg < RISCV::X19 || Reg > RISCV::X27 || (RegName[0] != 'x'))
2797 return Error(L: getLoc(),
2798 Msg: "register must be in the range 'x19' to 'x27'");
2799 } else
2800 llvm_unreachable("unexpected register");
2801
2802 RegEnd = Reg;
2803
2804 Lex();
2805 }
2806 } while (parseOptionalToken(T: AsmToken::Comma));
2807
2808 if (parseToken(T: AsmToken::RCurly, Msg: "expected ',' or '}'"))
2809 return ParseStatus::Failure;
2810
2811 if (RegEnd == RISCV::X26)
2812 return Error(L: S, Msg: "invalid register list, '{ra, s0-s10}' or '{x1, x8-x9, "
2813 "x18-x26}' is not supported");
2814
2815 auto Encode = RISCVZC::encodeRegList(EndReg: RegEnd, IsRVE: isRVE());
2816 assert(Encode != RISCVZC::INVALID_RLIST);
2817
2818 if (MustIncludeS0 && Encode == RISCVZC::RA)
2819 return Error(L: S, Msg: "register list must include 's0' or 'x8'");
2820
2821 Operands.push_back(Elt: RISCVOperand::createRegList(RlistEncode: Encode, S));
2822
2823 return ParseStatus::Success;
2824}
2825
2826ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
2827 bool ExpectNegative) {
2828 SMLoc S = getLoc();
2829 bool Negative = parseOptionalToken(T: AsmToken::Minus);
2830
2831 if (getTok().isNot(K: AsmToken::Integer))
2832 return ParseStatus::NoMatch;
2833
2834 int64_t StackAdjustment = getTok().getIntVal();
2835
2836 auto *RegListOp = static_cast<RISCVOperand *>(Operands.back().get());
2837 if (!RegListOp->isRegList())
2838 return ParseStatus::NoMatch;
2839
2840 unsigned RlistEncode = RegListOp->RegList.Encoding;
2841
2842 assert(RlistEncode != RISCVZC::INVALID_RLIST);
2843 unsigned StackAdjBase = RISCVZC::getStackAdjBase(RlistVal: RlistEncode, IsRV64: isRV64());
2844 if (Negative != ExpectNegative || StackAdjustment % 16 != 0 ||
2845 StackAdjustment < StackAdjBase || (StackAdjustment - StackAdjBase) > 48) {
2846 int64_t Lower = StackAdjBase;
2847 int64_t Upper = StackAdjBase + 48;
2848 if (ExpectNegative) {
2849 Lower = -Lower;
2850 Upper = -Upper;
2851 std::swap(a&: Lower, b&: Upper);
2852 }
2853 return generateImmOutOfRangeError(ErrorLoc: S, Lower, Upper,
2854 Msg: "stack adjustment for register list must "
2855 "be a multiple of 16 bytes in the range");
2856 }
2857
2858 unsigned StackAdj = (StackAdjustment - StackAdjBase);
2859 Operands.push_back(Elt: RISCVOperand::createStackAdj(StackAdj, S));
2860 Lex();
2861 return ParseStatus::Success;
2862}
2863
2864/// Looks at a token type and creates the relevant operand from this
2865/// information, adding to Operands. If operand was parsed, returns false, else
2866/// true.
2867bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2868 // Check if the current operand has a custom associated parser, if so, try to
2869 // custom parse the operand, or fallback to the general approach.
2870 ParseStatus Result =
2871 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
2872 if (Result.isSuccess())
2873 return false;
2874 if (Result.isFailure())
2875 return true;
2876
2877 // Attempt to parse token as a register.
2878 if (parseRegister(Operands, AllowParens: true).isSuccess())
2879 return false;
2880
2881 // Attempt to parse token as an immediate
2882 if (parseImmediate(Operands).isSuccess()) {
2883 // Parse memory base register if present
2884 if (getLexer().is(K: AsmToken::LParen))
2885 return !parseMemOpBaseReg(Operands).isSuccess();
2886 return false;
2887 }
2888
2889 // Finally we have exhausted all options and must declare defeat.
2890 Error(L: getLoc(), Msg: "unknown operand");
2891 return true;
2892}
2893
2894bool RISCVAsmParser::parseInstruction(ParseInstructionInfo &Info,
2895 StringRef Name, SMLoc NameLoc,
2896 OperandVector &Operands) {
2897 // Apply mnemonic aliases because the destination mnemonic may have require
2898 // custom operand parsing. The generic tblgen'erated code does this later, at
2899 // the start of MatchInstructionImpl(), but that's too late for custom
2900 // operand parsing.
2901 const FeatureBitset &AvailableFeatures = getAvailableFeatures();
2902 applyMnemonicAliases(Mnemonic&: Name, Features: AvailableFeatures, VariantID: 0);
2903
2904 // First operand is token for instruction
2905 Operands.push_back(Elt: RISCVOperand::createToken(Str: Name, S: NameLoc));
2906
2907 // If there are no more operands, then finish
2908 if (getLexer().is(K: AsmToken::EndOfStatement)) {
2909 getParser().Lex(); // Consume the EndOfStatement.
2910 return false;
2911 }
2912
2913 // Parse first operand
2914 if (parseOperand(Operands, Mnemonic: Name))
2915 return true;
2916
2917 // Parse until end of statement, consuming commas between operands
2918 while (parseOptionalToken(T: AsmToken::Comma)) {
2919 // Parse next operand
2920 if (parseOperand(Operands, Mnemonic: Name))
2921 return true;
2922 }
2923
2924 if (getParser().parseEOL(ErrMsg: "unexpected token")) {
2925 getParser().eatToEndOfStatement();
2926 return true;
2927 }
2928 return false;
2929}
2930
2931bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2932 RISCV::Specifier &Kind) {
2933 Kind = RISCV::S_None;
2934 if (const auto *RE = dyn_cast<MCSpecifierExpr>(Val: Expr)) {
2935 Kind = RE->getSpecifier();
2936 Expr = RE->getSubExpr();
2937 }
2938
2939 MCValue Res;
2940 if (Expr->evaluateAsRelocatable(Res, Asm: nullptr))
2941 return Res.getSpecifier() == RISCV::S_None;
2942 return false;
2943}
2944
2945bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
2946 MCValue Res;
2947 if (Expr->evaluateAsRelocatable(Res, Asm: nullptr)) {
2948 return Res.getSpecifier() == RISCV::S_None && Res.getAddSym() &&
2949 Res.getSubSym();
2950 }
2951 return false;
2952}
2953
2954ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
2955 StringRef IDVal = DirectiveID.getString();
2956
2957 if (IDVal == ".option")
2958 return parseDirectiveOption();
2959 if (IDVal == ".attribute")
2960 return parseDirectiveAttribute();
2961 if (IDVal == ".insn")
2962 return parseDirectiveInsn(L: DirectiveID.getLoc());
2963 if (IDVal == ".variant_cc")
2964 return parseDirectiveVariantCC();
2965
2966 return ParseStatus::NoMatch;
2967}
2968
2969bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
2970 bool FromOptionDirective) {
2971 for (auto &Feature : RISCVFeatureKV)
2972 if (llvm::RISCVISAInfo::isSupportedExtensionFeature(Ext: Feature.Key))
2973 clearFeatureBits(Feature: Feature.Value, FeatureString: Feature.Key);
2974
2975 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
2976 Arch, /*EnableExperimentalExtension=*/true,
2977 /*ExperimentalExtensionVersionCheck=*/true);
2978 if (!ParseResult) {
2979 std::string Buffer;
2980 raw_string_ostream OutputErrMsg(Buffer);
2981 handleAllErrors(E: ParseResult.takeError(), Handlers: [&](llvm::StringError &ErrMsg) {
2982 OutputErrMsg << "invalid arch name '" << Arch << "', "
2983 << ErrMsg.getMessage();
2984 });
2985
2986 return Error(L: Loc, Msg: OutputErrMsg.str());
2987 }
2988 auto &ISAInfo = *ParseResult;
2989
2990 for (auto &Feature : RISCVFeatureKV)
2991 if (ISAInfo->hasExtension(Ext: Feature.Key))
2992 setFeatureBits(Feature: Feature.Value, FeatureString: Feature.Key);
2993
2994 if (FromOptionDirective) {
2995 if (ISAInfo->getXLen() == 32 && isRV64())
2996 return Error(L: Loc, Msg: "bad arch string switching from rv64 to rv32");
2997 else if (ISAInfo->getXLen() == 64 && !isRV64())
2998 return Error(L: Loc, Msg: "bad arch string switching from rv32 to rv64");
2999 }
3000
3001 if (ISAInfo->getXLen() == 32)
3002 clearFeatureBits(Feature: RISCV::Feature64Bit, FeatureString: "64bit");
3003 else if (ISAInfo->getXLen() == 64)
3004 setFeatureBits(Feature: RISCV::Feature64Bit, FeatureString: "64bit");
3005 else
3006 return Error(L: Loc, Msg: "bad arch string " + Arch);
3007
3008 Result = ISAInfo->toString();
3009 return false;
3010}
3011
3012bool RISCVAsmParser::parseDirectiveOption() {
3013 MCAsmParser &Parser = getParser();
3014 // Get the option token.
3015 AsmToken Tok = Parser.getTok();
3016
3017 // At the moment only identifiers are supported.
3018 if (parseToken(T: AsmToken::Identifier, Msg: "expected identifier"))
3019 return true;
3020
3021 StringRef Option = Tok.getIdentifier();
3022
3023 if (Option == "push") {
3024 if (Parser.parseEOL())
3025 return true;
3026
3027 getTargetStreamer().emitDirectiveOptionPush();
3028 pushFeatureBits();
3029 return false;
3030 }
3031
3032 if (Option == "pop") {
3033 SMLoc StartLoc = Parser.getTok().getLoc();
3034 if (Parser.parseEOL())
3035 return true;
3036
3037 getTargetStreamer().emitDirectiveOptionPop();
3038 if (popFeatureBits())
3039 return Error(L: StartLoc, Msg: ".option pop with no .option push");
3040
3041 return false;
3042 }
3043
3044 if (Option == "arch") {
3045 SmallVector<RISCVOptionArchArg> Args;
3046 do {
3047 if (Parser.parseComma())
3048 return true;
3049
3050 RISCVOptionArchArgType Type;
3051 if (parseOptionalToken(T: AsmToken::Plus))
3052 Type = RISCVOptionArchArgType::Plus;
3053 else if (parseOptionalToken(T: AsmToken::Minus))
3054 Type = RISCVOptionArchArgType::Minus;
3055 else if (!Args.empty())
3056 return Error(L: Parser.getTok().getLoc(),
3057 Msg: "unexpected token, expected + or -");
3058 else
3059 Type = RISCVOptionArchArgType::Full;
3060
3061 if (Parser.getTok().isNot(K: AsmToken::Identifier))
3062 return Error(L: Parser.getTok().getLoc(),
3063 Msg: "unexpected token, expected identifier");
3064
3065 StringRef Arch = Parser.getTok().getString();
3066 SMLoc Loc = Parser.getTok().getLoc();
3067 Parser.Lex();
3068
3069 if (Type == RISCVOptionArchArgType::Full) {
3070 std::string Result;
3071 if (resetToArch(Arch, Loc, Result, FromOptionDirective: true))
3072 return true;
3073
3074 Args.emplace_back(Args&: Type, Args&: Result);
3075 break;
3076 }
3077
3078 if (isDigit(C: Arch.back()))
3079 return Error(
3080 L: Loc, Msg: "extension version number parsing not currently implemented");
3081
3082 std::string Feature = RISCVISAInfo::getTargetFeatureForExtension(Ext: Arch);
3083 if (!enableExperimentalExtension() &&
3084 StringRef(Feature).starts_with(Prefix: "experimental-"))
3085 return Error(L: Loc, Msg: "unexpected experimental extensions");
3086 auto Ext = llvm::lower_bound(Range: RISCVFeatureKV, Value&: Feature);
3087 if (Ext == std::end(arr: RISCVFeatureKV) || StringRef(Ext->Key) != Feature)
3088 return Error(L: Loc, Msg: "unknown extension feature");
3089
3090 Args.emplace_back(Args&: Type, Args: Arch.str());
3091
3092 if (Type == RISCVOptionArchArgType::Plus) {
3093 FeatureBitset OldFeatureBits = STI->getFeatureBits();
3094
3095 setFeatureBits(Feature: Ext->Value, FeatureString: Ext->Key);
3096 auto ParseResult = RISCVFeatures::parseFeatureBits(IsRV64: isRV64(), FeatureBits: STI->getFeatureBits());
3097 if (!ParseResult) {
3098 copySTI().setFeatureBits(OldFeatureBits);
3099 setAvailableFeatures(ComputeAvailableFeatures(FB: OldFeatureBits));
3100
3101 std::string Buffer;
3102 raw_string_ostream OutputErrMsg(Buffer);
3103 handleAllErrors(E: ParseResult.takeError(), Handlers: [&](llvm::StringError &ErrMsg) {
3104 OutputErrMsg << ErrMsg.getMessage();
3105 });
3106
3107 return Error(L: Loc, Msg: OutputErrMsg.str());
3108 }
3109 } else {
3110 assert(Type == RISCVOptionArchArgType::Minus);
3111 // It is invalid to disable an extension that there are other enabled
3112 // extensions depend on it.
3113 // TODO: Make use of RISCVISAInfo to handle this
3114 for (auto &Feature : RISCVFeatureKV) {
3115 if (getSTI().hasFeature(Feature: Feature.Value) &&
3116 Feature.Implies.test(I: Ext->Value))
3117 return Error(L: Loc, Msg: Twine("can't disable ") + Ext->Key +
3118 " extension; " + Feature.Key +
3119 " extension requires " + Ext->Key +
3120 " extension");
3121 }
3122
3123 clearFeatureBits(Feature: Ext->Value, FeatureString: Ext->Key);
3124 }
3125 } while (Parser.getTok().isNot(K: AsmToken::EndOfStatement));
3126
3127 if (Parser.parseEOL())
3128 return true;
3129
3130 getTargetStreamer().emitDirectiveOptionArch(Args);
3131 return false;
3132 }
3133
3134 if (Option == "exact") {
3135 if (Parser.parseEOL())
3136 return true;
3137
3138 getTargetStreamer().emitDirectiveOptionExact();
3139 setFeatureBits(Feature: RISCV::FeatureExactAssembly, FeatureString: "exact-asm");
3140 clearFeatureBits(Feature: RISCV::FeatureRelax, FeatureString: "relax");
3141 return false;
3142 }
3143
3144 if (Option == "noexact") {
3145 if (Parser.parseEOL())
3146 return true;
3147
3148 getTargetStreamer().emitDirectiveOptionNoExact();
3149 clearFeatureBits(Feature: RISCV::FeatureExactAssembly, FeatureString: "exact-asm");
3150 setFeatureBits(Feature: RISCV::FeatureRelax, FeatureString: "relax");
3151 return false;
3152 }
3153
3154 if (Option == "rvc") {
3155 if (Parser.parseEOL())
3156 return true;
3157
3158 getTargetStreamer().emitDirectiveOptionRVC();
3159 setFeatureBits(Feature: RISCV::FeatureStdExtC, FeatureString: "c");
3160 return false;
3161 }
3162
3163 if (Option == "norvc") {
3164 if (Parser.parseEOL())
3165 return true;
3166
3167 getTargetStreamer().emitDirectiveOptionNoRVC();
3168 clearFeatureBits(Feature: RISCV::FeatureStdExtC, FeatureString: "c");
3169 clearFeatureBits(Feature: RISCV::FeatureStdExtZca, FeatureString: "zca");
3170 return false;
3171 }
3172
3173 if (Option == "pic") {
3174 if (Parser.parseEOL())
3175 return true;
3176
3177 getTargetStreamer().emitDirectiveOptionPIC();
3178 ParserOptions.IsPicEnabled = true;
3179 return false;
3180 }
3181
3182 if (Option == "nopic") {
3183 if (Parser.parseEOL())
3184 return true;
3185
3186 getTargetStreamer().emitDirectiveOptionNoPIC();
3187 ParserOptions.IsPicEnabled = false;
3188 return false;
3189 }
3190
3191 if (Option == "relax") {
3192 if (Parser.parseEOL())
3193 return true;
3194
3195 getTargetStreamer().emitDirectiveOptionRelax();
3196 setFeatureBits(Feature: RISCV::FeatureRelax, FeatureString: "relax");
3197 return false;
3198 }
3199
3200 if (Option == "norelax") {
3201 if (Parser.parseEOL())
3202 return true;
3203
3204 getTargetStreamer().emitDirectiveOptionNoRelax();
3205 clearFeatureBits(Feature: RISCV::FeatureRelax, FeatureString: "relax");
3206 return false;
3207 }
3208
3209 // Unknown option.
3210 Warning(L: Parser.getTok().getLoc(),
3211 Msg: "unknown option, expected 'push', 'pop', "
3212 "'rvc', 'norvc', 'arch', 'relax', 'norelax', "
3213 "'exact', or 'noexact'");
3214 Parser.eatToEndOfStatement();
3215 return false;
3216}
3217
3218/// parseDirectiveAttribute
3219/// ::= .attribute expression ',' ( expression | "string" )
3220/// ::= .attribute identifier ',' ( expression | "string" )
3221bool RISCVAsmParser::parseDirectiveAttribute() {
3222 MCAsmParser &Parser = getParser();
3223 int64_t Tag;
3224 SMLoc TagLoc;
3225 TagLoc = Parser.getTok().getLoc();
3226 if (Parser.getTok().is(K: AsmToken::Identifier)) {
3227 StringRef Name = Parser.getTok().getIdentifier();
3228 std::optional<unsigned> Ret =
3229 ELFAttrs::attrTypeFromString(tag: Name, tagNameMap: RISCVAttrs::getRISCVAttributeTags());
3230 if (!Ret)
3231 return Error(L: TagLoc, Msg: "attribute name not recognised: " + Name);
3232 Tag = *Ret;
3233 Parser.Lex();
3234 } else {
3235 const MCExpr *AttrExpr;
3236
3237 TagLoc = Parser.getTok().getLoc();
3238 if (Parser.parseExpression(Res&: AttrExpr))
3239 return true;
3240
3241 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Val: AttrExpr);
3242 if (check(P: !CE, Loc: TagLoc, Msg: "expected numeric constant"))
3243 return true;
3244
3245 Tag = CE->getValue();
3246 }
3247
3248 if (Parser.parseComma())
3249 return true;
3250
3251 StringRef StringValue;
3252 int64_t IntegerValue = 0;
3253 bool IsIntegerValue = true;
3254
3255 // RISC-V attributes have a string value if the tag number is odd
3256 // and an integer value if the tag number is even.
3257 if (Tag % 2)
3258 IsIntegerValue = false;
3259
3260 SMLoc ValueExprLoc = Parser.getTok().getLoc();
3261 if (IsIntegerValue) {
3262 const MCExpr *ValueExpr;
3263 if (Parser.parseExpression(Res&: ValueExpr))
3264 return true;
3265
3266 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Val: ValueExpr);
3267 if (!CE)
3268 return Error(L: ValueExprLoc, Msg: "expected numeric constant");
3269 IntegerValue = CE->getValue();
3270 } else {
3271 if (Parser.getTok().isNot(K: AsmToken::String))
3272 return Error(L: Parser.getTok().getLoc(), Msg: "expected string constant");
3273
3274 StringValue = Parser.getTok().getStringContents();
3275 Parser.Lex();
3276 }
3277
3278 if (Parser.parseEOL())
3279 return true;
3280
3281 if (IsIntegerValue)
3282 getTargetStreamer().emitAttribute(Attribute: Tag, Value: IntegerValue);
3283 else if (Tag != RISCVAttrs::ARCH)
3284 getTargetStreamer().emitTextAttribute(Attribute: Tag, String: StringValue);
3285 else {
3286 std::string Result;
3287 if (resetToArch(Arch: StringValue, Loc: ValueExprLoc, Result, FromOptionDirective: false))
3288 return true;
3289
3290 // Then emit the arch string.
3291 getTargetStreamer().emitTextAttribute(Attribute: Tag, String: Result);
3292 }
3293
3294 return false;
3295}
3296
3297bool isValidInsnFormat(StringRef Format, const MCSubtargetInfo &STI) {
3298 return StringSwitch<bool>(Format)
3299 .Cases(S0: "r", S1: "r4", S2: "i", S3: "b", S4: "sb", S5: "u", S6: "j", S7: "uj", S8: "s", Value: true)
3300 .Cases(S0: "cr", S1: "ci", S2: "ciw", S3: "css", S4: "cl", S5: "cs", S6: "ca", S7: "cb", S8: "cj",
3301 Value: STI.hasFeature(Feature: RISCV::FeatureStdExtZca))
3302 .Cases(S0: "qc.eai", S1: "qc.ei", S2: "qc.eb", S3: "qc.ej", S4: "qc.es",
3303 Value: !STI.hasFeature(Feature: RISCV::Feature64Bit))
3304 .Default(Value: false);
3305}
3306
3307/// parseDirectiveInsn
3308/// ::= .insn [ format encoding, (operands (, operands)*) ]
3309/// ::= .insn [ length, value ]
3310/// ::= .insn [ value ]
3311bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
3312 MCAsmParser &Parser = getParser();
3313
3314 // Expect instruction format as identifier.
3315 StringRef Format;
3316 SMLoc ErrorLoc = Parser.getTok().getLoc();
3317 if (Parser.parseIdentifier(Res&: Format)) {
3318 // Try parsing .insn [ length , ] value
3319 std::optional<int64_t> Length;
3320 int64_t Value = 0;
3321 if (Parser.parseAbsoluteExpression(Res&: Value))
3322 return true;
3323 if (Parser.parseOptionalToken(T: AsmToken::Comma)) {
3324 Length = Value;
3325 if (Parser.parseAbsoluteExpression(Res&: Value))
3326 return true;
3327
3328 if (*Length == 0 || (*Length % 2) != 0)
3329 return Error(L: ErrorLoc,
3330 Msg: "instruction lengths must be a non-zero multiple of two");
3331
3332 // TODO: Support Instructions > 64 bits.
3333 if (*Length > 8)
3334 return Error(L: ErrorLoc,
3335 Msg: "instruction lengths over 64 bits are not supported");
3336 }
3337
3338 // We only derive a length from the encoding for 16- and 32-bit
3339 // instructions, as the encodings for longer instructions are not frozen in
3340 // the spec.
3341 int64_t EncodingDerivedLength = ((Value & 0b11) == 0b11) ? 4 : 2;
3342
3343 if (Length) {
3344 // Only check the length against the encoding if the length is present and
3345 // could match
3346 if ((*Length <= 4) && (*Length != EncodingDerivedLength))
3347 return Error(L: ErrorLoc,
3348 Msg: "instruction length does not match the encoding");
3349
3350 if (!isUIntN(N: *Length * 8, x: Value))
3351 return Error(L: ErrorLoc, Msg: "encoding value does not fit into instruction");
3352 } else {
3353 if (!isUIntN(N: EncodingDerivedLength * 8, x: Value))
3354 return Error(L: ErrorLoc, Msg: "encoding value does not fit into instruction");
3355 }
3356
3357 if (!getSTI().hasFeature(Feature: RISCV::FeatureStdExtZca) &&
3358 (EncodingDerivedLength == 2))
3359 return Error(L: ErrorLoc, Msg: "compressed instructions are not allowed");
3360
3361 if (getParser().parseEOL(ErrMsg: "invalid operand for instruction")) {
3362 getParser().eatToEndOfStatement();
3363 return true;
3364 }
3365
3366 unsigned Opcode;
3367 if (Length) {
3368 switch (*Length) {
3369 case 2:
3370 Opcode = RISCV::Insn16;
3371 break;
3372 case 4:
3373 Opcode = RISCV::Insn32;
3374 break;
3375 case 6:
3376 Opcode = RISCV::Insn48;
3377 break;
3378 case 8:
3379 Opcode = RISCV::Insn64;
3380 break;
3381 default:
3382 llvm_unreachable("Error should have already been emitted");
3383 }
3384 } else
3385 Opcode = (EncodingDerivedLength == 2) ? RISCV::Insn16 : RISCV::Insn32;
3386
3387 emitToStreamer(S&: getStreamer(), Inst: MCInstBuilder(Opcode).addImm(Val: Value));
3388 return false;
3389 }
3390
3391 if (!isValidInsnFormat(Format, STI: getSTI()))
3392 return Error(L: ErrorLoc, Msg: "invalid instruction format");
3393
3394 std::string FormatName = (".insn_" + Format).str();
3395
3396 ParseInstructionInfo Info;
3397 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> Operands;
3398
3399 if (parseInstruction(Info, Name: FormatName, NameLoc: L, Operands))
3400 return true;
3401
3402 unsigned Opcode;
3403 uint64_t ErrorInfo;
3404 return matchAndEmitInstruction(IDLoc: L, Opcode, Operands, Out&: Parser.getStreamer(),
3405 ErrorInfo,
3406 /*MatchingInlineAsm=*/false);
3407}
3408
3409/// parseDirectiveVariantCC
3410/// ::= .variant_cc symbol
3411bool RISCVAsmParser::parseDirectiveVariantCC() {
3412 StringRef Name;
3413 if (getParser().parseIdentifier(Res&: Name))
3414 return TokError(Msg: "expected symbol name");
3415 if (parseEOL())
3416 return true;
3417 getTargetStreamer().emitDirectiveVariantCC(
3418 Symbol&: *getContext().getOrCreateSymbol(Name));
3419 return false;
3420}
3421
3422void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
3423 MCInst CInst;
3424 bool Res = false;
3425 const MCSubtargetInfo &STI = getSTI();
3426 if (!STI.hasFeature(Feature: RISCV::FeatureExactAssembly))
3427 Res = RISCVRVC::compress(OutInst&: CInst, MI: Inst, STI);
3428 if (Res)
3429 ++RISCVNumInstrsCompressed;
3430 S.emitInstruction(Inst: (Res ? CInst : Inst), STI);
3431}
3432
3433void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
3434 MCStreamer &Out) {
3435 SmallVector<MCInst, 8> Seq;
3436 RISCVMatInt::generateMCInstSeq(Val: Value, STI: getSTI(), DestReg, Insts&: Seq);
3437
3438 for (MCInst &Inst : Seq) {
3439 emitToStreamer(S&: Out, Inst);
3440 }
3441}
3442
3443void RISCVAsmParser::emitAuipcInstPair(MCRegister DestReg, MCRegister TmpReg,
3444 const MCExpr *Symbol,
3445 RISCV::Specifier VKHi,
3446 unsigned SecondOpcode, SMLoc IDLoc,
3447 MCStreamer &Out) {
3448 // A pair of instructions for PC-relative addressing; expands to
3449 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3450 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3451 MCContext &Ctx = getContext();
3452
3453 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol(Name: "pcrel_hi");
3454 Out.emitLabel(Symbol: TmpLabel);
3455
3456 const auto *SymbolHi = MCSpecifierExpr::create(Expr: Symbol, S: VKHi, Ctx);
3457 emitToStreamer(S&: Out,
3458 Inst: MCInstBuilder(RISCV::AUIPC).addReg(Reg: TmpReg).addExpr(Val: SymbolHi));
3459
3460 const MCExpr *RefToLinkTmpLabel = MCSpecifierExpr::create(
3461 Expr: MCSymbolRefExpr::create(Symbol: TmpLabel, Ctx), S: RISCV::S_PCREL_LO, Ctx);
3462
3463 emitToStreamer(S&: Out, Inst: MCInstBuilder(SecondOpcode)
3464 .addReg(Reg: DestReg)
3465 .addReg(Reg: TmpReg)
3466 .addExpr(Val: RefToLinkTmpLabel));
3467}
3468
3469void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3470 MCStreamer &Out) {
3471 // The load local address pseudo-instruction "lla" is used in PC-relative
3472 // addressing of local symbols:
3473 // lla rdest, symbol
3474 // expands to
3475 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3476 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3477 MCRegister DestReg = Inst.getOperand(i: 0).getReg();
3478 const MCExpr *Symbol = Inst.getOperand(i: 1).getExpr();
3479 emitAuipcInstPair(DestReg, TmpReg: DestReg, Symbol, VKHi: ELF::R_RISCV_PCREL_HI20,
3480 SecondOpcode: RISCV::ADDI, IDLoc, Out);
3481}
3482
3483void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3484 MCStreamer &Out) {
3485 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3486 // addressing of global symbols:
3487 // lga rdest, symbol
3488 // expands to
3489 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3490 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3491 MCRegister DestReg = Inst.getOperand(i: 0).getReg();
3492 const MCExpr *Symbol = Inst.getOperand(i: 1).getExpr();
3493 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3494 emitAuipcInstPair(DestReg, TmpReg: DestReg, Symbol, VKHi: ELF::R_RISCV_GOT_HI20,
3495 SecondOpcode, IDLoc, Out);
3496}
3497
3498void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3499 MCStreamer &Out) {
3500 // The load address pseudo-instruction "la" is used in PC-relative and
3501 // GOT-indirect addressing of global symbols:
3502 // la rdest, symbol
3503 // is an alias for either (for non-PIC)
3504 // lla rdest, symbol
3505 // or (for PIC)
3506 // lga rdest, symbol
3507 if (ParserOptions.IsPicEnabled)
3508 emitLoadGlobalAddress(Inst, IDLoc, Out);
3509 else
3510 emitLoadLocalAddress(Inst, IDLoc, Out);
3511}
3512
3513void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3514 MCStreamer &Out) {
3515 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3516 // initial-exec TLS model addressing of global symbols:
3517 // la.tls.ie rdest, symbol
3518 // expands to
3519 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3520 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3521 MCRegister DestReg = Inst.getOperand(i: 0).getReg();
3522 const MCExpr *Symbol = Inst.getOperand(i: 1).getExpr();
3523 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3524 emitAuipcInstPair(DestReg, TmpReg: DestReg, Symbol, VKHi: ELF::R_RISCV_TLS_GOT_HI20,
3525 SecondOpcode, IDLoc, Out);
3526}
3527
3528void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3529 MCStreamer &Out) {
3530 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3531 // global-dynamic TLS model addressing of global symbols:
3532 // la.tls.gd rdest, symbol
3533 // expands to
3534 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3535 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3536 MCRegister DestReg = Inst.getOperand(i: 0).getReg();
3537 const MCExpr *Symbol = Inst.getOperand(i: 1).getExpr();
3538 emitAuipcInstPair(DestReg, TmpReg: DestReg, Symbol, VKHi: ELF::R_RISCV_TLS_GD_HI20,
3539 SecondOpcode: RISCV::ADDI, IDLoc, Out);
3540}
3541
3542void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3543 SMLoc IDLoc, MCStreamer &Out,
3544 bool HasTmpReg) {
3545 // The load/store pseudo-instruction does a pc-relative load with
3546 // a symbol.
3547 //
3548 // The expansion looks like this
3549 //
3550 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3551 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3552 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3553 MCRegister DestReg = Inst.getOperand(i: DestRegOpIdx).getReg();
3554 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3555 MCRegister TmpReg = Inst.getOperand(i: 0).getReg();
3556
3557 // If TmpReg is a GPR pair, get the even register.
3558 if (RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(Reg: TmpReg)) {
3559 const MCRegisterInfo *RI = getContext().getRegisterInfo();
3560 TmpReg = RI->getSubReg(Reg: TmpReg, Idx: RISCV::sub_gpr_even);
3561 }
3562
3563 const MCExpr *Symbol = Inst.getOperand(i: SymbolOpIdx).getExpr();
3564 emitAuipcInstPair(DestReg, TmpReg, Symbol, VKHi: ELF::R_RISCV_PCREL_HI20, SecondOpcode: Opcode,
3565 IDLoc, Out);
3566}
3567
3568void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3569 int64_t Width, SMLoc IDLoc,
3570 MCStreamer &Out) {
3571 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3572 // amounts dependent on the XLEN.
3573 //
3574 // The expansion looks like this
3575 //
3576 // SLLI rd, rs, XLEN - Width
3577 // SR[A|R]I rd, rd, XLEN - Width
3578 const MCOperand &DestReg = Inst.getOperand(i: 0);
3579 const MCOperand &SourceReg = Inst.getOperand(i: 1);
3580
3581 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3582 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3583
3584 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3585
3586 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::SLLI)
3587 .addOperand(Op: DestReg)
3588 .addOperand(Op: SourceReg)
3589 .addImm(Val: ShAmt));
3590
3591 emitToStreamer(S&: Out, Inst: MCInstBuilder(SecondOpcode)
3592 .addOperand(Op: DestReg)
3593 .addOperand(Op: DestReg)
3594 .addImm(Val: ShAmt));
3595}
3596
3597void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3598 MCStreamer &Out) {
3599 if (Inst.getNumOperands() == 3) {
3600 // unmasked va >= x
3601 //
3602 // pseudoinstruction: vmsge{u}.vx vd, va, x
3603 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3604 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opcode)
3605 .addOperand(Op: Inst.getOperand(i: 0))
3606 .addOperand(Op: Inst.getOperand(i: 1))
3607 .addOperand(Op: Inst.getOperand(i: 2))
3608 .addReg(Reg: MCRegister())
3609 .setLoc(IDLoc));
3610 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::VMNAND_MM)
3611 .addOperand(Op: Inst.getOperand(i: 0))
3612 .addOperand(Op: Inst.getOperand(i: 0))
3613 .addOperand(Op: Inst.getOperand(i: 0))
3614 .setLoc(IDLoc));
3615 } else if (Inst.getNumOperands() == 4) {
3616 // masked va >= x, vd != v0
3617 //
3618 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3619 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3620 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3621 "The destination register should not be V0.");
3622 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opcode)
3623 .addOperand(Op: Inst.getOperand(i: 0))
3624 .addOperand(Op: Inst.getOperand(i: 1))
3625 .addOperand(Op: Inst.getOperand(i: 2))
3626 .addOperand(Op: Inst.getOperand(i: 3))
3627 .setLoc(IDLoc));
3628 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::VMXOR_MM)
3629 .addOperand(Op: Inst.getOperand(i: 0))
3630 .addOperand(Op: Inst.getOperand(i: 0))
3631 .addReg(Reg: RISCV::V0)
3632 .setLoc(IDLoc));
3633 } else if (Inst.getNumOperands() == 5 &&
3634 Inst.getOperand(i: 0).getReg() == RISCV::V0) {
3635 // masked va >= x, vd == v0
3636 //
3637 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3638 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3639 assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
3640 "The destination register should be V0.");
3641 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3642 "The temporary vector register should not be V0.");
3643 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opcode)
3644 .addOperand(Op: Inst.getOperand(i: 1))
3645 .addOperand(Op: Inst.getOperand(i: 2))
3646 .addOperand(Op: Inst.getOperand(i: 3))
3647 .addReg(Reg: MCRegister())
3648 .setLoc(IDLoc));
3649 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::VMANDN_MM)
3650 .addOperand(Op: Inst.getOperand(i: 0))
3651 .addOperand(Op: Inst.getOperand(i: 0))
3652 .addOperand(Op: Inst.getOperand(i: 1))
3653 .setLoc(IDLoc));
3654 } else if (Inst.getNumOperands() == 5) {
3655 // masked va >= x, any vd
3656 //
3657 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3658 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3659 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3660 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3661 "The temporary vector register should not be V0.");
3662 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opcode)
3663 .addOperand(Op: Inst.getOperand(i: 1))
3664 .addOperand(Op: Inst.getOperand(i: 2))
3665 .addOperand(Op: Inst.getOperand(i: 3))
3666 .addReg(Reg: MCRegister())
3667 .setLoc(IDLoc));
3668 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::VMANDN_MM)
3669 .addOperand(Op: Inst.getOperand(i: 1))
3670 .addReg(Reg: RISCV::V0)
3671 .addOperand(Op: Inst.getOperand(i: 1))
3672 .setLoc(IDLoc));
3673 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::VMANDN_MM)
3674 .addOperand(Op: Inst.getOperand(i: 0))
3675 .addOperand(Op: Inst.getOperand(i: 0))
3676 .addReg(Reg: RISCV::V0)
3677 .setLoc(IDLoc));
3678 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::VMOR_MM)
3679 .addOperand(Op: Inst.getOperand(i: 0))
3680 .addOperand(Op: Inst.getOperand(i: 1))
3681 .addOperand(Op: Inst.getOperand(i: 0))
3682 .setLoc(IDLoc));
3683 }
3684}
3685
3686bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3687 OperandVector &Operands) {
3688 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3689 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3690 if (Inst.getOperand(i: 2).getReg() != RISCV::X4) {
3691 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3692 return Error(L: ErrorLoc, Msg: "the second input operand must be tp/x4 when using "
3693 "%tprel_add specifier");
3694 }
3695
3696 return false;
3697}
3698
3699bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3700 OperandVector &Operands) {
3701 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3702 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3703 if (Inst.getOperand(i: 0).getReg() != RISCV::X5) {
3704 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3705 return Error(L: ErrorLoc, Msg: "the output operand must be t0/x5 when using "
3706 "%tlsdesc_call specifier");
3707 }
3708
3709 return false;
3710}
3711
3712std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3713 return RISCVOperand::createReg(Reg: MCRegister(), S: llvm::SMLoc(), E: llvm::SMLoc());
3714}
3715
3716std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3717 return RISCVOperand::createFRMArg(FRM: RISCVFPRndMode::RoundingMode::DYN,
3718 S: llvm::SMLoc());
3719}
3720
3721std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3722 return RISCVOperand::createFRMArg(FRM: RISCVFPRndMode::RoundingMode::RNE,
3723 S: llvm::SMLoc());
3724}
3725
3726bool RISCVAsmParser::validateInstruction(MCInst &Inst,
3727 OperandVector &Operands) {
3728 unsigned Opcode = Inst.getOpcode();
3729
3730 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
3731 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
3732 MCRegister DestReg = Inst.getOperand(i: 0).getReg();
3733 MCRegister TempReg = Inst.getOperand(i: 1).getReg();
3734 if (DestReg == TempReg) {
3735 SMLoc Loc = Operands.back()->getStartLoc();
3736 return Error(L: Loc, Msg: "the temporary vector register cannot be the same as "
3737 "the destination register");
3738 }
3739 }
3740
3741 if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
3742 Opcode == RISCV::TH_LWD) {
3743 MCRegister Rd1 = Inst.getOperand(i: 0).getReg();
3744 MCRegister Rd2 = Inst.getOperand(i: 1).getReg();
3745 MCRegister Rs1 = Inst.getOperand(i: 2).getReg();
3746 // The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
3747 if (Rs1 == Rd1 || Rs1 == Rd2 || Rd1 == Rd2) {
3748 SMLoc Loc = Operands[1]->getStartLoc();
3749 return Error(L: Loc, Msg: "rs1, rd1, and rd2 cannot overlap");
3750 }
3751 }
3752
3753 if (Opcode == RISCV::CM_MVSA01 || Opcode == RISCV::QC_CM_MVSA01) {
3754 MCRegister Rd1 = Inst.getOperand(i: 0).getReg();
3755 MCRegister Rd2 = Inst.getOperand(i: 1).getReg();
3756 if (Rd1 == Rd2) {
3757 SMLoc Loc = Operands[1]->getStartLoc();
3758 return Error(L: Loc, Msg: "rs1 and rs2 must be different");
3759 }
3760 }
3761
3762 const MCInstrDesc &MCID = MII.get(Opcode);
3763 if (!(MCID.TSFlags & RISCVII::ConstraintMask))
3764 return false;
3765
3766 if (Opcode == RISCV::SF_VC_V_XVW || Opcode == RISCV::SF_VC_V_IVW ||
3767 Opcode == RISCV::SF_VC_V_FVW || Opcode == RISCV::SF_VC_V_VVW) {
3768 // Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for SF_VC_V_XVW.
3769 MCRegister VCIXDst = Inst.getOperand(i: 0).getReg();
3770 SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
3771 if (MCID.TSFlags & RISCVII::VS1Constraint) {
3772 MCRegister VCIXRs1 = Inst.getOperand(i: Inst.getNumOperands() - 1).getReg();
3773 if (VCIXDst == VCIXRs1)
3774 return Error(L: VCIXDstLoc, Msg: "the destination vector register group cannot"
3775 " overlap the source vector register group");
3776 }
3777 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3778 MCRegister VCIXRs2 = Inst.getOperand(i: Inst.getNumOperands() - 2).getReg();
3779 if (VCIXDst == VCIXRs2)
3780 return Error(L: VCIXDstLoc, Msg: "the destination vector register group cannot"
3781 " overlap the source vector register group");
3782 }
3783 return false;
3784 }
3785
3786 MCRegister DestReg = Inst.getOperand(i: 0).getReg();
3787 unsigned Offset = 0;
3788 int TiedOp = MCID.getOperandConstraint(OpNum: 1, Constraint: MCOI::TIED_TO);
3789 if (TiedOp == 0)
3790 Offset = 1;
3791
3792 // Operands[1] will be the first operand, DestReg.
3793 SMLoc Loc = Operands[1]->getStartLoc();
3794 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3795 MCRegister CheckReg = Inst.getOperand(i: Offset + 1).getReg();
3796 if (DestReg == CheckReg)
3797 return Error(L: Loc, Msg: "the destination vector register group cannot overlap"
3798 " the source vector register group");
3799 }
3800 if ((MCID.TSFlags & RISCVII::VS1Constraint) && Inst.getOperand(i: Offset + 2).isReg()) {
3801 MCRegister CheckReg = Inst.getOperand(i: Offset + 2).getReg();
3802 if (DestReg == CheckReg)
3803 return Error(L: Loc, Msg: "the destination vector register group cannot overlap"
3804 " the source vector register group");
3805 }
3806 if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
3807 // vadc, vsbc are special cases. These instructions have no mask register.
3808 // The destination register could not be V0.
3809 if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
3810 Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
3811 Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
3812 Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
3813 Opcode == RISCV::VMERGE_VXM)
3814 return Error(L: Loc, Msg: "the destination vector register group cannot be V0");
3815
3816 // Regardless masked or unmasked version, the number of operands is the
3817 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
3818 // actually. We need to check the last operand to ensure whether it is
3819 // masked or not.
3820 MCRegister CheckReg = Inst.getOperand(i: Inst.getNumOperands() - 1).getReg();
3821 assert((CheckReg == RISCV::V0 || !CheckReg) &&
3822 "Unexpected register for mask operand");
3823
3824 if (DestReg == CheckReg)
3825 return Error(L: Loc, Msg: "the destination vector register group cannot overlap"
3826 " the mask register");
3827 }
3828 return false;
3829}
3830
3831bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
3832 OperandVector &Operands,
3833 MCStreamer &Out) {
3834 Inst.setLoc(IDLoc);
3835
3836 switch (Inst.getOpcode()) {
3837 default:
3838 break;
3839 case RISCV::PseudoC_ADDI_NOP:
3840 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::C_NOP));
3841 return false;
3842 case RISCV::PseudoLLAImm:
3843 case RISCV::PseudoLAImm:
3844 case RISCV::PseudoLI: {
3845 MCRegister Reg = Inst.getOperand(i: 0).getReg();
3846 const MCOperand &Op1 = Inst.getOperand(i: 1);
3847 if (Op1.isExpr()) {
3848 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
3849 // Just convert to an addi. This allows compatibility with gas.
3850 emitToStreamer(S&: Out, Inst: MCInstBuilder(RISCV::ADDI)
3851 .addReg(Reg)
3852 .addReg(Reg: RISCV::X0)
3853 .addExpr(Val: Op1.getExpr()));
3854 return false;
3855 }
3856 int64_t Imm = Inst.getOperand(i: 1).getImm();
3857 // On RV32 the immediate here can either be a signed or an unsigned
3858 // 32-bit number. Sign extension has to be performed to ensure that Imm
3859 // represents the expected signed 64-bit number.
3860 if (!isRV64())
3861 Imm = SignExtend64<32>(x: Imm);
3862 emitLoadImm(DestReg: Reg, Value: Imm, Out);
3863 return false;
3864 }
3865 case RISCV::PseudoLLA:
3866 emitLoadLocalAddress(Inst, IDLoc, Out);
3867 return false;
3868 case RISCV::PseudoLGA:
3869 emitLoadGlobalAddress(Inst, IDLoc, Out);
3870 return false;
3871 case RISCV::PseudoLA:
3872 emitLoadAddress(Inst, IDLoc, Out);
3873 return false;
3874 case RISCV::PseudoLA_TLS_IE:
3875 emitLoadTLSIEAddress(Inst, IDLoc, Out);
3876 return false;
3877 case RISCV::PseudoLA_TLS_GD:
3878 emitLoadTLSGDAddress(Inst, IDLoc, Out);
3879 return false;
3880 case RISCV::PseudoLB:
3881 case RISCV::PseudoQC_E_LB:
3882 emitLoadStoreSymbol(Inst, Opcode: RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
3883 return false;
3884 case RISCV::PseudoLBU:
3885 case RISCV::PseudoQC_E_LBU:
3886 emitLoadStoreSymbol(Inst, Opcode: RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
3887 return false;
3888 case RISCV::PseudoLH:
3889 case RISCV::PseudoQC_E_LH:
3890 emitLoadStoreSymbol(Inst, Opcode: RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
3891 return false;
3892 case RISCV::PseudoLHU:
3893 case RISCV::PseudoQC_E_LHU:
3894 emitLoadStoreSymbol(Inst, Opcode: RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
3895 return false;
3896 case RISCV::PseudoLW:
3897 case RISCV::PseudoQC_E_LW:
3898 emitLoadStoreSymbol(Inst, Opcode: RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
3899 return false;
3900 case RISCV::PseudoLWU:
3901 emitLoadStoreSymbol(Inst, Opcode: RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
3902 return false;
3903 case RISCV::PseudoLD:
3904 emitLoadStoreSymbol(Inst, Opcode: RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
3905 return false;
3906 case RISCV::PseudoLD_RV32:
3907 emitLoadStoreSymbol(Inst, Opcode: RISCV::LD_RV32, IDLoc, Out, /*HasTmpReg=*/false);
3908 return false;
3909 case RISCV::PseudoFLH:
3910 emitLoadStoreSymbol(Inst, Opcode: RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
3911 return false;
3912 case RISCV::PseudoFLW:
3913 emitLoadStoreSymbol(Inst, Opcode: RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
3914 return false;
3915 case RISCV::PseudoFLD:
3916 emitLoadStoreSymbol(Inst, Opcode: RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
3917 return false;
3918 case RISCV::PseudoFLQ:
3919 emitLoadStoreSymbol(Inst, Opcode: RISCV::FLQ, IDLoc, Out, /*HasTmpReg=*/true);
3920 return false;
3921 case RISCV::PseudoSB:
3922 case RISCV::PseudoQC_E_SB:
3923 emitLoadStoreSymbol(Inst, Opcode: RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
3924 return false;
3925 case RISCV::PseudoSH:
3926 case RISCV::PseudoQC_E_SH:
3927 emitLoadStoreSymbol(Inst, Opcode: RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
3928 return false;
3929 case RISCV::PseudoSW:
3930 case RISCV::PseudoQC_E_SW:
3931 emitLoadStoreSymbol(Inst, Opcode: RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
3932 return false;
3933 case RISCV::PseudoSD:
3934 emitLoadStoreSymbol(Inst, Opcode: RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
3935 return false;
3936 case RISCV::PseudoSD_RV32:
3937 emitLoadStoreSymbol(Inst, Opcode: RISCV::SD_RV32, IDLoc, Out, /*HasTmpReg=*/true);
3938 return false;
3939 case RISCV::PseudoFSH:
3940 emitLoadStoreSymbol(Inst, Opcode: RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
3941 return false;
3942 case RISCV::PseudoFSW:
3943 emitLoadStoreSymbol(Inst, Opcode: RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
3944 return false;
3945 case RISCV::PseudoFSD:
3946 emitLoadStoreSymbol(Inst, Opcode: RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
3947 return false;
3948 case RISCV::PseudoFSQ:
3949 emitLoadStoreSymbol(Inst, Opcode: RISCV::FSQ, IDLoc, Out, /*HasTmpReg=*/true);
3950 return false;
3951 case RISCV::PseudoAddTPRel:
3952 if (checkPseudoAddTPRel(Inst, Operands))
3953 return true;
3954 break;
3955 case RISCV::PseudoTLSDESCCall:
3956 if (checkPseudoTLSDESCCall(Inst, Operands))
3957 return true;
3958 break;
3959 case RISCV::PseudoSEXT_B:
3960 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
3961 return false;
3962 case RISCV::PseudoSEXT_H:
3963 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
3964 return false;
3965 case RISCV::PseudoZEXT_H:
3966 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
3967 return false;
3968 case RISCV::PseudoZEXT_W:
3969 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
3970 return false;
3971 case RISCV::PseudoVMSGEU_VX:
3972 case RISCV::PseudoVMSGEU_VX_M:
3973 case RISCV::PseudoVMSGEU_VX_M_T:
3974 emitVMSGE(Inst, Opcode: RISCV::VMSLTU_VX, IDLoc, Out);
3975 return false;
3976 case RISCV::PseudoVMSGE_VX:
3977 case RISCV::PseudoVMSGE_VX_M:
3978 case RISCV::PseudoVMSGE_VX_M_T:
3979 emitVMSGE(Inst, Opcode: RISCV::VMSLT_VX, IDLoc, Out);
3980 return false;
3981 case RISCV::PseudoVMSGE_VI:
3982 case RISCV::PseudoVMSLT_VI: {
3983 // These instructions are signed and so is immediate so we can subtract one
3984 // and change the opcode.
3985 int64_t Imm = Inst.getOperand(i: 2).getImm();
3986 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
3987 : RISCV::VMSLE_VI;
3988 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opc)
3989 .addOperand(Op: Inst.getOperand(i: 0))
3990 .addOperand(Op: Inst.getOperand(i: 1))
3991 .addImm(Val: Imm - 1)
3992 .addOperand(Op: Inst.getOperand(i: 3))
3993 .setLoc(IDLoc));
3994 return false;
3995 }
3996 case RISCV::PseudoVMSGEU_VI:
3997 case RISCV::PseudoVMSLTU_VI: {
3998 int64_t Imm = Inst.getOperand(i: 2).getImm();
3999 // Unsigned comparisons are tricky because the immediate is signed. If the
4000 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
4001 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
4002 // vmsne v0, v1, v1 which is always false.
4003 if (Imm == 0) {
4004 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
4005 ? RISCV::VMSEQ_VV
4006 : RISCV::VMSNE_VV;
4007 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opc)
4008 .addOperand(Op: Inst.getOperand(i: 0))
4009 .addOperand(Op: Inst.getOperand(i: 1))
4010 .addOperand(Op: Inst.getOperand(i: 1))
4011 .addOperand(Op: Inst.getOperand(i: 3))
4012 .setLoc(IDLoc));
4013 } else {
4014 // Other immediate values can subtract one like signed.
4015 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
4016 ? RISCV::VMSGTU_VI
4017 : RISCV::VMSLEU_VI;
4018 emitToStreamer(S&: Out, Inst: MCInstBuilder(Opc)
4019 .addOperand(Op: Inst.getOperand(i: 0))
4020 .addOperand(Op: Inst.getOperand(i: 1))
4021 .addImm(Val: Imm - 1)
4022 .addOperand(Op: Inst.getOperand(i: 3))
4023 .setLoc(IDLoc));
4024 }
4025
4026 return false;
4027 }
4028 }
4029
4030 emitToStreamer(S&: Out, Inst);
4031 return false;
4032}
4033
4034extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
4035LLVMInitializeRISCVAsmParser() {
4036 RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
4037 RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
4038}
4039