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