LLVM 24.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
18#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
24#include "llvm/MC/MCAssembler.h"
25#include "llvm/MC/MCContext.h"
26#include "llvm/MC/MCExpr.h"
27#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstrInfo.h"
35#include "llvm/MC/MCStreamer.h"
37#include "llvm/MC/MCValue.h"
41#include "llvm/Support/Debug.h"
45
46#include <limits>
47#include <map>
48#include <optional>
49
50using namespace llvm;
51
52#define DEBUG_TYPE "riscv-asm-parser"
53
54STATISTIC(RISCVNumInstrsCompressed,
55 "Number of RISC-V Compressed instructions emitted");
56
57namespace {
58struct RISCVOperand;
59
60struct ParserOptionsSet {
61 bool IsPicEnabled;
62};
63
64class RISCVAsmParser : public MCTargetAsmParser {
65 const RISCVMCOptions &CLOpts;
66
67 // This tracks the parsing of the 4 optional operands that make up the vtype
68 // portion of vset(i)vli instructions which are separated by commas.
69 enum class VTypeState {
70 SeenNothingYet,
71 SeenSew,
72 SeenLmul,
73 SeenTailPolicy,
74 SeenMaskPolicy,
75 };
76
77 SmallVector<FeatureBitset, 4> FeatureBitStack;
78
79 SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
80 ParserOptionsSet ParserOptions;
81
82 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
83 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
84 bool isRVE() const { return getSTI().hasFeature(RISCV::FeatureStdExtE); }
85 bool enableExperimentalExtension() const {
86 return getSTI().hasFeature(RISCV::Experimental);
87 }
88
89 RISCVTargetStreamer &getTargetStreamer() {
90 assert(getParser().getStreamer().getTargetStreamer() &&
91 "do not have a target streamer");
92 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
93 return static_cast<RISCVTargetStreamer &>(TS);
94 }
95
96 bool generateImmOutOfRangeError(SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
97 const Twine &Msg);
98
99 struct NearMissMessage {
100 SMLoc Loc;
101 std::string Message;
102 };
103
104 std::string getCustomOperandDiag(unsigned MatchError);
105
106 void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
107 SmallVectorImpl<NearMissMessage> &NearMissesOut,
108 SMLoc IDLoc, OperandVector &Operands);
109 void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
111
112 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
113 OperandVector &Operands, MCStreamer &Out,
114 uint64_t &ErrorInfo,
115 bool MatchingInlineAsm) override;
116
117 MCRegister matchRegisterNameHelper(StringRef Name) const;
118 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
119 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
120 SMLoc &EndLoc) override;
121
122 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
123 SMLoc NameLoc, OperandVector &Operands) override;
124
125 ParseStatus parseDirective(AsmToken DirectiveID) override;
126
127 bool parseVTypeToken(const AsmToken &Tok, VTypeState &State, unsigned &Sew,
128 unsigned &Lmul, bool &Fractional, bool &TailAgnostic,
129 bool &MaskAgnostic, bool &AltFmt);
130 bool generateVTypeError(SMLoc ErrorLoc);
131
132 bool generateXSfmmVTypeError(SMLoc ErrorLoc);
133 // Helper to actually emit an instruction to the MCStreamer. Also, when
134 // possible, compression of the instruction is performed.
135 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
136 void validateInstructionPreEmit(const MCInst &Inst,
137 const MCSubtargetInfo &STI);
138
139 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
140 // synthesize the desired immediate value into the destination register.
141 void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
142
143 // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
144 // helpers such as emitLoadLocalAddress and emitLoadAddress.
145 void emitAuipcInstPair(MCRegister DestReg, MCRegister TmpReg,
146 const MCExpr *Symbol, RISCV::Specifier VKHi,
147 unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
148
149 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
150 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
151
152 // Helper to emit pseudo instruction "lga" used in GOT-rel addressing.
153 void emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
154
155 // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
156 void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
157
158 // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
159 // addressing.
160 void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
161
162 // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
163 // addressing.
164 void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
165
166 // Helper to emit pseudo load/store instruction with a symbol.
167 void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
168 MCStreamer &Out, bool HasTmpReg);
169
170 // Helper to emit Xqcilo pseudo load/store as qc.e.li + PseudoQCAccess pair.
171 // For loads: qc.e.li rd, sym; lx rd, 0(rd), %qc.access(sym)
172 // For stores: qc.e.li rt, sym; sx rs, 0(rt), %qc.access(sym)
173 void emitQCELILoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
174 MCStreamer &Out, bool HasTmpReg);
175
176 // Helper to emit pseudo sign/zero extend instruction.
177 void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
178 SMLoc IDLoc, MCStreamer &Out);
179
180 // Helper to emit pseudo vmsge{u}.vx instruction.
181 void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
182
183 // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
184 // Enforcing this using a restricted register class for the second input
185 // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
186 // 'add' is an overloaded mnemonic.
187 bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
188
189 // Checks that a PseudoTLSDESCCall is using x5/t0 in its output operand.
190 // Enforcing this using a restricted register class for the output
191 // operand of PseudoTLSDESCCall results in a poor diagnostic due to the fact
192 // 'jalr' is an overloaded mnemonic.
193 bool checkPseudoTLSDESCCall(MCInst &Inst, OperandVector &Operands);
194
195 // Check instruction constraints.
196 bool validateInstruction(MCInst &Inst, OperandVector &Operands);
197
198 /// Helper for processing MC instructions that have been successfully matched
199 /// by matchAndEmitInstruction. Modifications to the emitted instructions,
200 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
201 /// in this method.
202 bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
203 MCStreamer &Out);
204
205// Auto-generated instruction matching functions
206#define GET_ASSEMBLER_HEADER
207#include "RISCVGenAsmMatcher.inc"
208
209 ParseStatus parseCSRSystemRegister(OperandVector &Operands);
211 ParseStatus parseExpression(OperandVector &Operands);
212 ParseStatus parseRegister(OperandVector &Operands, bool AllowParens = false);
213 ParseStatus parseMemOpBaseReg(OperandVector &Operands);
214 ParseStatus parseZeroOffsetMemOp(OperandVector &Operands);
215 ParseStatus parseOperandWithSpecifier(OperandVector &Operands);
216 ParseStatus parseBareSymbol(OperandVector &Operands);
217 ParseStatus parseCallSymbol(OperandVector &Operands);
218 ParseStatus parseTailCallSymbol(OperandVector &Operands);
219 ParseStatus parsePseudoJumpSymbol(OperandVector &Operands);
220 ParseStatus parseJALOffset(OperandVector &Operands);
221 ParseStatus parseVTypeI(OperandVector &Operands);
222 ParseStatus parseMaskReg(OperandVector &Operands);
223 ParseStatus parseVScaleReg(OperandVector &Operands);
224 ParseStatus parseTileLambda(OperandVector &Operands);
225 ParseStatus parseInsnDirectiveOpcode(OperandVector &Operands);
226 ParseStatus parseInsnCDirectiveOpcode(OperandVector &Operands);
227 ParseStatus parseFRMArg(OperandVector &Operands);
228 ParseStatus parseSMTVType(OperandVector &Operands);
229 ParseStatus parseFenceArg(OperandVector &Operands);
230 ParseStatus parseRegList(OperandVector &Operands, bool MustIncludeS0 = false);
231 ParseStatus parseRegListS0(OperandVector &Operands) {
232 return parseRegList(Operands, /*MustIncludeS0=*/true);
233 }
234
235 ParseStatus parseRegReg(OperandVector &Operands);
236 ParseStatus parseXSfmmVType(OperandVector &Operands);
237 ParseStatus parseZcmpStackAdj(OperandVector &Operands,
238 bool ExpectNegative = false);
239 ParseStatus parseZcmpNegStackAdj(OperandVector &Operands) {
240 return parseZcmpStackAdj(Operands, /*ExpectNegative*/ true);
241 }
242
243 bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
244 bool parseExprWithSpecifier(const MCExpr *&Res, SMLoc &E);
245 bool parseDataExpr(const MCExpr *&Res) override;
246
247 bool parseDirectiveOption();
248 bool parseDirectiveAttribute();
249 bool parseDirectiveInsn(SMLoc L);
250 bool parseDirectiveVariantCC();
251
252 /// Helper to reset target features for a new arch string. It
253 /// also records the new arch string that is expanded by RISCVISAInfo
254 /// and reports error for invalid arch string.
255 bool resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
256 bool FromOptionDirective);
257
258 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
259 if (!(getSTI().hasFeature(Feature))) {
260 MCSubtargetInfo &STI = copySTI();
261 STI.ToggleFeature(FeatureString);
262
263 // Update the C and Zce implications.
265
266 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
267 }
268 }
269
270 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
271 if (getSTI().hasFeature(Feature)) {
272 MCSubtargetInfo &STI = copySTI();
273 setAvailableFeatures(
274 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
275 }
276 }
277
278 void pushFeatureBits() {
279 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
280 "These two stacks must be kept synchronized");
281 FeatureBitStack.push_back(getSTI().getFeatureBits());
282 ParserOptionsStack.push_back(ParserOptions);
283 }
284
285 bool popFeatureBits() {
286 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
287 "These two stacks must be kept synchronized");
288 if (FeatureBitStack.empty())
289 return true;
290
291 FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
292 copySTI().setFeatureBits(FeatureBits);
293 setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
294
295 ParserOptions = ParserOptionsStack.pop_back_val();
296
297 return false;
298 }
299
300 std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
301 std::unique_ptr<RISCVOperand> defaultFRMArgOp() const;
302 std::unique_ptr<RISCVOperand> defaultFRMArgLegacyOp() const;
303 std::unique_ptr<RISCVOperand> defaultSMTVType();
304 std::unique_ptr<RISCVOperand> defaultZeroOffset();
305
306public:
307 enum RISCVMatchResultTy : unsigned {
308 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
309#define GET_OPERAND_DIAGNOSTIC_TYPES
310#include "RISCVGenAsmMatcher.inc"
311#undef GET_OPERAND_DIAGNOSTIC_TYPES
312 };
313
314 static bool classifySymbolRef(const MCExpr *Expr, RISCV::Specifier &Kind);
315 static bool isSymbolDiff(const MCExpr *Expr);
316
317 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
318 const MCInstrInfo &MII)
319 : MCTargetAsmParser(STI, MII),
320 CLOpts(RISCV_MC::getCLOpts(Parser.getContext().getTargetOptions())) {
322
323 Parser.addAliasForDirective(".half", ".2byte");
324 Parser.addAliasForDirective(".hword", ".2byte");
325 Parser.addAliasForDirective(".word", ".4byte");
326 Parser.addAliasForDirective(".dword", ".8byte");
327 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
328
329 const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
330 ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
331
332 if (CLOpts.add_build_attributes)
333 getTargetStreamer().emitTargetAttributes(STI, /*EmitStackAlign*/ false);
334 }
335
336 // Validate the requested -target-abi now that the lexer has been primed
337 // with the first token, so diagnostics can be reported with a real source
338 // location instead of being printed with no location information.
339 void onBeginOfFile() override {
340 // If the target streamer already has a resolved ABI (e.g. set by
341 // RISCVAsmPrinter during codegen), skip ABI validation.
342 if (getTargetStreamer().hasTargetABI())
343 return;
344
345 Expected<RISCVABI::ABI> ABIOrErr =
346 RISCVABI::computeTargetABI(getSTI(), getTargetOptions().ABIName);
347 if (!ABIOrErr) {
348 getParser().printError(getLoc(), toString(ABIOrErr.takeError()));
349 getTargetStreamer().setTargetABI(
350 cantFail(RISCVABI::computeTargetABI(getSTI(), "")));
351 return;
352 }
353 getTargetStreamer().setTargetABI(*ABIOrErr);
354 }
355};
356
357/// RISCVOperand - Instances of this class represent a parsed machine
358/// instruction
359struct RISCVOperand final : public MCParsedAsmOperand {
360
361 enum class KindTy {
362 Token,
363 Register,
364 Expression,
365 FPImmediate,
366 SystemRegister,
367 VType,
368 SMTVType,
369 FRM,
370 Fence,
371 RegList,
372 StackAdj,
373 RegReg,
374 } Kind;
375
376 struct ExprOp {
377 const MCExpr *Expr;
378 bool IsRV64;
379 };
380
381 struct FPImmOp {
382 uint64_t Val;
383 };
384
385 struct SysRegOp {
386 const char *Data;
387 unsigned Length;
388 unsigned Encoding;
389 // FIXME: Add the Encoding parsed fields as needed for checks,
390 // e.g.: read/write or user/supervisor/machine privileges.
391 };
392
393 struct VTypeOp {
394 unsigned Val;
395 };
396
397 struct SMTVTypeOp {
399 };
400
401 struct FRMOp {
403 };
404
405 struct FenceOp {
406 unsigned Val;
407 };
408
409 struct RegListOp {
410 unsigned Encoding;
411 };
412
413 struct StackAdjOp {
414 unsigned Val;
415 };
416
417 struct RegRegOp {
418 MCRegister BaseReg;
419 MCRegister OffsetReg;
420 };
421
422 SMLoc StartLoc, EndLoc;
423 union {
424 StringRef Tok;
425 MCRegister Reg;
426 ExprOp Expr;
427 FPImmOp FPImm;
428 SysRegOp SysReg;
429 VTypeOp VType;
430 SMTVTypeOp SMTVType;
431 FRMOp FRM;
432 FenceOp Fence;
433 RegListOp RegList;
434 StackAdjOp StackAdj;
435 RegRegOp RegReg;
436 };
437
438 RISCVOperand(KindTy K) : Kind(K) {}
439
440public:
441 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
442 Kind = o.Kind;
443 StartLoc = o.StartLoc;
444 EndLoc = o.EndLoc;
445 switch (Kind) {
446 case KindTy::Register:
447 Reg = o.Reg;
448 break;
449 case KindTy::Expression:
450 Expr = o.Expr;
451 break;
452 case KindTy::FPImmediate:
453 FPImm = o.FPImm;
454 break;
455 case KindTy::Token:
456 Tok = o.Tok;
457 break;
458 case KindTy::SystemRegister:
459 SysReg = o.SysReg;
460 break;
461 case KindTy::VType:
462 VType = o.VType;
463 break;
464 case KindTy::SMTVType:
465 SMTVType = o.SMTVType;
466 break;
467 case KindTy::FRM:
468 FRM = o.FRM;
469 break;
470 case KindTy::Fence:
471 Fence = o.Fence;
472 break;
473 case KindTy::RegList:
474 RegList = o.RegList;
475 break;
476 case KindTy::StackAdj:
477 StackAdj = o.StackAdj;
478 break;
479 case KindTy::RegReg:
480 RegReg = o.RegReg;
481 break;
482 }
483 }
484
485 bool isToken() const override { return Kind == KindTy::Token; }
486 bool isReg() const override { return Kind == KindTy::Register; }
487 bool isExpr() const { return Kind == KindTy::Expression; }
488 bool isV0Reg() const { return Kind == KindTy::Register && Reg == RISCV::V0; }
489 bool isAnyReg() const {
490 return Kind == KindTy::Register &&
491 (getRISCVMCRegisterClass(RISCV::GPRRegClassID).contains(Reg) ||
492 getRISCVMCRegisterClass(RISCV::FPR64RegClassID).contains(Reg) ||
493 getRISCVMCRegisterClass(RISCV::VRRegClassID).contains(Reg));
494 }
495 bool isAnyRegC() const {
496 return Kind == KindTy::Register &&
497 (getRISCVMCRegisterClass(RISCV::GPRCRegClassID).contains(Reg) ||
498 getRISCVMCRegisterClass(RISCV::FPR64CRegClassID).contains(Reg));
499 }
500 bool isImm() const override { return isExpr(); }
501 bool isMem() const override { return false; }
502 bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
503 bool isRegReg() const { return Kind == KindTy::RegReg; }
504 bool isRegList() const { return Kind == KindTy::RegList; }
505 bool isRegListS0() const {
506 return Kind == KindTy::RegList && RegList.Encoding != RISCVZC::RA;
507 }
508 bool isStackAdj() const { return Kind == KindTy::StackAdj; }
509
510 bool isGPR() const {
511 return Kind == KindTy::Register &&
512 getRISCVMCRegisterClass(RISCV::GPRRegClassID).contains(Reg);
513 }
514
515 bool isGPRForFP(const MCSubtargetInfo &STI) const {
516 // Check !F rather than Zfinx/Zdinx/Zhinx so GPR operands still match *inx
517 // variants when no FP extension is enabled, letting the matcher report the
518 // missing *inx extension instead of an invalid operand.
519 return isGPR() && !STI.hasFeature(RISCV::FeatureStdExtF);
520 }
521
522 bool isGPRForFP64(const MCSubtargetInfo &STI) const {
523 // Accept single GPRs on RV32 Zdinx as well so RV64-only instructions (which
524 // have no GPRPairAsFPR variant) report the missing RV64 feature rather than
525 // an invalid operand.
526 return isGPR() && !STI.hasFeature(RISCV::FeatureStdExtF) &&
527 (STI.hasFeature(RISCV::Feature64Bit) ||
528 STI.hasFeature(RISCV::FeatureStdExtZdinx));
529 }
530
531 bool isEvenGPRForFP64(const MCSubtargetInfo &STI) const {
532 return isGPR() && (Reg - RISCV::X0) % 2 == 0 &&
533 !STI.hasFeature(RISCV::Feature64Bit) &&
534 !STI.hasFeature(RISCV::FeatureStdExtF);
535 }
536
537 static bool evaluateConstantExpr(const MCExpr *Expr, int64_t &Imm) {
538 if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
539 Imm = CE->getValue();
540 return true;
541 }
542
543 return false;
544 }
545
546 // True if operand is a symbol with no modifiers, or a constant with no
547 // modifiers and isShiftedInt<N-1, 1>(Op).
548 template <int N> bool isBareSimmNLsb0() const {
549 if (!isExpr())
550 return false;
551
552 int64_t Imm;
553 if (evaluateConstantExpr(getExpr(), Imm))
554 return isShiftedInt<N - 1, 1>(fixImmediateForRV32(Imm, isRV64Expr()));
555
557 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
558 VK == RISCV::S_None;
559 }
560
561 // True if operand is a symbol with no modifiers, or a constant with no
562 // modifiers and isInt<N>(Op).
563 template <int N> bool isBareSimmN() const {
564 if (!isExpr())
565 return false;
566
567 int64_t Imm;
568 if (evaluateConstantExpr(getExpr(), Imm))
569 return isInt<N>(fixImmediateForRV32(Imm, isRV64Expr()));
570
572 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
573 VK == RISCV::S_None;
574 }
575
576 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
577
578 bool isBareSymbol() const {
579 int64_t Imm;
580 // Must be of 'immediate' type but not a constant.
581 if (!isExpr() || evaluateConstantExpr(getExpr(), Imm))
582 return false;
583
585 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
586 VK == RISCV::S_None;
587 }
588
589 bool isCallSymbol() const {
590 int64_t Imm;
591 // Must be of 'immediate' type but not a constant.
592 if (!isExpr() || evaluateConstantExpr(getExpr(), Imm))
593 return false;
594
596 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
597 VK == RISCV::S_CALL_PLT;
598 }
599
600 bool isTailCallSymbol() const { return isCallSymbol(); }
601
602 bool isPseudoJumpSymbol() const {
603 int64_t Imm;
604 // Must be of 'immediate' type but not a constant.
605 if (!isExpr() || evaluateConstantExpr(getExpr(), Imm))
606 return false;
607
609 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
610 VK == RISCV::S_CALL_PLT;
611 }
612
613 bool isTPRelAddSymbol() const {
614 int64_t Imm;
615 // Must be of 'immediate' type but not a constant.
616 if (!isExpr() || evaluateConstantExpr(getExpr(), Imm))
617 return false;
618
620 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
621 VK == ELF::R_RISCV_TPREL_ADD;
622 }
623
624 bool isTLSDESCCallSymbol() const {
625 int64_t Imm;
626 // Must be of 'immediate' type but not a constant.
627 if (!isExpr() || evaluateConstantExpr(getExpr(), Imm))
628 return false;
629
631 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
632 VK == ELF::R_RISCV_TLSDESC_CALL;
633 }
634
635 bool isQCAccessSymbol() const {
636 int64_t Imm;
637 // Must be of 'immediate' type but not a constant.
638 if (!isExpr() || evaluateConstantExpr(getExpr(), Imm))
639 return false;
640
642 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
643 VK == RISCV::S_QC_ACCESS;
644 }
645
646 bool isCSRSystemRegister() const { return isSystemRegister(); }
647
648 // If the last operand of the vsetvli/vsetvli instruction is a constant
649 // expression, KindTy is Immediate.
650 bool isVTypeI10() const {
651 if (Kind == KindTy::VType)
652 return true;
653 return isUImm<10>();
654 }
655 bool isVTypeI11() const {
656 if (Kind == KindTy::VType)
657 return true;
658 return isUImm<11>();
659 }
660
661 bool isXSfmmVType() const {
662 return Kind == KindTy::VType && RISCVVType::isValidXSfmmVType(VType.Val);
663 }
664
665 bool isTileLambda() const {
666 return isUImmPred([](int64_t Imm) { return Imm && isUInt<3>(Imm); });
667 }
668
669 /// Return true if the operand is a valid for the fence instruction e.g.
670 /// ('iorw').
671 bool isFenceArg() const { return Kind == KindTy::Fence; }
672
673 /// Return true if the operand is a valid floating point rounding mode.
674 bool isFRMArg() const { return Kind == KindTy::FRM; }
675 bool isFRMArgLegacy() const { return Kind == KindTy::FRM; }
676 bool isRTZArg() const { return isFRMArg() && FRM.FRM == RISCVFPRndMode::RTZ; }
677
678 // Return true if the operand is a valid SpacemiT's Integer Matrix
679 // VType(i4/i8).
680 bool isSMTVType() const {
681 return Kind == KindTy::SMTVType &&
682 XSMTVTypeMode::isValidSMTVTypeMode(SMTVType.SMTVType);
683 }
684
685 bool isSMTI8() const {
686 return isSMTVType() && SMTVType.SMTVType == XSMTVTypeMode::SMT_I8;
687 }
688
689 /// Return true if the operand is a valid fli.s floating-point immediate.
690 bool isLoadFPImm() const {
691 if (isExpr())
692 return isUImm<5>();
693 if (Kind != KindTy::FPImmediate)
694 return false;
696 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
697 // Don't allow decimal version of the minimum value. It is a different value
698 // for each supported data type.
699 return Idx >= 0 && Idx != 1;
700 }
701
702 bool isImmXLenLI() const {
703 int64_t Imm;
704 if (!isExpr())
705 return false;
706 // Given only Imm, ensuring that the actually specified constant is either
707 // a signed or unsigned 64-bit number is unfortunately impossible.
708 if (evaluateConstantExpr(getExpr(), Imm))
709 return isRV64Expr() || (isInt<32>(Imm) || isUInt<32>(Imm));
710
711 return RISCVAsmParser::isSymbolDiff(getExpr());
712 }
713
714 bool isImmXLenLI_Restricted() const {
715 int64_t Imm;
716 if (!isExpr())
717 return false;
718 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
719 // 'la imm' supports constant immediates only.
720 return IsConstantImm &&
721 (isRV64Expr() || (isInt<32>(Imm) || isUInt<32>(Imm)));
722 }
723
724 template <unsigned N> bool isUImm() const {
725 int64_t Imm;
726 if (!isExpr())
727 return false;
728 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
729 return IsConstantImm && isUInt<N>(Imm);
730 }
731
732 template <unsigned N, unsigned S> bool isUImmShifted() const {
733 int64_t Imm;
734 if (!isExpr())
735 return false;
736 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
737 return IsConstantImm && isShiftedUInt<N, S>(Imm);
738 }
739
740 template <class Pred> bool isUImmPred(Pred p) const {
741 int64_t Imm;
742 if (!isExpr())
743 return false;
744 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
745 return IsConstantImm && p(Imm);
746 }
747
748 bool isUImmLog2XLen() const {
749 if (isExpr() && isRV64Expr())
750 return isUImm<6>();
751 return isUImm<5>();
752 }
753
754 bool isUImmLog2XLenNonZero() const {
755 if (isExpr() && isRV64Expr())
756 return isUImmPred([](int64_t Imm) { return Imm != 0 && isUInt<6>(Imm); });
757 return isUImmPred([](int64_t Imm) { return Imm != 0 && isUInt<5>(Imm); });
758 }
759
760 bool isUImmLog2XLenHalf() const {
761 if (isExpr() && isRV64Expr())
762 return isUImm<5>();
763 return isUImm<4>();
764 }
765
766 bool isUImm5NonZero() const {
767 return isUImmPred([](int64_t Imm) { return Imm != 0 && isUInt<5>(Imm); });
768 }
769
770 bool isUImm5GT3() const {
771 return isUImmPred([](int64_t Imm) { return isUInt<5>(Imm) && Imm > 3; });
772 }
773
774 bool isUImm4Plus1() const {
775 return isUImmPred(
776 [](int64_t Imm) { return Imm > 0 && isUInt<4>(Imm - 1); });
777 }
778
779 bool isUImm5Plus1() const {
780 return isUImmPred(
781 [](int64_t Imm) { return Imm > 0 && isUInt<5>(Imm - 1); });
782 }
783
784 bool isUImm6Plus1() const {
785 return isUImmPred(
786 [](int64_t Imm) { return Imm > 0 && isUInt<6>(Imm - 1); });
787 }
788
789 bool isUImm5GE6Plus1() const {
790 return isUImmPred(
791 [](int64_t Imm) { return Imm >= 6 && isUInt<5>(Imm - 1); });
792 }
793
794 bool isUImm5Slist() const {
795 return isUImmPred([](int64_t Imm) {
796 return (Imm == 0) || (Imm == 1) || (Imm == 2) || (Imm == 4) ||
797 (Imm == 8) || (Imm == 16) || (Imm == 15) || (Imm == 31);
798 });
799 }
800
801 bool isUImm8GE32() const {
802 return isUImmPred([](int64_t Imm) { return isUInt<8>(Imm) && Imm >= 32; });
803 }
804
805 bool isRnumArg() const {
806 return isUImmPred(
807 [](int64_t Imm) { return Imm >= INT64_C(0) && Imm <= INT64_C(10); });
808 }
809
810 bool isRnumArg_0_7() const {
811 return isUImmPred(
812 [](int64_t Imm) { return Imm >= INT64_C(0) && Imm <= INT64_C(7); });
813 }
814
815 bool isRnumArg_1_10() const {
816 return isUImmPred(
817 [](int64_t Imm) { return Imm >= INT64_C(1) && Imm <= INT64_C(10); });
818 }
819
820 bool isRnumArg_2_14() const {
821 return isUImmPred(
822 [](int64_t Imm) { return Imm >= INT64_C(2) && Imm <= INT64_C(14); });
823 }
824
825 template <unsigned N> bool isSImm() const {
826 int64_t Imm;
827 if (!isExpr())
828 return false;
829 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
830 return IsConstantImm && isInt<N>(fixImmediateForRV32(Imm, isRV64Expr()));
831 }
832
833 bool isYBNDSWImm() const {
834 if (!isExpr())
835 return false;
836
837 int64_t Imm;
838 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
839 return IsConstantImm && RISCV::isValidYBNDSWImm(Imm);
840 }
841
842 template <class Pred> bool isSImmPred(Pred p) const {
843 int64_t Imm;
844 if (!isExpr())
845 return false;
846 bool IsConstantImm = evaluateConstantExpr(getExpr(), Imm);
847 return IsConstantImm && p(fixImmediateForRV32(Imm, isRV64Expr()));
848 }
849
850 bool isSImm5NonZero() const {
851 return isSImmPred([](int64_t Imm) { return Imm != 0 && isInt<5>(Imm); });
852 }
853
854 bool isSImm6NonZero() const {
855 return isSImmPred([](int64_t Imm) { return Imm != 0 && isInt<6>(Imm); });
856 }
857
858 bool isCLUIImm() const {
859 return isUImmPred([](int64_t Imm) {
860 return (isUInt<5>(Imm) && Imm != 0) || (Imm >= 0xfffe0 && Imm <= 0xfffff);
861 });
862 }
863
864 bool isUImm10Lsb00NonZero() const {
865 return isUImmPred(
866 [](int64_t Imm) { return isShiftedUInt<8, 2>(Imm) && (Imm != 0); });
867 }
868
869 // If this a RV32 and the immediate is a uimm32, sign extend it to 32 bits.
870 // This allows writing 'addi a0, a0, 0xffffffff'.
871 static int64_t fixImmediateForRV32(int64_t Imm, bool IsRV64Imm) {
872 if (IsRV64Imm || !isUInt<32>(Imm))
873 return Imm;
874 return SignExtend64<32>(Imm);
875 }
876
877 bool isSImm12LO() const {
878 if (!isExpr())
879 return false;
880
881 int64_t Imm;
882 if (evaluateConstantExpr(getExpr(), Imm))
883 return isInt<12>(fixImmediateForRV32(Imm, isRV64Expr()));
884
886 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
887 (VK == RISCV::S_LO || VK == RISCV::S_PCREL_LO ||
888 VK == RISCV::S_TPREL_LO || VK == ELF::R_RISCV_TLSDESC_LOAD_LO12 ||
889 VK == ELF::R_RISCV_TLSDESC_ADD_LO12);
890 }
891
892 /// Returns NoMatch rather than the NearMatch of the underlying predicate
893 /// for anything that is not an immediate at all (such as the '(' token of an
894 /// offset-less memory operand). This lets the matcher skip this optional
895 /// operand and insert the default 0 offset. An immediate that fails Pred
896 /// (e.g. out of range) still reports the wrapped class diagnostic.
897 template <bool (RISCVOperand::*Pred)() const>
898 DiagnosticPredicate isOptionalMemOffset() const {
899 if (!isImm())
901 return (this->*Pred)() ? DiagnosticPredicate::Match
902 : DiagnosticPredicate::NearMatch;
903 }
904
905 bool isSImm12Lsb00000() const {
906 return isSImmPred([](int64_t Imm) { return isShiftedInt<7, 5>(Imm); });
907 }
908
909 bool isSImm10Lsb0000NonZero() const {
910 return isSImmPred(
911 [](int64_t Imm) { return Imm != 0 && isShiftedInt<6, 4>(Imm); });
912 }
913
914 bool isSImm16NonZero() const {
915 return isSImmPred([](int64_t Imm) { return Imm != 0 && isInt<16>(Imm); });
916 }
917
918 bool isUImm16NonZero() const {
919 return isUImmPred([](int64_t Imm) { return isUInt<16>(Imm) && Imm != 0; });
920 }
921
922 bool isSImm20LI() const {
923 if (!isExpr())
924 return false;
925
926 int64_t Imm;
927 if (evaluateConstantExpr(getExpr(), Imm))
928 return isInt<20>(fixImmediateForRV32(Imm, isRV64Expr()));
929
931 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
932 VK == RISCV::S_QC_ABS20;
933 }
934
935 bool isSImm8PLI_B() const { return isSImm<8>() || isUImm<8>(); }
936 bool isSImm10PLUI() const { return isSImm<10>() || isUImm<10>(); }
937
938 bool isSImm10PLI_H() const {
939 return isSImm<10>() || isUImmPred([](int64_t Imm) {
941 });
942 }
943 bool isSImm10PLI_W() const {
944 return isSImm<10>() || isUImmPred([](int64_t Imm) {
946 });
947 }
948
949 bool isUImm20LUI() const {
950 if (!isExpr())
951 return false;
952
953 int64_t Imm;
954 if (evaluateConstantExpr(getExpr(), Imm))
955 return isUInt<20>(Imm);
956
958 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
959 (VK == ELF::R_RISCV_HI20 || VK == ELF::R_RISCV_TPREL_HI20);
960 }
961
962 bool isUImm20AUIPC() const {
963 if (!isExpr())
964 return false;
965
966 int64_t Imm;
967 if (evaluateConstantExpr(getExpr(), Imm))
968 return isUInt<20>(Imm);
969
971 return RISCVAsmParser::classifySymbolRef(getExpr(), VK) &&
972 (VK == RISCV::S_PCREL_HI || VK == RISCV::S_GOT_HI ||
973 VK == ELF::R_RISCV_TLS_GOT_HI20 || VK == ELF::R_RISCV_TLS_GD_HI20 ||
974 VK == ELF::R_RISCV_TLSDESC_HI20);
975 }
976
977 bool isImmZero() const {
978 return isUImmPred([](int64_t Imm) { return 0 == Imm; });
979 }
980
981 bool isImmThree() const {
982 return isUImmPred([](int64_t Imm) { return 3 == Imm; });
983 }
984
985 bool isImmFour() const {
986 return isUImmPred([](int64_t Imm) { return 4 == Imm; });
987 }
988
989 bool isImm5Zibi() const {
990 return isUImmPred(
991 [](int64_t Imm) { return (Imm != 0 && isUInt<5>(Imm)) || Imm == -1; });
992 }
993
994 bool isSImm5Plus1() const {
995 return isSImmPred(
996 [](int64_t Imm) { return Imm != INT64_MIN && isInt<5>(Imm - 1); });
997 }
998
999 bool isSImm18Lsb0() const {
1000 return isSImmPred([](int64_t Imm) { return isShiftedInt<17, 1>(Imm); });
1001 }
1002
1003 bool isSImm19Lsb00() const {
1004 return isSImmPred([](int64_t Imm) { return isShiftedInt<17, 2>(Imm); });
1005 }
1006
1007 bool isSImm20Lsb000() const {
1008 return isSImmPred([](int64_t Imm) { return isShiftedInt<17, 3>(Imm); });
1009 }
1010
1011 bool isSImm32Lsb0() const {
1012 return isSImmPred([](int64_t Imm) { return isShiftedInt<31, 1>(Imm); });
1013 }
1014
1015 /// getStartLoc - Gets location of the first token of this operand
1016 SMLoc getStartLoc() const override { return StartLoc; }
1017 /// getEndLoc - Gets location of the last token of this operand
1018 SMLoc getEndLoc() const override { return EndLoc; }
1019
1020 /// True if this operand is for an RV64 instruction
1021 bool isRV64Expr() const {
1022 assert(Kind == KindTy::Expression && "Invalid type access!");
1023 return Expr.IsRV64;
1024 }
1025
1026 MCRegister getReg() const override {
1027 assert(Kind == KindTy::Register && "Invalid type access!");
1028 return Reg;
1029 }
1030
1031 StringRef getSysReg() const {
1032 assert(Kind == KindTy::SystemRegister && "Invalid type access!");
1033 return StringRef(SysReg.Data, SysReg.Length);
1034 }
1035
1036 const MCExpr *getExpr() const {
1037 assert(Kind == KindTy::Expression && "Invalid type access!");
1038 return Expr.Expr;
1039 }
1040
1041 uint64_t getFPConst() const {
1042 assert(Kind == KindTy::FPImmediate && "Invalid type access!");
1043 return FPImm.Val;
1044 }
1045
1046 StringRef getToken() const {
1047 assert(Kind == KindTy::Token && "Invalid type access!");
1048 return Tok;
1049 }
1050
1051 unsigned getVType() const {
1052 assert(Kind == KindTy::VType && "Invalid type access!");
1053 return VType.Val;
1054 }
1055
1056 RISCVFPRndMode::RoundingMode getFRM() const {
1057 assert(Kind == KindTy::FRM && "Invalid type access!");
1058 return FRM.FRM;
1059 }
1060
1061 unsigned getFence() const {
1062 assert(Kind == KindTy::Fence && "Invalid type access!");
1063 return Fence.Val;
1064 }
1065
1066 XSMTVTypeMode::SMTVTypeMode getSMTVType() const {
1067 assert(Kind == KindTy::SMTVType && "Invalid type access!");
1068 return SMTVType.SMTVType;
1069 }
1070
1071 void print(raw_ostream &OS, const MCAsmInfo &MAI) const override {
1072 const RISCVMCOptions &CLOpts = RISCV_MC::getCLOpts(MAI.getTargetOptions());
1073 auto RegName = [&](MCRegister Reg) {
1074 if (Reg)
1075 return RISCVInstPrinter::getRegisterName(CLOpts, Reg);
1076 else
1077 return "noreg";
1078 };
1079
1080 switch (Kind) {
1081 case KindTy::Expression:
1082 OS << "<imm: ";
1083 MAI.printExpr(OS, *Expr.Expr);
1084 OS << ' ' << (Expr.IsRV64 ? "rv64" : "rv32") << '>';
1085 break;
1086 case KindTy::FPImmediate:
1087 OS << "<fpimm: " << FPImm.Val << ">";
1088 break;
1089 case KindTy::Register:
1090 OS << "<reg: " << RegName(Reg) << " (" << Reg.id() << ")>";
1091 break;
1092 case KindTy::Token:
1093 OS << "'" << getToken() << "'";
1094 break;
1095 case KindTy::SystemRegister:
1096 OS << "<sysreg: " << getSysReg() << " (" << SysReg.Encoding << ")>";
1097 break;
1098 case KindTy::VType:
1099 OS << "<vtype: ";
1100 RISCVVType::printVType(getVType(), OS);
1101 OS << '>';
1102 break;
1103 case KindTy::FRM:
1104 OS << "<frm: ";
1105 OS << roundingModeToString(getFRM());
1106 OS << '>';
1107 break;
1108 case KindTy::SMTVType:
1109 OS << "<smtvtype: ";
1110 OS << SMTVTypeModeToString(getSMTVType());
1111 OS << '>';
1112 break;
1113 case KindTy::Fence:
1114 OS << "<fence: ";
1115 OS << getFence();
1116 OS << '>';
1117 break;
1118 case KindTy::RegList:
1119 OS << "<reglist: ";
1120 RISCVZC::printRegList(RegList.Encoding, OS);
1121 OS << '>';
1122 break;
1123 case KindTy::StackAdj:
1124 OS << "<stackadj: ";
1125 OS << StackAdj.Val;
1126 OS << '>';
1127 break;
1128 case KindTy::RegReg:
1129 OS << "<RegReg: BaseReg " << RegName(RegReg.BaseReg) << " OffsetReg "
1130 << RegName(RegReg.OffsetReg);
1131 break;
1132 }
1133 }
1134
1135 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S) {
1136 auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
1137 Op->Tok = Str;
1138 Op->StartLoc = S;
1139 Op->EndLoc = S;
1140 return Op;
1141 }
1142
1143 static std::unique_ptr<RISCVOperand> createReg(MCRegister Reg, SMLoc S,
1144 SMLoc E) {
1145 auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
1146 Op->Reg = Reg;
1147 Op->StartLoc = S;
1148 Op->EndLoc = E;
1149 return Op;
1150 }
1151
1152 static std::unique_ptr<RISCVOperand> createExpr(const MCExpr *Val, SMLoc S,
1153 SMLoc E, bool IsRV64) {
1154 auto Op = std::make_unique<RISCVOperand>(KindTy::Expression);
1155 Op->Expr.Expr = Val;
1156 Op->Expr.IsRV64 = IsRV64;
1157 Op->StartLoc = S;
1158 Op->EndLoc = E;
1159 return Op;
1160 }
1161
1162 static std::unique_ptr<RISCVOperand> createFPImm(uint64_t Val, SMLoc S) {
1163 auto Op = std::make_unique<RISCVOperand>(KindTy::FPImmediate);
1164 Op->FPImm.Val = Val;
1165 Op->StartLoc = S;
1166 Op->EndLoc = S;
1167 return Op;
1168 }
1169
1170 static std::unique_ptr<RISCVOperand> createSysReg(StringRef Str, SMLoc S,
1171 unsigned Encoding) {
1172 auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
1173 Op->SysReg.Data = Str.data();
1174 Op->SysReg.Length = Str.size();
1175 Op->SysReg.Encoding = Encoding;
1176 Op->StartLoc = S;
1177 Op->EndLoc = S;
1178 return Op;
1179 }
1180
1181 static std::unique_ptr<RISCVOperand>
1182 createFRMArg(RISCVFPRndMode::RoundingMode FRM, SMLoc S) {
1183 auto Op = std::make_unique<RISCVOperand>(KindTy::FRM);
1184 Op->FRM.FRM = FRM;
1185 Op->StartLoc = S;
1186 Op->EndLoc = S;
1187 return Op;
1188 }
1189
1190 static std::unique_ptr<RISCVOperand>
1191 createSMTVType(XSMTVTypeMode::SMTVTypeMode VType, SMLoc S) {
1192 auto Op = std::make_unique<RISCVOperand>(KindTy::SMTVType);
1193 Op->SMTVType.SMTVType = VType;
1194 Op->StartLoc = S;
1195 Op->EndLoc = S;
1196 return Op;
1197 }
1198
1199 static std::unique_ptr<RISCVOperand> createFenceArg(unsigned Val, SMLoc S) {
1200 auto Op = std::make_unique<RISCVOperand>(KindTy::Fence);
1201 Op->Fence.Val = Val;
1202 Op->StartLoc = S;
1203 Op->EndLoc = S;
1204 return Op;
1205 }
1206
1207 static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S) {
1208 auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
1209 Op->VType.Val = VTypeI;
1210 Op->StartLoc = S;
1211 Op->EndLoc = S;
1212 return Op;
1213 }
1214
1215 static std::unique_ptr<RISCVOperand> createRegList(unsigned RlistEncode,
1216 SMLoc S) {
1217 auto Op = std::make_unique<RISCVOperand>(KindTy::RegList);
1218 Op->RegList.Encoding = RlistEncode;
1219 Op->StartLoc = S;
1220 return Op;
1221 }
1222
1223 static std::unique_ptr<RISCVOperand>
1224 createRegReg(MCRegister BaseReg, MCRegister OffsetReg, SMLoc S) {
1225 auto Op = std::make_unique<RISCVOperand>(KindTy::RegReg);
1226 Op->RegReg.BaseReg = BaseReg;
1227 Op->RegReg.OffsetReg = OffsetReg;
1228 Op->StartLoc = S;
1229 Op->EndLoc = S;
1230 return Op;
1231 }
1232
1233 static std::unique_ptr<RISCVOperand> createStackAdj(unsigned StackAdj, SMLoc S) {
1234 auto Op = std::make_unique<RISCVOperand>(KindTy::StackAdj);
1235 Op->StackAdj.Val = StackAdj;
1236 Op->StartLoc = S;
1237 return Op;
1238 }
1239
1240 static void addExpr(MCInst &Inst, const MCExpr *Expr, bool IsRV64Imm) {
1241 assert(Expr && "Expr shouldn't be null!");
1242 int64_t Imm = 0;
1243 bool IsConstant = evaluateConstantExpr(Expr, Imm);
1244
1245 if (IsConstant)
1246 Inst.addOperand(
1247 MCOperand::createImm(fixImmediateForRV32(Imm, IsRV64Imm)));
1248 else
1250 }
1251
1252 // Used by the TableGen Code
1253 void addRegOperands(MCInst &Inst, unsigned N) const {
1254 assert(N == 1 && "Invalid number of operands!");
1256 }
1257
1258 void addGPRAsFPR16Operands(MCInst &Inst, unsigned N) const {
1259 assert(N == 1 && "Invalid number of operands!");
1260 Inst.addOperand(MCOperand::createReg(getReg() - RISCV::X0 + RISCV::X0_H));
1261 }
1262
1263 void addGPRAsFPR32Operands(MCInst &Inst, unsigned N) const {
1264 assert(N == 1 && "Invalid number of operands!");
1265 Inst.addOperand(MCOperand::createReg(getReg() - RISCV::X0 + RISCV::X0_W));
1266 }
1267
1268 void addGPRPairOperands(MCInst &Inst, unsigned N) const;
1269
1270 void addImmOperands(MCInst &Inst, unsigned N) const {
1271 assert(N == 1 && "Invalid number of operands!");
1272 addExpr(Inst, getExpr(), isRV64Expr());
1273 }
1274
1275 template <unsigned Bits>
1276 void addSExtImmOperands(MCInst &Inst, unsigned N) const {
1277 assert(N == 1 && "Invalid number of operands!");
1278 int64_t Imm;
1279 [[maybe_unused]] bool IsConstant = evaluateConstantExpr(getExpr(), Imm);
1280 assert(IsConstant);
1282 }
1283
1284 void addFPImmOperands(MCInst &Inst, unsigned N) const {
1285 assert(N == 1 && "Invalid number of operands!");
1286 if (isExpr()) {
1287 addExpr(Inst, getExpr(), isRV64Expr());
1288 return;
1289 }
1290
1292 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
1294 }
1295
1296 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
1297 assert(N == 1 && "Invalid number of operands!");
1299 }
1300
1301 void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1302 assert(N == 1 && "Invalid number of operands!");
1303 Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
1304 }
1305
1306 // Support non-canonical syntax:
1307 // "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
1308 // "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
1309 void addVTypeIOperands(MCInst &Inst, unsigned N) const {
1310 assert(N == 1 && "Invalid number of operands!");
1311 int64_t Imm = 0;
1312 if (Kind == KindTy::Expression) {
1313 [[maybe_unused]] bool IsConstantImm =
1314 evaluateConstantExpr(getExpr(), Imm);
1315 assert(IsConstantImm && "Invalid VTypeI Operand!");
1316 } else {
1317 Imm = getVType();
1318 }
1320 }
1321
1322 void addRegListOperands(MCInst &Inst, unsigned N) const {
1323 assert(N == 1 && "Invalid number of operands!");
1324 Inst.addOperand(MCOperand::createImm(RegList.Encoding));
1325 }
1326
1327 void addRegRegOperands(MCInst &Inst, unsigned N) const {
1328 assert(N == 2 && "Invalid number of operands!");
1329 Inst.addOperand(MCOperand::createReg(RegReg.BaseReg));
1330 Inst.addOperand(MCOperand::createReg(RegReg.OffsetReg));
1331 }
1332
1333 void addStackAdjOperands(MCInst &Inst, unsigned N) const {
1334 assert(N == 1 && "Invalid number of operands!");
1335 Inst.addOperand(MCOperand::createImm(StackAdj.Val));
1336 }
1337
1338 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
1339 assert(N == 1 && "Invalid number of operands!");
1340 Inst.addOperand(MCOperand::createImm(getFRM()));
1341 }
1342
1343 void addSMTVTypeOperand(MCInst &Inst, unsigned N) const {
1344 assert(N == 1 && "Invalid number of operands!");
1345 Inst.addOperand(MCOperand::createImm(getSMTVType()));
1346 }
1347};
1348} // end anonymous namespace.
1349
1350#define GET_REGISTER_MATCHER
1351#define GET_SUBTARGET_FEATURE_NAME
1352#define GET_MATCHER_IMPLEMENTATION
1353#define GET_MNEMONIC_SPELL_CHECKER
1354#include "RISCVGenAsmMatcher.inc"
1355
1356void RISCVOperand::addGPRPairOperands(MCInst &Inst, unsigned N) const {
1357 assert(N == 1 && "Invalid number of operands!");
1358 Inst.addOperand(MCOperand::createReg(convertToGPRPair(getReg())));
1359}
1360
1361bool RISCVAsmParser::generateImmOutOfRangeError(
1362 SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
1363 const Twine &Msg = "immediate must be an integer in the range") {
1364 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
1365}
1366
1367// Some diagnostics need to vary with subtarget features, so they are handled
1368// here. For example, several immediate ranges depend on whether the target is
1369// RV32 or RV64.
1370std::string RISCVAsmParser::getCustomOperandDiag(unsigned MatchError) {
1371 auto Range = [](int64_t Lower, int64_t Upper,
1372 StringRef Msg = "immediate must be an integer in the range") {
1373 return (Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]").str();
1374 };
1375
1376 switch (MatchError) {
1377 default:
1378 // For all other operand diagnostics, use the static string generated by
1379 // TableGen from the DiagnosticString field, if any.
1380 if (const char *Diag = getMatchKindDiag((RISCVMatchResultTy)MatchError))
1381 return Diag;
1382 return std::string();
1383 case Match_InvalidImmXLenLI:
1384 if (isRV64())
1385 return "operand must be a constant 64-bit integer";
1386 return Range(std::numeric_limits<int32_t>::min(),
1387 std::numeric_limits<uint32_t>::max());
1388 case Match_InvalidImmXLenLI_Restricted:
1389 if (isRV64())
1390 return "operand either must be a constant 64-bit integer "
1391 "or a bare symbol name";
1392 return Range(std::numeric_limits<int32_t>::min(),
1393 std::numeric_limits<uint32_t>::max(),
1394 "operand either must be a bare symbol name or an immediate "
1395 "integer in the range");
1396 case Match_InvalidUImmLog2XLen:
1397 if (isRV64())
1398 return Range(0, (1 << 6) - 1);
1399 return Range(0, (1 << 5) - 1);
1400 case Match_InvalidUImmLog2XLenNonZero:
1401 if (isRV64())
1402 return Range(1, (1 << 6) - 1);
1403 return Range(1, (1 << 5) - 1);
1404 case Match_InvalidUImm1:
1405 return Range(0, (1 << 1) - 1);
1406 case Match_InvalidUImm2:
1407 return Range(0, (1 << 2) - 1);
1408 case Match_InvalidUImm2Lsb0:
1409 return Range(0, 2, "immediate must be one of");
1410 case Match_InvalidUImm3:
1411 return Range(0, (1 << 3) - 1);
1412 case Match_InvalidUImm4:
1413 return Range(0, (1 << 4) - 1);
1414 case Match_InvalidUImm4Plus1:
1415 return Range(1, (1 << 4));
1416 case Match_InvalidUImm5:
1417 return Range(0, (1 << 5) - 1);
1418 case Match_InvalidUImm5NonZero:
1419 return Range(1, (1 << 5) - 1);
1420 case Match_InvalidUImm5GT3:
1421 return Range(4, (1 << 5) - 1);
1422 case Match_InvalidUImm5Plus1:
1423 return Range(1, (1 << 5));
1424 case Match_InvalidUImm5GE6Plus1:
1425 return Range(6, (1 << 5));
1426 case Match_InvalidUImm5Slist:
1427 return "immediate must be one of: 0, 1, 2, 4, 8, 15, 16, 31";
1428 case Match_InvalidUImm6:
1429 return Range(0, (1 << 6) - 1);
1430 case Match_InvalidUImm6Plus1:
1431 return Range(1, (1 << 6));
1432 case Match_InvalidUImm7:
1433 return Range(0, (1 << 7) - 1);
1434 case Match_InvalidUImm8:
1435 return Range(0, (1 << 8) - 1);
1436 case Match_InvalidUImm8GE32:
1437 return Range(32, (1 << 8) - 1);
1438 case Match_InvalidSImm5:
1439 return Range(-(1 << 4), (1 << 4) - 1);
1440 case Match_InvalidSImm5NonZero:
1441 return Range(-(1 << 4), (1 << 4) - 1,
1442 "immediate must be non-zero in the range");
1443 case Match_InvalidSImm6:
1444 return Range(-(1 << 5), (1 << 5) - 1);
1445 case Match_InvalidSImm6NonZero:
1446 return Range(-(1 << 5), (1 << 5) - 1,
1447 "immediate must be non-zero in the range");
1448 case Match_InvalidCLUIImm:
1449 return Range(1, (1 << 5) - 1, "immediate must be in [0xfffe0, 0xfffff] or");
1450 case Match_InvalidUImm5Lsb0:
1451 return Range(0, (1 << 5) - 2,
1452 "immediate must be a multiple of 2 bytes in the range");
1453 case Match_InvalidUImm6Lsb0:
1454 return Range(0, (1 << 6) - 2,
1455 "immediate must be a multiple of 2 bytes in the range");
1456 case Match_InvalidUImm6Lsb000:
1457 return Range(0, (1 << 6) - 8,
1458 "immediate must be a multiple of 8 in the range");
1459 case Match_InvalidUImm7Lsb00:
1460 return Range(0, (1 << 7) - 4,
1461 "immediate must be a multiple of 4 bytes in the range");
1462 case Match_InvalidUImm8Lsb00:
1463 return Range(0, (1 << 8) - 4,
1464 "immediate must be a multiple of 4 bytes in the range");
1465 case Match_InvalidUImm8Lsb000:
1466 return Range(0, (1 << 8) - 8,
1467 "immediate must be a multiple of 8 bytes in the range");
1468 case Match_InvalidUImm9:
1469 return Range(0, (1 << 9) - 1, "immediate offset must be in the range");
1470 case Match_InvalidBareSImm9Lsb0:
1471 return Range(-(1 << 8), (1 << 8) - 2,
1472 "immediate must be a multiple of 2 bytes in the range");
1473 case Match_InvalidUImm9Lsb000:
1474 return Range(0, (1 << 9) - 8,
1475 "immediate must be a multiple of 8 bytes in the range");
1476 case Match_InvalidUImm9Lsb0000:
1477 return Range(0, (1 << 9) - 16,
1478 "immediate must be a multiple of 16 bytes in the range");
1479 case Match_InvalidSImm8PLI_B:
1480 return Range(-(1 << 7), (1 << 8) - 1);
1481 case Match_InvalidSImm10:
1482 case Match_InvalidSImm10PLI_H:
1483 case Match_InvalidSImm10PLI_W:
1484 return Range(-(1 << 9), (1 << 9) - 1);
1485 case Match_InvalidSImm10PLUI:
1486 return Range(-(1 << 9), (1 << 10) - 1);
1487 case Match_InvalidUImm10Lsb00NonZero:
1488 return Range(4, (1 << 10) - 4,
1489 "immediate must be a multiple of 4 bytes in the range");
1490 case Match_InvalidUImm10Lsb0000:
1491 return Range(0, (1 << 10) - 16,
1492 "immediate must be a multiple of 16 bytes in the range");
1493 case Match_InvalidSImm10Lsb0000NonZero:
1494 return Range(
1495 -(1 << 9), (1 << 9) - 16,
1496 "immediate must be a multiple of 16 bytes and non-zero in the range");
1497 case Match_InvalidSImm11:
1498 return Range(-(1 << 10), (1 << 10) - 1);
1499 case Match_InvalidBareSImm11Lsb0:
1500 return Range(-(1 << 10), (1 << 10) - 2,
1501 "immediate must be a multiple of 2 bytes in the range");
1502 case Match_InvalidUImm10:
1503 return Range(0, (1 << 10) - 1);
1504 case Match_InvalidUImm11:
1505 return Range(0, (1 << 11) - 1);
1506 case Match_InvalidUImm14Lsb00:
1507 return Range(0, (1 << 14) - 4,
1508 "immediate must be a multiple of 4 bytes in the range");
1509 case Match_InvalidUImm16NonZero:
1510 return Range(1, (1 << 16) - 1);
1511 case Match_InvalidSImm12:
1512 return Range(-(1 << 11), (1 << 11) - 1);
1513 case Match_InvalidSImm12LO:
1514 return Range(-(1 << 11), (1 << 11) - 1,
1515 "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo "
1516 "specifier or an integer in the range");
1517 case Match_InvalidBareSImm12Lsb0:
1518 return Range(-(1 << 11), (1 << 11) - 2,
1519 "immediate must be a multiple of 2 bytes in the range");
1520 case Match_InvalidSImm12Lsb00000:
1521 return Range(-(1 << 11), (1 << 11) - 32,
1522 "immediate must be a multiple of 32 bytes in the range");
1523 case Match_InvalidBareSImm13Lsb0:
1524 return Range(-(1 << 12), (1 << 12) - 2,
1525 "immediate must be a multiple of 2 bytes in the range");
1526 case Match_InvalidSImm16:
1527 return Range(-(1 << 15), (1 << 15) - 1);
1528 case Match_InvalidSImm16NonZero:
1529 return Range(-(1 << 15), (1 << 15) - 1,
1530 "immediate must be non-zero in the range");
1531 case Match_InvalidSImm20LI:
1532 return Range(-(1 << 19), (1 << 19) - 1,
1533 "operand must be a symbol with a %qc.abs20 specifier or an "
1534 "integer in the range");
1535 case Match_InvalidUImm20LUI:
1536 return Range(0, (1 << 20) - 1,
1537 "operand must be a symbol with %hi/%tprel_hi specifier or an "
1538 "integer in the range");
1539 case Match_InvalidUImm20:
1540 return Range(0, (1 << 20) - 1);
1541 case Match_InvalidUImm20AUIPC:
1542 return Range(
1543 0, (1 << 20) - 1,
1544 "operand must be a symbol with a "
1545 "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi specifier "
1546 "or an integer in the range");
1547 case Match_InvalidBareSImm21Lsb0:
1548 return Range(-(1 << 20), (1 << 20) - 2,
1549 "immediate must be a multiple of 2 bytes in the range");
1550 case Match_InvalidCSRSystemRegister:
1551 return Range(0, (1 << 12) - 1,
1552 "operand must be a valid system register name or an integer "
1553 "in the range");
1554 case Match_InvalidImm5Zibi:
1555 return Range(-1, (1 << 5) - 1, "immediate must be non-zero in the range");
1556 case Match_InvalidVTypeI:
1557 return "operand must be "
1558 "e[8|8alt|16|16alt|32|64],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]";
1559 case Match_InvalidSImm5Plus1:
1560 return Range(-(1 << 4) + 1, (1 << 4), "immediate must be in the range");
1561 case Match_InvalidSImm18:
1562 return Range(-(1 << 17), (1 << 17) - 1);
1563 case Match_InvalidSImm18Lsb0:
1564 return Range(-(1 << 17), (1 << 17) - 2,
1565 "immediate must be a multiple of 2 bytes in the range");
1566 case Match_InvalidSImm19Lsb00:
1567 return Range(-(1 << 18), (1 << 18) - 4,
1568 "immediate must be a multiple of 4 bytes in the range");
1569 case Match_InvalidSImm20Lsb000:
1570 return Range(-(1 << 19), (1 << 19) - 8,
1571 "immediate must be a multiple of 8 bytes in the range");
1572 case Match_InvalidSImm26:
1573 return Range(-(1 << 25), (1 << 25) - 1);
1574 // HACK: See comment before `BareSymbolQC_E_LI` in RISCVInstrInfoXqci.td.
1575 case Match_InvalidBareSymbolQC_E_LI:
1576 [[fallthrough]];
1577 // END HACK
1578 case Match_InvalidBareSImm32:
1579 return Range(std::numeric_limits<int32_t>::min(),
1580 std::numeric_limits<uint32_t>::max());
1581 case Match_InvalidBareSImm32Lsb0:
1582 return Range(std::numeric_limits<int32_t>::min(),
1583 std::numeric_limits<int32_t>::max() - 1,
1584 "operand must be a multiple of 2 bytes in the range");
1585 case Match_InvalidRnumArg:
1586 return Range(0, 10);
1587 case Match_InvalidStackAdj:
1588 return "stack adjustment is invalid for this instruction and register "
1589 "list";
1590 case Match_InvalidYBNDSWImm:
1591 return "immediate must be an integer in the range "
1592 "[1, 255], a multiple of 8 in the range [256, 504], "
1593 "or a multiple of 16 in the range [512, 4096]";
1594 }
1595}
1596
1597// Process the list of near-misses, throwing away ones we don't want to report
1598// to the user, and converting the rest to a source location and string that
1599// should be reported.
1600void RISCVAsmParser::FilterNearMisses(
1601 SmallVectorImpl<NearMissInfo> &NearMissesIn,
1602 SmallVectorImpl<NearMissMessage> &NearMissesOut, SMLoc IDLoc,
1604 // Record some information about near-misses that we have already seen, so
1605 // that we can avoid reporting redundant ones.
1606 std::multimap<unsigned, unsigned> OperandMissesSeen;
1607 SmallSet<FeatureBitset, 4> FeatureMissesSeen;
1608 bool ReportedTooFewOperands = false;
1609 bool ReportedTooManyOperands = false;
1610
1611 for (NearMissInfo &I : NearMissesIn) {
1612 switch (I.getKind()) {
1614 SMLoc OperandLoc =
1615 ((RISCVOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
1616
1617 // When the matcher finds surplus operands, it records them as
1618 // NearMissOperand with InvalidMatchClass. We detect this and report
1619 // "unexpected extra operand" instead of "invalid operand".
1620 if (I.getOperandClass() == InvalidMatchClass) {
1621 if (!ReportedTooManyOperands) {
1622 NearMissesOut.emplace_back(NearMissMessage{
1623 OperandLoc, "unexpected extra operand for instruction"});
1624 ReportedTooManyOperands = true;
1625 }
1626 break;
1627 }
1628
1629 std::string OperandDiag = getCustomOperandDiag(I.getOperandError());
1630
1631 // If we have already emitted a message for a superclass on this operand,
1632 // don't also report the sub-class.
1633 unsigned DupCheckMatchClass =
1634 OperandDiag.empty() ? ~0U : I.getOperandClass();
1635 auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
1636 if (std::any_of(
1637 PrevReports.first, PrevReports.second,
1638 [DupCheckMatchClass](const std::pair<unsigned, unsigned> Pair) {
1639 if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
1640 return Pair.second == DupCheckMatchClass;
1641 return isSubclass((MatchClassKind)DupCheckMatchClass,
1642 (MatchClassKind)Pair.second);
1643 }))
1644 break;
1645 OperandMissesSeen.insert(
1646 std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
1647
1648 NearMissMessage Message;
1649 Message.Loc = OperandLoc;
1650 if (!OperandDiag.empty()) {
1651 Message.Message = OperandDiag;
1652 } else {
1653 Message.Message = "invalid operand for instruction";
1654 LLVM_DEBUG(
1655 dbgs() << "Missing diagnostic string for operand class "
1656 << getMatchClassName((MatchClassKind)I.getOperandClass())
1657 << I.getOperandClass() << ", error " << I.getOperandError()
1658 << ", opcode " << MII.getName(I.getOpcode()) << "\n");
1659 }
1660 NearMissesOut.emplace_back(Message);
1661 break;
1662 }
1664 const FeatureBitset &MissingFeatures = I.getFeatures();
1665 // Don't report the same set of features twice.
1666 if (!FeatureMissesSeen.insert(MissingFeatures).second)
1667 break;
1668
1669 NearMissMessage Message;
1670 Message.Loc = IDLoc;
1671 bool FirstFeature = true;
1672 Message.Message = "instruction requires the following:";
1673 for (unsigned Feature : MissingFeatures) {
1674 Message.Message += FirstFeature ? " " : ", ";
1675 Message.Message += getSubtargetFeatureName(Feature);
1676 FirstFeature = false;
1677 }
1678 NearMissesOut.emplace_back(Message);
1679 break;
1680 }
1682 // RISC-V does not define any target match predicates.
1683 llvm_unreachable("RISC-V has no target predicate near-misses");
1684 break;
1686 if (!ReportedTooFewOperands) {
1687 SMLoc EndLoc = ((RISCVOperand &)*Operands.back()).getEndLoc();
1688 NearMissesOut.emplace_back(
1689 NearMissMessage{EndLoc, "too few operands for instruction"});
1690 ReportedTooFewOperands = true;
1691 }
1692 break;
1693 }
1695 // This should never leave the matcher.
1696 llvm_unreachable("not a near-miss");
1697 break;
1698 }
1699 }
1700}
1701
1702void RISCVAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
1703 SMLoc IDLoc, OperandVector &Operands) {
1705 FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
1706
1707 if (Messages.empty()) {
1708 // No near-misses were found, so the best we can do is "invalid
1709 // instruction".
1710 Error(IDLoc, "invalid instruction");
1711 } else if (Messages.size() == 1) {
1712 // One near miss was found, report it as the sole error.
1713 Error(Messages[0].Loc, Messages[0].Message);
1714 } else {
1715 // More than one near miss, so report a generic "invalid instruction"
1716 // error, followed by notes for each of the near-misses.
1717 Error(IDLoc,
1718 "invalid instruction, any one of the following would fix this:");
1719 for (auto &M : Messages)
1720 Note(M.Loc, M.Message);
1721 }
1722}
1723
1724bool RISCVAsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1726 MCStreamer &Out,
1727 uint64_t &ErrorInfo,
1728 bool MatchingInlineAsm) {
1729 MCInst Inst;
1731
1732 auto Result =
1733 MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
1734 switch (Result) {
1735 default:
1736 break;
1737 case Match_Success:
1738 if (validateInstruction(Inst, Operands))
1739 return true;
1740 return processInstruction(Inst, IDLoc, Operands, Out);
1741 case Match_MnemonicFail: {
1742 FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1743 std::string Suggestion = RISCVMnemonicSpellCheck(
1744 ((RISCVOperand &)*Operands[0]).getToken(), FBS, 0);
1745 return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
1746 }
1747 case Match_NearMisses:
1748 ReportNearMisses(NearMisses, IDLoc, Operands);
1749 return true;
1750 }
1751
1752 llvm_unreachable("Unknown match type detected!");
1753}
1754
1755// Attempts to match Name as a register (either using the default name or
1756// alternative ABI names), returning the matching register. Upon failure,
1757// returns a non-valid MCRegister. If IsRVE, then registers x16-x31 will be
1758// rejected.
1759MCRegister RISCVAsmParser::matchRegisterNameHelper(StringRef Name) const {
1760 MCRegister Reg = MatchRegisterName(Name);
1761 // The 16-/32-/128- and 64-bit FPRs have the same asm name. Check
1762 // that the initial match always matches the 64-bit variant, and
1763 // not the 16/32/128-bit one.
1764 assert(!(Reg >= RISCV::F0_H && Reg <= RISCV::F31_H));
1765 assert(!(Reg >= RISCV::F0_F && Reg <= RISCV::F31_F));
1766 assert(!(Reg >= RISCV::F0_Q && Reg <= RISCV::F31_Q));
1767 // The default FPR register class is based on the tablegen enum ordering.
1768 static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1769 static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1770 static_assert(RISCV::F0_D < RISCV::F0_Q, "FPR matching must be updated");
1771 if (!Reg)
1772 Reg = MatchRegisterAltName(Name);
1773 if (isRVE() && Reg >= RISCV::X16 && Reg <= RISCV::X31)
1774 Reg = MCRegister();
1775 return Reg;
1776}
1777
1778bool RISCVAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1779 SMLoc &EndLoc) {
1780 if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
1781 return Error(StartLoc, "invalid register name");
1782 return false;
1783}
1784
1785ParseStatus RISCVAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1786 SMLoc &EndLoc) {
1787 const AsmToken &Tok = getParser().getTok();
1788 StartLoc = Tok.getLoc();
1789 EndLoc = Tok.getEndLoc();
1790 StringRef Name = getLexer().getTok().getIdentifier();
1791
1793 if (!Reg)
1794 return ParseStatus::NoMatch;
1795
1796 getParser().Lex(); // Eat identifier token.
1797 return ParseStatus::Success;
1798}
1799
1800ParseStatus RISCVAsmParser::parseRegister(OperandVector &Operands,
1801 bool AllowParens) {
1802 SMLoc FirstS = getLoc();
1803 bool HadParens = false;
1804 AsmToken LParen;
1805
1806 // If this is an LParen and a parenthesised register name is allowed, parse it
1807 // atomically.
1808 if (AllowParens && getLexer().is(AsmToken::LParen)) {
1809 AsmToken Buf[2];
1810 size_t ReadCount = getLexer().peekTokens(Buf);
1811 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1812 HadParens = true;
1813 LParen = getParser().getTok();
1814 getParser().Lex(); // Eat '('
1815 }
1816 }
1817
1818 switch (getLexer().getKind()) {
1819 default:
1820 if (HadParens)
1821 getLexer().UnLex(LParen);
1822 return ParseStatus::NoMatch;
1824 StringRef Name = getLexer().getTok().getIdentifier();
1825 MCRegister Reg = matchRegisterNameHelper(Name);
1826
1827 if (!Reg) {
1828 if (HadParens)
1829 getLexer().UnLex(LParen);
1830 return ParseStatus::NoMatch;
1831 }
1832 if (HadParens)
1833 Operands.push_back(RISCVOperand::createToken("(", FirstS));
1834 SMLoc S = getLoc();
1835 SMLoc E = getTok().getEndLoc();
1836 getLexer().Lex();
1837 Operands.push_back(RISCVOperand::createReg(Reg, S, E));
1838 }
1839
1840 if (HadParens) {
1841 getParser().Lex(); // Eat ')'
1842 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
1843 }
1844
1845 return ParseStatus::Success;
1846}
1847
1848ParseStatus RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
1849 SMLoc S = getLoc();
1850 SMLoc E;
1851 const MCExpr *Res;
1852
1853 switch (getLexer().getKind()) {
1854 default:
1855 return ParseStatus::NoMatch;
1856 case AsmToken::LParen:
1857 case AsmToken::Minus:
1858 case AsmToken::Plus:
1859 case AsmToken::Exclaim:
1860 case AsmToken::Tilde:
1861 case AsmToken::Integer:
1862 case AsmToken::String: {
1863 if (getParser().parseExpression(Res, E))
1864 return ParseStatus::Failure;
1865
1866 auto *CE = dyn_cast<MCConstantExpr>(Res);
1867 if (CE) {
1868 int64_t Imm = CE->getValue();
1869 if (isUInt<7>(Imm)) {
1870 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
1871 return ParseStatus::Success;
1872 }
1873 }
1874
1875 break;
1876 }
1877 case AsmToken::Identifier: {
1878 StringRef Identifier;
1879 if (getParser().parseIdentifier(Identifier))
1880 return ParseStatus::Failure;
1881
1882 auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Identifier);
1883 if (Opcode) {
1884 assert(isUInt<7>(Opcode->Value) && (Opcode->Value & 0x3) == 3 &&
1885 "Unexpected opcode");
1886 Res = MCConstantExpr::create(Opcode->Value, getContext());
1888 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
1889 return ParseStatus::Success;
1890 }
1891
1892 break;
1893 }
1894 case AsmToken::Percent:
1895 break;
1896 }
1897
1898 return generateImmOutOfRangeError(
1899 S, 0, 127,
1900 "opcode must be a valid opcode name or an immediate in the range");
1901}
1902
1903ParseStatus RISCVAsmParser::parseInsnCDirectiveOpcode(OperandVector &Operands) {
1904 SMLoc S = getLoc();
1905 SMLoc E;
1906 const MCExpr *Res;
1907
1908 switch (getLexer().getKind()) {
1909 default:
1910 return ParseStatus::NoMatch;
1911 case AsmToken::LParen:
1912 case AsmToken::Minus:
1913 case AsmToken::Plus:
1914 case AsmToken::Exclaim:
1915 case AsmToken::Tilde:
1916 case AsmToken::Integer:
1917 case AsmToken::String: {
1918 if (getParser().parseExpression(Res, E))
1919 return ParseStatus::Failure;
1920
1921 auto *CE = dyn_cast<MCConstantExpr>(Res);
1922 if (CE) {
1923 int64_t Imm = CE->getValue();
1924 if (Imm >= 0 && Imm <= 2) {
1925 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
1926 return ParseStatus::Success;
1927 }
1928 }
1929
1930 break;
1931 }
1932 case AsmToken::Identifier: {
1933 StringRef Identifier;
1934 if (getParser().parseIdentifier(Identifier))
1935 return ParseStatus::Failure;
1936
1937 unsigned Opcode;
1938 if (Identifier == "C0")
1939 Opcode = 0;
1940 else if (Identifier == "C1")
1941 Opcode = 1;
1942 else if (Identifier == "C2")
1943 Opcode = 2;
1944 else
1945 break;
1946
1947 Res = MCConstantExpr::create(Opcode, getContext());
1949 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
1950 return ParseStatus::Success;
1951 }
1952 case AsmToken::Percent: {
1953 // Discard operand with modifier.
1954 break;
1955 }
1956 }
1957
1958 return generateImmOutOfRangeError(
1959 S, 0, 2,
1960 "opcode must be a valid opcode name or an immediate in the range");
1961}
1962
1963ParseStatus RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1964 SMLoc S = getLoc();
1965 const MCExpr *Res;
1966
1967 auto SysRegFromConstantInt = [this](const MCExpr *E, SMLoc S) {
1968 if (auto *CE = dyn_cast<MCConstantExpr>(E)) {
1969 int64_t Imm = CE->getValue();
1970 if (isUInt<12>(Imm)) {
1971 auto Range = RISCVSysReg::lookupSysRegByEncoding(Imm);
1972 // Accept an immediate representing a named Sys Reg if it satisfies the
1973 // the required features.
1974 for (auto &Reg : Range) {
1975 if (Reg.IsAltName || Reg.IsDeprecatedName)
1976 continue;
1977 if (Reg.haveRequiredFeatures(STI->getFeatureBits()))
1978 return RISCVOperand::createSysReg(
1979 RISCVSysReg::getSysRegStr(Reg.Name), S, Imm);
1980 }
1981 // Accept an immediate representing an un-named Sys Reg if the range is
1982 // valid, regardless of the required features.
1983 return RISCVOperand::createSysReg("", S, Imm);
1984 }
1985 }
1986 return std::unique_ptr<RISCVOperand>();
1987 };
1988
1989 switch (getLexer().getKind()) {
1990 default:
1991 return ParseStatus::NoMatch;
1992 case AsmToken::LParen:
1993 case AsmToken::Minus:
1994 case AsmToken::Plus:
1995 case AsmToken::Exclaim:
1996 case AsmToken::Tilde:
1997 case AsmToken::Integer:
1998 case AsmToken::String: {
1999 if (getParser().parseExpression(Res))
2000 return ParseStatus::Failure;
2001
2002 if (auto SysOpnd = SysRegFromConstantInt(Res, S)) {
2003 Operands.push_back(std::move(SysOpnd));
2004 return ParseStatus::Success;
2005 }
2006
2007 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
2008 }
2009 case AsmToken::Identifier: {
2010 StringRef Identifier;
2011 if (getParser().parseIdentifier(Identifier))
2012 return ParseStatus::Failure;
2013
2014 const auto *SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
2015
2016 if (SysReg) {
2017 if (SysReg->IsDeprecatedName) {
2018 // Lookup the undeprecated name.
2019 auto Range = RISCVSysReg::lookupSysRegByEncoding(SysReg->Encoding);
2020 for (auto &Reg : Range) {
2021 if (Reg.IsAltName || Reg.IsDeprecatedName)
2022 continue;
2023 Warning(S, "'" + Identifier + "' is a deprecated alias for '" +
2024 RISCVSysReg::getSysRegStr(Reg.Name) + "'");
2025 }
2026 }
2027
2028 // Accept a named Sys Reg if the required features are present.
2029 const auto &FeatureBits = getSTI().getFeatureBits();
2030 const auto &AllFeatures = getSTI().getAllProcessorFeatures();
2031 if (!SysReg->haveRequiredFeatures(FeatureBits)) {
2032 const auto *Feature =
2033 llvm::find_if(AllFeatures, [&](const auto &Feature) {
2034 return SysReg->FeaturesRequired[Feature.Value];
2035 });
2036 std::string ErrorMsg =
2037 std::string("system register '") +
2038 std::string(RISCVSysReg::getSysRegStr(SysReg->Name)) + "' ";
2039 if (SysReg->IsRV32Only && FeatureBits[RISCV::Feature64Bit]) {
2040 ErrorMsg += "is RV32 only";
2041 if (Feature != std::end(AllFeatures))
2042 ErrorMsg += " and ";
2043 }
2044 if (Feature != std::end(AllFeatures)) {
2045 ErrorMsg +=
2046 "requires '" + std::string(Feature->key()) + "' to be enabled";
2047 }
2048
2049 return Error(S, ErrorMsg);
2050 }
2051 Operands.push_back(
2052 RISCVOperand::createSysReg(Identifier, S, SysReg->Encoding));
2053 return ParseStatus::Success;
2054 }
2055
2056 // Accept a symbol name that evaluates to an absolute value.
2057 MCSymbol *Sym = getContext().lookupSymbol(Identifier);
2058 if (Sym && Sym->isVariable()) {
2059 // Pass false for SetUsed, since redefining the value later does not
2060 // affect this instruction.
2061 if (auto SysOpnd = SysRegFromConstantInt(Sym->getVariableValue(), S)) {
2062 Operands.push_back(std::move(SysOpnd));
2063 return ParseStatus::Success;
2064 }
2065 }
2066
2067 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1,
2068 "operand must be a valid system register "
2069 "name or an integer in the range");
2070 }
2071 case AsmToken::Percent: {
2072 // Discard operand with modifier.
2073 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
2074 }
2075 }
2076
2077 return ParseStatus::NoMatch;
2078}
2079
2080ParseStatus RISCVAsmParser::parseFPImm(OperandVector &Operands) {
2081 SMLoc S = getLoc();
2082
2083 // Parse special floats (inf/nan/min) representation.
2084 if (getTok().is(AsmToken::Identifier)) {
2085 StringRef Identifier = getTok().getIdentifier();
2086 if (Identifier.compare_insensitive("inf") == 0) {
2087 Operands.push_back(
2088 RISCVOperand::createExpr(MCConstantExpr::create(30, getContext()), S,
2089 getTok().getEndLoc(), isRV64()));
2090 } else if (Identifier.compare_insensitive("nan") == 0) {
2091 Operands.push_back(
2092 RISCVOperand::createExpr(MCConstantExpr::create(31, getContext()), S,
2093 getTok().getEndLoc(), isRV64()));
2094 } else if (Identifier.compare_insensitive("min") == 0) {
2095 Operands.push_back(
2096 RISCVOperand::createExpr(MCConstantExpr::create(1, getContext()), S,
2097 getTok().getEndLoc(), isRV64()));
2098 } else {
2099 return TokError("invalid floating point literal");
2100 }
2101
2102 Lex(); // Eat the token.
2103
2104 return ParseStatus::Success;
2105 }
2106
2107 // Handle negation, as that still comes through as a separate token.
2108 bool IsNegative = parseOptionalToken(AsmToken::Minus);
2109
2110 const AsmToken &Tok = getTok();
2111 if (!Tok.is(AsmToken::Real))
2112 return TokError("invalid floating point immediate");
2113
2114 // Parse FP representation.
2115 APFloat RealVal(APFloat::IEEEdouble());
2116 auto StatusOrErr =
2117 RealVal.convertFromString(Tok.getString(), APFloat::rmTowardZero);
2118 if (errorToBool(StatusOrErr.takeError()))
2119 return TokError("invalid floating point representation");
2120
2121 if (IsNegative)
2122 RealVal.changeSign();
2123
2124 Operands.push_back(RISCVOperand::createFPImm(
2125 RealVal.bitcastToAPInt().getZExtValue(), S));
2126
2127 Lex(); // Eat the token.
2128
2129 return ParseStatus::Success;
2130}
2131
2132ParseStatus RISCVAsmParser::parseExpression(OperandVector &Operands) {
2133 SMLoc S = getLoc();
2134 SMLoc E;
2135 const MCExpr *Res;
2136
2137 switch (getLexer().getKind()) {
2138 default:
2139 return ParseStatus::NoMatch;
2140 case AsmToken::LParen:
2141 case AsmToken::Dot:
2142 case AsmToken::Minus:
2143 case AsmToken::Plus:
2144 case AsmToken::Exclaim:
2145 case AsmToken::Tilde:
2146 case AsmToken::Integer:
2147 case AsmToken::String:
2149 if (getParser().parseExpression(Res, E))
2150 return ParseStatus::Failure;
2151 break;
2152 case AsmToken::Percent:
2153 return parseOperandWithSpecifier(Operands);
2154 }
2155
2156 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
2157 return ParseStatus::Success;
2158}
2159
2160ParseStatus RISCVAsmParser::parseOperandWithSpecifier(OperandVector &Operands) {
2161 SMLoc S = getLoc();
2162 SMLoc E;
2163
2164 if (parseToken(AsmToken::Percent, "expected '%' relocation specifier"))
2165 return ParseStatus::Failure;
2166 const MCExpr *Expr = nullptr;
2167 bool Failed = parseExprWithSpecifier(Expr, E);
2168 if (!Failed)
2169 Operands.push_back(RISCVOperand::createExpr(Expr, S, E, isRV64()));
2170 return Failed;
2171}
2172
2173bool RISCVAsmParser::parseExprWithSpecifier(const MCExpr *&Res, SMLoc &E) {
2174 SMLoc Loc = getLoc();
2175 if (getLexer().getKind() != AsmToken::Identifier)
2176 return TokError("expected '%' relocation specifier");
2177 StringRef Identifier = getParser().getTok().getIdentifier();
2178 auto Spec = RISCV::parseSpecifierName(Identifier);
2179 if (!Spec)
2180 return TokError("invalid relocation specifier");
2181
2182 getParser().Lex(); // Eat the identifier
2183 if (parseToken(AsmToken::LParen, "expected '('"))
2184 return true;
2185
2186 const MCExpr *SubExpr;
2187 if (getParser().parseParenExpression(SubExpr, E))
2188 return true;
2189
2190 Res = MCSpecifierExpr::create(SubExpr, Spec, getContext(), Loc);
2191 return false;
2192}
2193
2194bool RISCVAsmParser::parseDataExpr(const MCExpr *&Res) {
2195 SMLoc E;
2196 if (parseOptionalToken(AsmToken::Percent))
2197 return parseExprWithSpecifier(Res, E);
2198 return getParser().parseExpression(Res);
2199}
2200
2201ParseStatus RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
2202 SMLoc S = getLoc();
2203 const MCExpr *Res;
2204
2205 if (getLexer().getKind() != AsmToken::Identifier)
2206 return ParseStatus::NoMatch;
2207
2208 StringRef Identifier = getTok().getIdentifier();
2209 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2210
2211 if (Sym->isVariable()) {
2212 const MCExpr *V = Sym->getVariableValue();
2213 if (!isa<MCSymbolRefExpr>(V))
2214 return ParseStatus::NoMatch;
2215 }
2216
2217 SMLoc E;
2218 if (getParser().parseExpression(Res, E))
2219 return ParseStatus::Failure;
2220
2221 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
2222 return ParseStatus::Success;
2223}
2224
2225ParseStatus RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
2226 SMLoc S = getLoc();
2227 const MCExpr *Res;
2228
2229 if (getLexer().getKind() != AsmToken::Identifier)
2230 return ParseStatus::NoMatch;
2231 std::string Identifier(getTok().getIdentifier());
2232
2233 if (getLexer().peekTok().is(AsmToken::At)) {
2234 Lex();
2235 Lex();
2236 StringRef PLT;
2237 SMLoc Loc = getLoc();
2238 if (getParser().parseIdentifier(PLT) || PLT != "plt")
2239 return Error(Loc, "@ (except the deprecated/ignored @plt) is disallowed");
2240 } else if (!getLexer().peekTok().is(AsmToken::EndOfStatement)) {
2241 // Avoid parsing the register in `call rd, foo` as a call symbol.
2242 return ParseStatus::NoMatch;
2243 } else {
2244 Lex();
2245 }
2246
2247 SMLoc E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
2249
2250 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2251 Res = MCSymbolRefExpr::create(Sym, getContext());
2252 Res = MCSpecifierExpr::create(Res, Kind, getContext());
2253 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
2254 return ParseStatus::Success;
2255}
2256
2257// Like parseCallSymbol but allows the symbol to be followed by a comma
2258// (for "tail address, register" form where the symbol is not the last operand).
2259ParseStatus RISCVAsmParser::parseTailCallSymbol(OperandVector &Operands) {
2260 SMLoc S = getLoc();
2261 const MCExpr *Res;
2262
2263 if (getLexer().getKind() != AsmToken::Identifier)
2264 return ParseStatus::NoMatch;
2265 std::string Identifier(getTok().getIdentifier());
2266
2267 if (getLexer().peekTok().is(AsmToken::At)) {
2268 Lex();
2269 Lex();
2270 StringRef PLT;
2271 SMLoc Loc = getLoc();
2272 if (getParser().parseIdentifier(PLT) || PLT != "plt")
2273 return Error(Loc, "@ (except the deprecated/ignored @plt) is disallowed");
2274 } else if (!getLexer().peekTok().is(AsmToken::EndOfStatement) &&
2275 !getLexer().peekTok().is(AsmToken::Comma)) {
2276 return ParseStatus::NoMatch;
2277 } else {
2278 Lex();
2279 }
2280
2281 SMLoc E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
2283
2284 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2285 Res = MCSymbolRefExpr::create(Sym, getContext());
2286 Res = MCSpecifierExpr::create(Res, Kind, getContext());
2287 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
2288 return ParseStatus::Success;
2289}
2290
2291ParseStatus RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
2292 SMLoc S = getLoc();
2293 SMLoc E;
2294 const MCExpr *Res;
2295
2296 if (getParser().parseExpression(Res, E))
2297 return ParseStatus::Failure;
2298
2299 if (Res->getKind() != MCExpr::ExprKind::SymbolRef)
2300 return Error(S, "operand must be a valid jump target");
2301
2303 Operands.push_back(RISCVOperand::createExpr(Res, S, E, isRV64()));
2304 return ParseStatus::Success;
2305}
2306
2307ParseStatus RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
2308 // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
2309 // both being acceptable forms. When parsing `jal ra, foo` this function
2310 // will be called for the `ra` register operand in an attempt to match the
2311 // single-operand alias. parseJALOffset must fail for this case. It would
2312 // seem logical to try parse the operand using parseExpression and return
2313 // NoMatch if the next token is a comma (meaning we must be parsing a jal in
2314 // the second form rather than the first). We can't do this as there's no
2315 // way of rewinding the lexer state. Instead, return NoMatch if this operand
2316 // is an identifier and is followed by a comma.
2317 if (getLexer().is(AsmToken::Identifier) &&
2318 getLexer().peekTok().is(AsmToken::Comma))
2319 return ParseStatus::NoMatch;
2320
2321 return parseExpression(Operands);
2322}
2323
2324bool RISCVAsmParser::parseVTypeToken(const AsmToken &Tok, VTypeState &State,
2325 unsigned &Sew, unsigned &Lmul,
2326 bool &Fractional, bool &TailAgnostic,
2327 bool &MaskAgnostic, bool &AltFmt) {
2328 if (Tok.isNot(AsmToken::Identifier))
2329 return true;
2330
2331 StringRef Identifier = Tok.getIdentifier();
2332 if (State < VTypeState::SeenSew && Identifier.consume_front("e")) {
2333 if (Identifier.getAsInteger(10, Sew)) {
2334 if (Identifier == "16alt") {
2335 AltFmt = true;
2336 Sew = 16;
2337 } else if (Identifier == "8alt") {
2338 AltFmt = true;
2339 Sew = 8;
2340 } else {
2341 return true;
2342 }
2343 }
2344 if (!RISCVVType::isValidSEW(Sew))
2345 return true;
2346
2347 State = VTypeState::SeenSew;
2348 return false;
2349 }
2350
2351 if (State < VTypeState::SeenLmul && Identifier.consume_front("m")) {
2352 // Might arrive here if lmul and tail policy unspecified, if so we're
2353 // parsing a MaskPolicy not an LMUL.
2354 if (Identifier == "a" || Identifier == "u") {
2355 MaskAgnostic = (Identifier == "a");
2356 State = VTypeState::SeenMaskPolicy;
2357 return false;
2358 }
2359
2360 Fractional = Identifier.consume_front("f");
2361 if (Identifier.getAsInteger(10, Lmul))
2362 return true;
2363 if (!RISCVVType::isValidLMUL(Lmul, Fractional))
2364 return true;
2365
2366 if (Fractional) {
2367 unsigned ELEN = STI->hasFeature(RISCV::FeatureStdExtZve64x) ? 64 : 32;
2368 unsigned MinLMUL = ELEN / 8;
2369 if (Lmul > MinLMUL)
2370 Warning(Tok.getLoc(),
2371 "use of vtype encodings with LMUL < SEWMIN/ELEN == mf" +
2372 Twine(MinLMUL) + " is reserved");
2373 }
2374
2375 State = VTypeState::SeenLmul;
2376 return false;
2377 }
2378
2379 if (State < VTypeState::SeenTailPolicy && Identifier.starts_with("t")) {
2380 if (Identifier == "ta")
2381 TailAgnostic = true;
2382 else if (Identifier == "tu")
2383 TailAgnostic = false;
2384 else
2385 return true;
2386
2387 State = VTypeState::SeenTailPolicy;
2388 return false;
2389 }
2390
2391 if (State < VTypeState::SeenMaskPolicy && Identifier.starts_with("m")) {
2392 if (Identifier == "ma")
2393 MaskAgnostic = true;
2394 else if (Identifier == "mu")
2395 MaskAgnostic = false;
2396 else
2397 return true;
2398
2399 State = VTypeState::SeenMaskPolicy;
2400 return false;
2401 }
2402
2403 return true;
2404}
2405
2406ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2407 SMLoc S = getLoc();
2408
2409 // Default values
2410 unsigned Sew = 8;
2411 unsigned Lmul = 1;
2412 bool Fractional = false;
2413 bool TailAgnostic = false;
2414 bool MaskAgnostic = false;
2415 bool AltFmt = false;
2416
2417 VTypeState State = VTypeState::SeenNothingYet;
2418 do {
2419 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2420 MaskAgnostic, AltFmt)) {
2421 // The first time, errors return NoMatch rather than Failure
2422 if (State == VTypeState::SeenNothingYet)
2423 return ParseStatus::NoMatch;
2424 break;
2425 }
2426
2427 getLexer().Lex();
2428 } while (parseOptionalToken(AsmToken::Comma));
2429
2430 if (!getLexer().is(AsmToken::EndOfStatement) ||
2431 State == VTypeState::SeenNothingYet)
2432 return generateVTypeError(S);
2433
2435 if (Fractional) {
2436 unsigned ELEN = STI->hasFeature(RISCV::FeatureStdExtZve64x) ? 64 : 32;
2437 unsigned MaxSEW = ELEN / Lmul;
2438 // If MaxSEW < 8, we should have printed warning about reserved LMUL.
2439 if (MaxSEW >= 8 && Sew > MaxSEW)
2440 Warning(S, "use of vtype encodings with SEW > " + Twine(MaxSEW) +
2441 " and LMUL == mf" + Twine(Lmul) +
2442 " may not be compatible with all RVV implementations");
2443 }
2444
2445 unsigned VTypeI =
2446 RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic, AltFmt);
2447 Operands.push_back(RISCVOperand::createVType(VTypeI, S));
2448 return ParseStatus::Success;
2449}
2450
2451bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2452 return Error(ErrorLoc,
2453 "operand must be "
2454 "e[8|8alt|16|16alt|32|64],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2455}
2456
2457ParseStatus RISCVAsmParser::parseXSfmmVType(OperandVector &Operands) {
2458 SMLoc S = getLoc();
2459
2460 unsigned Widen = 0;
2461 unsigned SEW = 0;
2462 bool AltFmt = false;
2463 StringRef Identifier;
2464
2465 if (getTok().isNot(AsmToken::Identifier))
2466 goto Fail;
2467
2468 Identifier = getTok().getIdentifier();
2469
2470 if (!Identifier.consume_front("e"))
2471 goto Fail;
2472
2473 if (Identifier.getAsInteger(10, SEW)) {
2474 if (Identifier != "16alt")
2475 goto Fail;
2476
2477 AltFmt = true;
2478 SEW = 16;
2479 }
2480 if (!RISCVVType::isValidSEW(SEW))
2481 goto Fail;
2482
2483 Lex();
2484
2485 if (!parseOptionalToken(AsmToken::Comma))
2486 goto Fail;
2487
2488 if (getTok().isNot(AsmToken::Identifier))
2489 goto Fail;
2490
2491 Identifier = getTok().getIdentifier();
2492
2493 if (!Identifier.consume_front("w"))
2494 goto Fail;
2495 if (Identifier.getAsInteger(10, Widen))
2496 goto Fail;
2497 if (Widen != 1 && Widen != 2 && Widen != 4)
2498 goto Fail;
2499
2500 Lex();
2501
2502 if (getLexer().is(AsmToken::EndOfStatement)) {
2503 Operands.push_back(RISCVOperand::createVType(
2504 RISCVVType::encodeXSfmmVType(SEW, Widen, AltFmt), S));
2505 return ParseStatus::Success;
2506 }
2507
2508Fail:
2509 return generateXSfmmVTypeError(S);
2510}
2511
2512bool RISCVAsmParser::generateXSfmmVTypeError(SMLoc ErrorLoc) {
2513 return Error(ErrorLoc, "operand must be e[8|16|16alt|32|64],w[1|2|4]");
2514}
2515
2516ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2517 if (getLexer().isNot(AsmToken::Identifier))
2518 return ParseStatus::NoMatch;
2519
2520 StringRef Name = getLexer().getTok().getIdentifier();
2521 if (!Name.consume_back(".t")) {
2522 // Non-register identifiers may belong to another optional operand in an
2523 // overloaded mnemonic. Let the matcher try those alternatives.
2524 if (matchRegisterNameHelper(Name))
2525 return Error(getLoc(), "expected '.t' suffix");
2526 return ParseStatus::NoMatch;
2527 }
2528 MCRegister Reg = matchRegisterNameHelper(Name);
2529
2530 if (!Reg)
2531 return ParseStatus::NoMatch;
2532 if (Reg != RISCV::V0)
2533 return ParseStatus::NoMatch;
2534 SMLoc S = getLoc();
2535 SMLoc E = getTok().getEndLoc();
2536 getLexer().Lex();
2537 Operands.push_back(RISCVOperand::createReg(Reg, S, E));
2538 return ParseStatus::Success;
2539}
2540
2541ParseStatus RISCVAsmParser::parseVScaleReg(OperandVector &Operands) {
2542 if (getLexer().isNot(AsmToken::Identifier))
2543 return ParseStatus::NoMatch;
2544
2545 StringRef Name = getLexer().getTok().getIdentifier();
2546 if (!Name.consume_back(".scale"))
2547 return Error(getLoc(), "expected '.scale' suffix");
2548 MCRegister Reg = matchRegisterNameHelper(Name);
2549
2550 if (!Reg)
2551 return ParseStatus::NoMatch;
2552 if (Reg != RISCV::V0)
2553 return ParseStatus::NoMatch;
2554 SMLoc S = getLoc();
2555 SMLoc E = getTok().getEndLoc();
2556 getLexer().Lex();
2557 Operands.push_back(RISCVOperand::createReg(Reg, S, E));
2558 return ParseStatus::Success;
2559}
2560
2561ParseStatus RISCVAsmParser::parseTileLambda(OperandVector &Operands) {
2562 if (getLexer().isNot(AsmToken::Identifier))
2563 return ParseStatus::NoMatch;
2564
2565 SMLoc S = getLoc();
2566 StringRef Name = getLexer().getTok().getIdentifier();
2567 if (!Name.consume_front("L") && !Name.consume_front("l"))
2568 return ParseStatus::NoMatch;
2569
2570 unsigned Lambda;
2571 if (Name.getAsInteger(10, Lambda) || !isPowerOf2_32(Lambda) || Lambda >= 128)
2572 return Error(S, "operand must be L1, L2, L4, L8, L16, L32, or L64");
2573
2574 unsigned EncodedLambda = Log2_32(Lambda) + 1;
2575
2576 SMLoc E = getTok().getEndLoc();
2577 getLexer().Lex();
2578 Operands.push_back(RISCVOperand::createExpr(
2579 MCConstantExpr::create(EncodedLambda, getContext()), S, E, isRV64()));
2580 return ParseStatus::Success;
2581}
2582
2583ParseStatus RISCVAsmParser::parseSMTVType(OperandVector &Operands) {
2584 if (getLexer().isNot(AsmToken::Identifier))
2585 return TokError(
2586 "operand must be a valid SpacemiT's Integer Matrix VType mnemonic");
2587
2588 StringRef Str = getLexer().getTok().getIdentifier();
2590
2591 if (!isValidSMTVTypeMode(VType))
2592 return TokError("SpacemiT's Integer Matrix only supports [i4|i8] mode");
2593
2594 Operands.push_back(RISCVOperand::createSMTVType(VType, getLoc()));
2595 Lex(); // Eat identifier token.
2596 return ParseStatus::Success;
2597}
2598
2599ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2600 if (getLexer().isNot(AsmToken::Identifier))
2601 return TokError(
2602 "operand must be a valid floating point rounding mode mnemonic");
2603
2604 StringRef Str = getLexer().getTok().getIdentifier();
2606
2607 if (FRM == RISCVFPRndMode::Invalid)
2608 return TokError(
2609 "operand must be a valid floating point rounding mode mnemonic");
2610
2611 Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
2612 Lex(); // Eat identifier token.
2613 return ParseStatus::Success;
2614}
2615
2616std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultSMTVType() {
2617 return RISCVOperand::createSMTVType(XSMTVTypeMode::SMTVTypeMode::SMT_I8,
2618 SMLoc());
2619}
2620
2621ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2622 const AsmToken &Tok = getLexer().getTok();
2623
2624 if (Tok.is(AsmToken::Integer)) {
2625 if (Tok.getIntVal() != 0)
2626 goto ParseFail;
2627
2628 Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
2629 Lex();
2630 return ParseStatus::Success;
2631 }
2632
2633 if (Tok.is(AsmToken::Identifier)) {
2634 StringRef Str = Tok.getIdentifier();
2635
2636 // Letters must be unique, taken from 'iorw', and in ascending order. This
2637 // holds as long as each individual character is one of 'iorw' and is
2638 // greater than the previous character.
2639 unsigned Imm = 0;
2640 bool Valid = true;
2641 char Prev = '\0';
2642 for (char c : Str) {
2643 switch (c) {
2644 default:
2645 Valid = false;
2646 break;
2647 case 'i':
2649 break;
2650 case 'o':
2652 break;
2653 case 'r':
2655 break;
2656 case 'w':
2658 break;
2659 }
2660
2661 if (c <= Prev) {
2662 Valid = false;
2663 break;
2664 }
2665 Prev = c;
2666 }
2667
2668 if (!Valid)
2669 goto ParseFail;
2670
2671 Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
2672 Lex();
2673 return ParseStatus::Success;
2674 }
2675
2676ParseFail:
2677 return TokError("operand must be formed of letters selected in-order from "
2678 "'iorw' or be 0");
2679}
2680
2681ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2682 if (parseToken(AsmToken::LParen, "expected '('"))
2683 return ParseStatus::Failure;
2684 Operands.push_back(RISCVOperand::createToken("(", getLoc()));
2685
2686 if (!parseRegister(Operands).isSuccess())
2687 return Error(getLoc(), "expected register");
2688
2689 if (parseToken(AsmToken::RParen, "expected ')'"))
2690 return ParseStatus::Failure;
2691 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
2692
2693 return ParseStatus::Success;
2694}
2695
2696ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2697 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2698 // as one of their register operands, such as `(a0)`. This just denotes that
2699 // the register (in this case `a0`) contains a memory address.
2700 //
2701 // Normally, we would be able to parse these by putting the parens into the
2702 // instruction string. However, GNU as also accepts a zero-offset memory
2703 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2704 // with parseExpression followed by parseMemOpBaseReg, but these instructions
2705 // do not accept an immediate operand, and we do not want to add a "dummy"
2706 // operand that is silently dropped.
2707 //
2708 // Instead, we use this custom parser. This will: allow (and discard) an
2709 // offset if it is zero; require (and discard) parentheses; and add only the
2710 // parsed register operand to `Operands`.
2711 //
2712 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2713 // which will only print the register surrounded by parentheses (which GNU as
2714 // also uses as its canonical representation for these operands).
2715 std::unique_ptr<RISCVOperand> OptionalImmOp;
2716
2717 if (getLexer().isNot(AsmToken::LParen)) {
2718 // Parse an Integer token. We do not accept arbitrary constant expressions
2719 // in the offset field (because they may include parens, which complicates
2720 // parsing a lot).
2721 int64_t ImmVal;
2722 SMLoc ImmStart = getLoc();
2723 if (getParser().parseIntToken(ImmVal,
2724 "expected '(' or optional integer offset"))
2725 return ParseStatus::Failure;
2726
2727 // Create a RISCVOperand for checking later (so the error messages are
2728 // nicer), but we don't add it to Operands.
2729 SMLoc ImmEnd = getLoc();
2730 OptionalImmOp =
2731 RISCVOperand::createExpr(MCConstantExpr::create(ImmVal, getContext()),
2732 ImmStart, ImmEnd, isRV64());
2733 }
2734
2735 if (parseToken(AsmToken::LParen,
2736 OptionalImmOp ? "expected '(' after optional integer offset"
2737 : "expected '(' or optional integer offset"))
2738 return ParseStatus::Failure;
2739
2740 if (!parseRegister(Operands).isSuccess())
2741 return Error(getLoc(), "expected register");
2742
2743 if (parseToken(AsmToken::RParen, "expected ')'"))
2744 return ParseStatus::Failure;
2745
2746 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2747 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2748 return Error(
2749 OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
2750 SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2751
2752 return ParseStatus::Success;
2753}
2754
2755ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2756 // RR : a2(a1)
2757 if (getLexer().getKind() != AsmToken::Identifier)
2758 return ParseStatus::NoMatch;
2759
2760 SMLoc S = getLoc();
2761 StringRef OffsetRegName = getLexer().getTok().getIdentifier();
2762 MCRegister OffsetReg = matchRegisterNameHelper(OffsetRegName);
2763 if (!OffsetReg ||
2764 !getRISCVMCRegisterClass(RISCV::GPRRegClassID).contains(OffsetReg))
2765 return Error(getLoc(), "expected GPR register");
2766 getLexer().Lex();
2767
2768 if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
2769 return ParseStatus::Failure;
2770
2771 if (getLexer().getKind() != AsmToken::Identifier)
2772 return Error(getLoc(), "expected GPR register");
2773
2774 StringRef BaseRegName = getLexer().getTok().getIdentifier();
2775 MCRegister BaseReg = matchRegisterNameHelper(BaseRegName);
2776 if (!BaseReg ||
2777 !getRISCVMCRegisterClass(RISCV::GPRRegClassID).contains(BaseReg))
2778 return Error(getLoc(), "expected GPR register");
2779 getLexer().Lex();
2780
2781 if (parseToken(AsmToken::RParen, "expected ')'"))
2782 return ParseStatus::Failure;
2783
2784 Operands.push_back(RISCVOperand::createRegReg(BaseReg, OffsetReg, S));
2785
2786 return ParseStatus::Success;
2787}
2788
2789// RegList: {ra [, s0[-sN]]}
2790// XRegList: {x1 [, x8[-x9][, x18[-xN]]]}
2791
2792// When MustIncludeS0 = true (not the default) (used for `qc.cm.pushfp`) which
2793// must include `fp`/`s0` in the list:
2794// RegList: {ra, s0[-sN]}
2795// XRegList: {x1, x8[-x9][, x18[-xN]]}
2796ParseStatus RISCVAsmParser::parseRegList(OperandVector &Operands,
2797 bool MustIncludeS0) {
2798 if (getTok().isNot(AsmToken::LCurly))
2799 return ParseStatus::NoMatch;
2800
2801 SMLoc S = getLoc();
2802
2803 Lex();
2804
2805 bool UsesXRegs;
2806 MCRegister RegEnd;
2807 do {
2808 if (getTok().isNot(AsmToken::Identifier))
2809 return Error(getLoc(), "invalid register");
2810
2811 StringRef RegName = getTok().getIdentifier();
2812 MCRegister Reg = matchRegisterNameHelper(RegName);
2813 if (!Reg)
2814 return Error(getLoc(), "invalid register");
2815
2816 if (!RegEnd) {
2817 UsesXRegs = RegName[0] == 'x';
2818 if (Reg != RISCV::X1)
2819 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2820 } else if (RegEnd == RISCV::X1) {
2821 if (Reg != RISCV::X8 || (UsesXRegs != (RegName[0] == 'x')))
2822 return Error(getLoc(), Twine("register must be '") +
2823 (UsesXRegs ? "x8" : "s0") + "'");
2824 } else if (RegEnd == RISCV::X9 && UsesXRegs) {
2825 if (Reg != RISCV::X18 || (RegName[0] != 'x'))
2826 return Error(getLoc(), "register must be 'x18'");
2827 } else {
2828 return Error(getLoc(), "too many register ranges");
2829 }
2830
2831 RegEnd = Reg;
2832
2833 Lex();
2834
2835 SMLoc MinusLoc = getLoc();
2836 if (parseOptionalToken(AsmToken::Minus)) {
2837 if (RegEnd == RISCV::X1)
2838 return Error(MinusLoc, Twine("register '") + (UsesXRegs ? "x1" : "ra") +
2839 "' cannot start a multiple register range");
2840
2841 if (getTok().isNot(AsmToken::Identifier))
2842 return Error(getLoc(), "invalid register");
2843
2844 StringRef RegName = getTok().getIdentifier();
2845 MCRegister Reg = matchRegisterNameHelper(RegName);
2846 if (!Reg)
2847 return Error(getLoc(), "invalid register");
2848
2849 if (RegEnd == RISCV::X8) {
2850 if ((Reg != RISCV::X9 &&
2851 (UsesXRegs || Reg < RISCV::X18 || Reg > RISCV::X27)) ||
2852 (UsesXRegs != (RegName[0] == 'x'))) {
2853 if (UsesXRegs)
2854 return Error(getLoc(), "register must be 'x9'");
2855 return Error(getLoc(), "register must be in the range 's1' to 's11'");
2856 }
2857 } else if (RegEnd == RISCV::X18) {
2858 if (Reg < RISCV::X19 || Reg > RISCV::X27 || (RegName[0] != 'x'))
2859 return Error(getLoc(),
2860 "register must be in the range 'x19' to 'x27'");
2861 } else
2862 llvm_unreachable("unexpected register");
2863
2864 RegEnd = Reg;
2865
2866 Lex();
2867 }
2868 } while (parseOptionalToken(AsmToken::Comma));
2869
2870 if (parseToken(AsmToken::RCurly, "expected ',' or '}'"))
2871 return ParseStatus::Failure;
2872
2873 if (RegEnd == RISCV::X26)
2874 return Error(S, "invalid register list, '{ra, s0-s10}' or '{x1, x8-x9, "
2875 "x18-x26}' is not supported");
2876
2877 auto Encode = RISCVZC::encodeRegList(RegEnd, isRVE());
2878 assert(Encode != RISCVZC::INVALID_RLIST);
2879
2880 if (MustIncludeS0 && Encode == RISCVZC::RA)
2881 return Error(S, "register list must include 's0' or 'x8'");
2882
2883 Operands.push_back(RISCVOperand::createRegList(Encode, S));
2884
2885 return ParseStatus::Success;
2886}
2887
2888ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
2889 bool ExpectNegative) {
2890 SMLoc S = getLoc();
2891 bool Negative = parseOptionalToken(AsmToken::Minus);
2892
2893 if (getTok().isNot(AsmToken::Integer))
2894 return ParseStatus::NoMatch;
2895
2896 int64_t StackAdjustment = getTok().getIntVal();
2897
2898 auto *RegListOp = static_cast<RISCVOperand *>(Operands.back().get());
2899 if (!RegListOp->isRegList())
2900 return ParseStatus::NoMatch;
2901
2902 unsigned RlistEncode = RegListOp->RegList.Encoding;
2903
2904 assert(RlistEncode != RISCVZC::INVALID_RLIST);
2905 unsigned StackAdjBase = RISCVZC::getStackAdjBase(RlistEncode, isRV64());
2906 if (Negative != ExpectNegative || StackAdjustment % 16 != 0 ||
2907 StackAdjustment < StackAdjBase || (StackAdjustment - StackAdjBase) > 48) {
2908 int64_t Lower = StackAdjBase;
2909 int64_t Upper = StackAdjBase + 48;
2910 if (ExpectNegative) {
2911 Lower = -Lower;
2912 Upper = -Upper;
2914 }
2915 return generateImmOutOfRangeError(S, Lower, Upper,
2916 "stack adjustment for register list must "
2917 "be a multiple of 16 bytes in the range");
2918 }
2919
2920 unsigned StackAdj = (StackAdjustment - StackAdjBase);
2921 Operands.push_back(RISCVOperand::createStackAdj(StackAdj, S));
2922 Lex();
2923 return ParseStatus::Success;
2924}
2925
2926/// Looks at a token type and creates the relevant operand from this
2927/// information, adding to Operands. If operand was parsed, returns false, else
2928/// true.
2929bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2930 // Check if the current operand has a custom associated parser, if so, try to
2931 // custom parse the operand, or fallback to the general approach.
2932 ParseStatus Result =
2933 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
2934 if (Result.isSuccess())
2935 return false;
2936 if (Result.isFailure())
2937 return true;
2938
2939 // Attempt to parse token as a register.
2940 if (parseRegister(Operands, true).isSuccess())
2941 return false;
2942
2943 // Attempt to parse token as an expression
2944 if (parseExpression(Operands).isSuccess()) {
2945 // Parse memory base register if present
2946 if (getLexer().is(AsmToken::LParen))
2947 return !parseMemOpBaseReg(Operands).isSuccess();
2948 return false;
2949 }
2950
2951 // Finally we have exhausted all options and must declare defeat.
2952 Error(getLoc(), "unknown operand");
2953 return true;
2954}
2955
2956bool RISCVAsmParser::parseInstruction(ParseInstructionInfo &Info,
2957 StringRef Name, SMLoc NameLoc,
2959 // Apply mnemonic aliases because the destination mnemonic may have require
2960 // custom operand parsing. The generic tblgen'erated code does this later, at
2961 // the start of MatchInstructionImpl(), but that's too late for custom
2962 // operand parsing.
2963 const FeatureBitset &AvailableFeatures = getAvailableFeatures();
2964 applyMnemonicAliases(Name, AvailableFeatures, 0);
2965
2966 // First operand is token for instruction
2967 Operands.push_back(RISCVOperand::createToken(Name, NameLoc));
2968
2969 // If there are no more operands, then finish
2970 if (getLexer().is(AsmToken::EndOfStatement)) {
2971 getParser().Lex(); // Consume the EndOfStatement.
2972 return false;
2973 }
2974
2975 // Parse first operand
2976 if (parseOperand(Operands, Name))
2977 return true;
2978
2979 // Parse until end of statement, consuming commas between operands
2980 while (parseOptionalToken(AsmToken::Comma)) {
2981 // Parse next operand
2982 if (parseOperand(Operands, Name))
2983 return true;
2984 }
2985
2986 if (getParser().parseEOL("unexpected token")) {
2987 getParser().eatToEndOfStatement();
2988 return true;
2989 }
2990 return false;
2991}
2992
2993bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2994 RISCV::Specifier &Kind) {
2996 if (const auto *RE = dyn_cast<MCSpecifierExpr>(Expr)) {
2997 Kind = RE->getSpecifier();
2998 Expr = RE->getSubExpr();
2999 }
3000
3001 MCValue Res;
3002 if (Expr->evaluateAsRelocatable(Res, nullptr))
3003 return Res.getSpecifier() == RISCV::S_None;
3004 return false;
3005}
3006
3007bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
3008 MCValue Res;
3009 if (Expr->evaluateAsRelocatable(Res, nullptr)) {
3010 return Res.getSpecifier() == RISCV::S_None && Res.getAddSym() &&
3011 Res.getSubSym();
3012 }
3013 return false;
3014}
3015
3016ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
3017 StringRef IDVal = DirectiveID.getString();
3018
3019 if (IDVal == ".option")
3020 return parseDirectiveOption();
3021 if (IDVal == ".attribute")
3022 return parseDirectiveAttribute();
3023 if (IDVal == ".insn")
3024 return parseDirectiveInsn(DirectiveID.getLoc());
3025 if (IDVal == ".variant_cc")
3026 return parseDirectiveVariantCC();
3027
3028 return ParseStatus::NoMatch;
3029}
3030
3031bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
3032 bool FromOptionDirective) {
3033 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
3034 Arch, /*EnableExperimentalExtension=*/true,
3035 /*ExperimentalExtensionVersionCheck=*/true);
3036 if (!ParseResult) {
3037 std::string Buffer;
3038 raw_string_ostream OutputErrMsg(Buffer);
3039 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
3040 OutputErrMsg << "invalid arch name '" << Arch << "', "
3041 << ErrMsg.getMessage();
3042 });
3043
3044 return Error(Loc, OutputErrMsg.str());
3045 }
3046 auto &ISAInfo = *ParseResult;
3047
3048 if (FromOptionDirective) {
3049 if (ISAInfo->getXLen() == 32 && isRV64())
3050 return Error(Loc, "bad arch string switching from rv64 to rv32");
3051 else if (ISAInfo->getXLen() == 64 && !isRV64())
3052 return Error(Loc, "bad arch string switching from rv32 to rv64");
3053 }
3054 if (ISAInfo->getXLen() != 32 && ISAInfo->getXLen() != 64)
3055 return Error(Loc, "bad arch string " + Arch);
3056
3057 // RISCVISAInfo::parseArchString already expands all implied extensions
3058 // (including conditional C/Zce implications like Zcd and Zcf), so we can
3059 // toggle the feature bits directly without calling setFeatureBits() (which
3060 // would run updateCZceFeatureImplications() on an incomplete feature set).
3061 MCSubtargetInfo &STI = copySTI();
3062 for (auto &Feature : STI.getAllProcessorFeatures()) {
3064 continue;
3065 if (ISAInfo->hasExtension(Feature.key()) != STI.hasFeature(Feature.Value))
3066 STI.ToggleFeature(Feature.Value);
3067 }
3068 if ((ISAInfo->getXLen() == 64) != STI.hasFeature(RISCV::Feature64Bit))
3069 STI.ToggleFeature(RISCV::Feature64Bit);
3070 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
3071
3072 Result = ISAInfo->toString();
3073 return false;
3074}
3075
3076bool RISCVAsmParser::parseDirectiveOption() {
3077 MCAsmParser &Parser = getParser();
3078 // Get the option token.
3079 AsmToken Tok = Parser.getTok();
3080
3081 // At the moment only identifiers are supported.
3082 if (parseToken(AsmToken::Identifier, "expected identifier"))
3083 return true;
3084
3085 StringRef Option = Tok.getIdentifier();
3086
3087 if (Option == "push") {
3088 if (Parser.parseEOL())
3089 return true;
3090
3091 getTargetStreamer().emitDirectiveOptionPush();
3092 pushFeatureBits();
3093 return false;
3094 }
3095
3096 if (Option == "pop") {
3097 SMLoc StartLoc = Parser.getTok().getLoc();
3098 if (Parser.parseEOL())
3099 return true;
3100
3101 getTargetStreamer().emitDirectiveOptionPop();
3102 if (popFeatureBits())
3103 return Error(StartLoc, ".option pop with no .option push");
3104
3105 return false;
3106 }
3107
3108 if (Option == "arch") {
3110 do {
3111 if (Parser.parseComma())
3112 return true;
3113
3115 if (parseOptionalToken(AsmToken::Plus))
3116 Type = RISCVOptionArchArgType::Plus;
3117 else if (parseOptionalToken(AsmToken::Minus))
3118 Type = RISCVOptionArchArgType::Minus;
3119 else if (!Args.empty())
3120 return Error(Parser.getTok().getLoc(),
3121 "unexpected token, expected + or -");
3122 else
3123 Type = RISCVOptionArchArgType::Full;
3124
3125 if (Parser.getTok().isNot(AsmToken::Identifier))
3126 return Error(Parser.getTok().getLoc(),
3127 "unexpected token, expected identifier");
3128
3129 StringRef Arch = Parser.getTok().getString();
3130 SMLoc Loc = Parser.getTok().getLoc();
3131 Parser.Lex();
3132
3133 if (Type == RISCVOptionArchArgType::Full) {
3134 std::string Result;
3135 if (resetToArch(Arch, Loc, Result, true))
3136 return true;
3137
3138 Args.emplace_back(Type, Result);
3139 break;
3140 }
3141
3142 if (isDigit(Arch.back()))
3143 return Error(
3144 Loc, "extension version number parsing not currently implemented");
3145
3146 std::string Feature = RISCVISAInfo::getTargetFeatureForExtension(Arch);
3147 if (!enableExperimentalExtension() &&
3148 StringRef(Feature).starts_with("experimental-"))
3149 return Error(Loc, "unexpected experimental extensions");
3150 const auto &AllFeatures = getSTI().getAllProcessorFeatures();
3151 auto Ext = llvm::lower_bound(AllFeatures, Feature);
3152 if (Ext == std::end(AllFeatures) || StringRef(Ext->key()) != Feature)
3153 return Error(Loc, "unknown extension feature");
3154
3155 if (Ext->Value == RISCV::FeatureStdExtY)
3156 return Error(Loc, "passing '+y'/'-y' is not supported yet; specify a "
3157 "full arch string instead");
3158
3159 Args.emplace_back(Type, Arch.str());
3160
3161 if (Type == RISCVOptionArchArgType::Plus) {
3162 FeatureBitset OldFeatureBits = STI->getFeatureBits();
3163
3164 setFeatureBits(Ext->Value, Ext->key());
3165 auto ParseResult = RISCVFeatures::parseFeatureBits(*STI);
3166 if (!ParseResult) {
3167 copySTI().setFeatureBits(OldFeatureBits);
3168 setAvailableFeatures(ComputeAvailableFeatures(OldFeatureBits));
3169
3170 std::string Buffer;
3171 raw_string_ostream OutputErrMsg(Buffer);
3172 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
3173 OutputErrMsg << ErrMsg.getMessage();
3174 });
3175
3176 return Error(Loc, OutputErrMsg.str());
3177 }
3178 } else {
3179 assert(Type == RISCVOptionArchArgType::Minus);
3180 // It is invalid to disable an extension that there are other enabled
3181 // extensions depend on it.
3182 // TODO: Make use of RISCVISAInfo to handle this
3183 for (auto &Feature : AllFeatures) {
3184 if (getSTI().hasFeature(Feature.Value) &&
3185 Feature.Implies.test(Ext->Value))
3186 return Error(Loc, Twine("can't disable ") + Ext->key() +
3187 " extension; " + Feature.key() +
3188 " extension requires " + Ext->key() +
3189 " extension");
3190 }
3191
3192 clearFeatureBits(Ext->Value, Ext->key());
3193 }
3194 } while (Parser.getTok().isNot(AsmToken::EndOfStatement));
3195
3196 if (Parser.parseEOL())
3197 return true;
3198
3199 getTargetStreamer().emitDirectiveOptionArch(Args);
3200
3201 if (auto ParseResult = RISCVFeatures::parseFeatureBits(*STI))
3202 getTargetStreamer().setArchString((*ParseResult)->toString());
3203 return false;
3204 }
3205
3206 if (Option == "exact") {
3207 if (Parser.parseEOL())
3208 return true;
3209
3210 getTargetStreamer().emitDirectiveOptionExact();
3211 setFeatureBits(RISCV::FeatureExactAssembly, "exact-asm");
3212 clearFeatureBits(RISCV::FeatureRelax, "relax");
3213 return false;
3214 }
3215
3216 if (Option == "noexact") {
3217 if (Parser.parseEOL())
3218 return true;
3219
3220 getTargetStreamer().emitDirectiveOptionNoExact();
3221 clearFeatureBits(RISCV::FeatureExactAssembly, "exact-asm");
3222 setFeatureBits(RISCV::FeatureRelax, "relax");
3223 return false;
3224 }
3225
3226 if (Option == "rvc") {
3227 if (Parser.parseEOL())
3228 return true;
3229
3230 getTargetStreamer().emitDirectiveOptionRVC();
3231 setFeatureBits(RISCV::FeatureStdExtC, "c");
3232 if (auto ParseResult = RISCVFeatures::parseFeatureBits(*STI))
3233 getTargetStreamer().setArchString((*ParseResult)->toString());
3234 return false;
3235 }
3236
3237 if (Option == "norvc") {
3238 if (Parser.parseEOL())
3239 return true;
3240
3241 getTargetStreamer().emitDirectiveOptionNoRVC();
3242 clearFeatureBits(RISCV::FeatureStdExtC, "c");
3243 clearFeatureBits(RISCV::FeatureStdExtZca, "zca");
3244 if (auto ParseResult = RISCVFeatures::parseFeatureBits(*STI))
3245 getTargetStreamer().setArchString((*ParseResult)->toString());
3246 return false;
3247 }
3248
3249 if (Option == "pic") {
3250 if (Parser.parseEOL())
3251 return true;
3252
3253 getTargetStreamer().emitDirectiveOptionPIC();
3254 ParserOptions.IsPicEnabled = true;
3255 return false;
3256 }
3257
3258 if (Option == "nopic") {
3259 if (Parser.parseEOL())
3260 return true;
3261
3262 getTargetStreamer().emitDirectiveOptionNoPIC();
3263 ParserOptions.IsPicEnabled = false;
3264 return false;
3265 }
3266
3267 if (Option == "relax") {
3268 if (Parser.parseEOL())
3269 return true;
3270
3271 getTargetStreamer().emitDirectiveOptionRelax();
3272 setFeatureBits(RISCV::FeatureRelax, "relax");
3273 return false;
3274 }
3275
3276 if (Option == "norelax") {
3277 if (Parser.parseEOL())
3278 return true;
3279
3280 getTargetStreamer().emitDirectiveOptionNoRelax();
3281 clearFeatureBits(RISCV::FeatureRelax, "relax");
3282 return false;
3283 }
3284
3285 // Unknown option.
3286 Warning(Parser.getTok().getLoc(),
3287 "unknown option, expected 'push', 'pop', "
3288 "'rvc', 'norvc', 'arch', 'relax', 'norelax', "
3289 "'exact', or 'noexact'");
3290 Parser.eatToEndOfStatement();
3291 return false;
3292}
3293
3294/// parseDirectiveAttribute
3295/// ::= .attribute expression ',' ( expression | "string" )
3296/// ::= .attribute identifier ',' ( expression | "string" )
3297bool RISCVAsmParser::parseDirectiveAttribute() {
3298 MCAsmParser &Parser = getParser();
3299 int64_t Tag;
3300 SMLoc TagLoc;
3301 TagLoc = Parser.getTok().getLoc();
3302 if (Parser.getTok().is(AsmToken::Identifier)) {
3303 StringRef Name = Parser.getTok().getIdentifier();
3304 std::optional<unsigned> Ret =
3306 if (!Ret)
3307 return Error(TagLoc, "attribute name not recognised: " + Name);
3308 Tag = *Ret;
3309 Parser.Lex();
3310 } else {
3311 const MCExpr *AttrExpr;
3312
3313 TagLoc = Parser.getTok().getLoc();
3314 if (Parser.parseExpression(AttrExpr))
3315 return true;
3316
3317 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
3318 if (check(!CE, TagLoc, "expected numeric constant"))
3319 return true;
3320
3321 Tag = CE->getValue();
3322 }
3323
3324 if (Parser.parseComma())
3325 return true;
3326
3327 StringRef StringValue;
3328 int64_t IntegerValue = 0;
3329 bool IsIntegerValue = true;
3330
3331 // RISC-V attributes have a string value if the tag number is odd
3332 // and an integer value if the tag number is even.
3333 if (Tag % 2)
3334 IsIntegerValue = false;
3335
3336 SMLoc ValueExprLoc = Parser.getTok().getLoc();
3337 if (IsIntegerValue) {
3338 const MCExpr *ValueExpr;
3339 if (Parser.parseExpression(ValueExpr))
3340 return true;
3341
3342 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
3343 if (!CE)
3344 return Error(ValueExprLoc, "expected numeric constant");
3345 IntegerValue = CE->getValue();
3346 } else {
3347 if (Parser.getTok().isNot(AsmToken::String))
3348 return Error(Parser.getTok().getLoc(), "expected string constant");
3349
3350 StringValue = Parser.getTok().getStringContents();
3351 Parser.Lex();
3352 }
3353
3354 if (Parser.parseEOL())
3355 return true;
3356
3357 if (IsIntegerValue)
3358 getTargetStreamer().emitAttribute(Tag, IntegerValue);
3359 else if (Tag != RISCVAttrs::ARCH)
3360 getTargetStreamer().emitTextAttribute(Tag, StringValue);
3361 else {
3362 std::string Result;
3363 if (resetToArch(StringValue, ValueExprLoc, Result, false))
3364 return true;
3365
3366 // Then emit the arch string.
3367 getTargetStreamer().emitTextAttribute(Tag, Result);
3368
3369 // And then update the active ISA so the next instruction-run emits
3370 // an ISA-specific mapping symbol.
3371 getTargetStreamer().setArchString(Result);
3372 }
3373
3374 return false;
3375}
3376
3378 return StringSwitch<bool>(Format)
3379 .Cases({"r", "r4", "i", "b", "sb", "u", "j", "uj", "s"}, true)
3380 .Cases({"cr", "ci", "ciw", "css", "cl", "cs", "ca", "cb", "cj"},
3381 STI.hasFeature(RISCV::FeatureStdExtZca))
3382 .Cases({"qc.eai", "qc.ei", "qc.eb", "qc.ej", "qc.es"},
3383 !STI.hasFeature(RISCV::Feature64Bit))
3384 .Default(false);
3385}
3386
3387/// parseDirectiveInsn
3388/// ::= .insn [ format encoding, (operands (, operands)*) ]
3389/// ::= .insn [ length, value ]
3390/// ::= .insn [ value ]
3391bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
3392 MCAsmParser &Parser = getParser();
3393
3394 // Expect instruction format as identifier.
3395 StringRef Format;
3396 SMLoc ErrorLoc = Parser.getTok().getLoc();
3397 if (Parser.parseIdentifier(Format)) {
3398 // Try parsing .insn [ length , ] value
3399 std::optional<int64_t> Length;
3400 int64_t Value = 0;
3401 if (Parser.parseAbsoluteExpression(Value))
3402 return true;
3403 if (Parser.parseOptionalToken(AsmToken::Comma)) {
3404 Length = Value;
3405 if (Parser.parseAbsoluteExpression(Value))
3406 return true;
3407
3408 if (*Length == 0 || (*Length % 2) != 0)
3409 return Error(ErrorLoc,
3410 "instruction lengths must be a non-zero multiple of two");
3411
3412 // TODO: Support Instructions > 64 bits.
3413 if (*Length > 8)
3414 return Error(ErrorLoc,
3415 "instruction lengths over 64 bits are not supported");
3416 }
3417
3418 // We only derive a length from the encoding for 16- and 32-bit
3419 // instructions, as the encodings for longer instructions are not frozen in
3420 // the spec.
3421 int64_t EncodingDerivedLength = ((Value & 0b11) == 0b11) ? 4 : 2;
3422
3423 if (Length) {
3424 // Only check the length against the encoding if the length is present and
3425 // could match
3426 if ((*Length <= 4) && (*Length != EncodingDerivedLength))
3427 return Error(ErrorLoc,
3428 "instruction length does not match the encoding");
3429
3430 if (!isUIntN(*Length * 8, Value))
3431 return Error(ErrorLoc, "encoding value does not fit into instruction");
3432 } else {
3433 if (!isUIntN(EncodingDerivedLength * 8, Value))
3434 return Error(ErrorLoc, "encoding value does not fit into instruction");
3435 }
3436
3437 if (!getSTI().hasFeature(RISCV::FeatureStdExtZca) &&
3438 (EncodingDerivedLength == 2))
3439 return Error(ErrorLoc, "compressed instructions are not allowed");
3440
3441 if (getParser().parseEOL("invalid operand for instruction")) {
3442 getParser().eatToEndOfStatement();
3443 return true;
3444 }
3445
3446 unsigned Opcode;
3447 if (Length) {
3448 switch (*Length) {
3449 case 2:
3450 Opcode = RISCV::Insn16;
3451 break;
3452 case 4:
3453 Opcode = RISCV::Insn32;
3454 break;
3455 case 6:
3456 Opcode = RISCV::Insn48;
3457 break;
3458 case 8:
3459 Opcode = RISCV::Insn64;
3460 break;
3461 default:
3462 llvm_unreachable("Error should have already been emitted");
3463 }
3464 } else
3465 Opcode = (EncodingDerivedLength == 2) ? RISCV::Insn16 : RISCV::Insn32;
3466
3467 emitToStreamer(getStreamer(), MCInstBuilder(Opcode).addImm(Value));
3468 return false;
3469 }
3470
3471 if (!isValidInsnFormat(Format, getSTI()))
3472 return Error(ErrorLoc, "invalid instruction format");
3473
3474 std::string FormatName = (".insn_" + Format).str();
3475
3476 ParseInstructionInfo Info;
3478
3479 if (parseInstruction(Info, FormatName, L, Operands))
3480 return true;
3481
3482 unsigned Opcode;
3483 uint64_t ErrorInfo;
3484 return matchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
3485 ErrorInfo,
3486 /*MatchingInlineAsm=*/false);
3487}
3488
3489/// parseDirectiveVariantCC
3490/// ::= .variant_cc symbol
3491bool RISCVAsmParser::parseDirectiveVariantCC() {
3492 StringRef Name;
3493 if (getParser().parseIdentifier(Name))
3494 return TokError("expected symbol name");
3495 if (parseEOL())
3496 return true;
3497 getTargetStreamer().emitDirectiveVariantCC(
3498 *getContext().getOrCreateSymbol(Name));
3499 return false;
3500}
3501
3502void RISCVAsmParser::validateInstructionPreEmit(const MCInst &Inst,
3503 const MCSubtargetInfo &STI) {
3504 // Ensure that we don't emit instructions with missing predicates or invalid
3505 // register classes.
3506 // TODO: ideally this code should be shared between targets.
3507 RISCV_MC::verifyInstructionPredicates(Inst.getOpcode(), STI.getFeatureBits());
3508 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
3509 unsigned HwMode = STI.getHwMode(MCSubtargetInfo::HwMode_RegInfo);
3510 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
3511 for (auto [I, Op] : enumerate(Inst.getOperands())) {
3512 if (I < Desc.getNumOperands() && Op.isReg() && Op.getReg().isValid()) {
3513 auto RCID = MII.getOpRegClassID(Desc.operands()[I], HwMode);
3514 // Some instructions don't have a valid regclass, e.g. .insn_*
3515 if (RCID == -1)
3516 continue;
3517 const MCRegisterClass &RegClass = MRI->getRegClass(RCID);
3518 if (!RegClass.contains(Op.getReg())) {
3519 SMLoc Loc = Inst.getLoc().isValid() ? Inst.getLoc() : getLoc();
3520 getParser().printError(
3521 Loc, MII.getName(Inst.getOpcode()) + " operand " + Twine(I + 1) +
3522 " register " + MRI->getName(Op.getReg()) +
3523 " is not a member of register class " +
3524 MRI->getRegClassName(&RegClass));
3525 reportFatalInternalError("Attempting to emit invalid instruction. "
3526 "Incorrect pseudo expansion?");
3527 }
3528 }
3529 }
3530}
3531
3532void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
3533 MCInst CInst;
3534 bool Res = false;
3535 const MCSubtargetInfo &STI = getSTI();
3536#ifdef EXPENSIVE_CHECKS
3537 constexpr bool VerifyByDefault = true;
3538#else
3539 constexpr bool VerifyByDefault = false;
3540#endif
3541 bool VerifyMCInst = valueOr(CLOpts.verify_mcinst, VerifyByDefault);
3542 if (VerifyMCInst)
3543 validateInstructionPreEmit(Inst, STI);
3544 if (!STI.hasFeature(RISCV::FeatureExactAssembly))
3545 Res = RISCVRVC::compress(CInst, Inst, STI);
3546 if (Res) {
3547 ++RISCVNumInstrsCompressed;
3548 if (VerifyMCInst)
3549 validateInstructionPreEmit(CInst, STI);
3550 }
3551 S.emitInstruction((Res ? CInst : Inst), STI);
3552}
3553
3554void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
3555 MCStreamer &Out) {
3557 RISCVMatInt::generateMCInstSeq(Value, getSTI(), DestReg, Seq);
3558
3559 for (MCInst &Inst : Seq) {
3560 emitToStreamer(Out, Inst);
3561 }
3562}
3563
3564void RISCVAsmParser::emitAuipcInstPair(MCRegister DestReg, MCRegister TmpReg,
3565 const MCExpr *Symbol,
3566 RISCV::Specifier VKHi,
3567 unsigned SecondOpcode, SMLoc IDLoc,
3568 MCStreamer &Out) {
3569 // A pair of instructions for PC-relative addressing; expands to
3570 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3571 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3572 MCContext &Ctx = getContext();
3573
3574 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
3575 Out.emitLabel(TmpLabel);
3576
3577 const auto *SymbolHi = MCSpecifierExpr::create(Symbol, VKHi, Ctx);
3578 emitToStreamer(Out,
3579 MCInstBuilder(RISCV::AUIPC).addReg(TmpReg).addExpr(SymbolHi));
3580
3581 const MCExpr *RefToLinkTmpLabel = MCSpecifierExpr::create(
3582 MCSymbolRefExpr::create(TmpLabel, Ctx), RISCV::S_PCREL_LO, Ctx);
3583
3584 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3585 .addReg(DestReg)
3586 .addReg(TmpReg)
3587 .addExpr(RefToLinkTmpLabel));
3588}
3589
3590void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3591 MCStreamer &Out) {
3592 // The load local address pseudo-instruction "lla" is used in PC-relative
3593 // addressing of local symbols:
3594 // lla rdest, symbol
3595 // expands to
3596 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3597 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3598 MCRegister DestReg = Inst.getOperand(0).getReg();
3599 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3600 if (STI->hasFeature(RISCV::Feature32Bit) &&
3601 STI->hasFeature(RISCV::FeatureVendorXqcili) &&
3602 !ParserOptions.IsPicEnabled)
3603 emitToStreamer(
3604 Out, MCInstBuilder(RISCV::QC_E_LI).addReg(DestReg).addExpr(Symbol));
3605 else
3606 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCV::S_PCREL_HI, RISCV::ADDI,
3607 IDLoc, Out);
3608}
3609
3610void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3611 MCStreamer &Out) {
3612 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3613 // addressing of global symbols:
3614 // lga rdest, symbol
3615 // expands to
3616 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3617 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3618 MCRegister DestReg = Inst.getOperand(0).getReg();
3619 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3620 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3621 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCV::S_GOT_HI, SecondOpcode,
3622 IDLoc, Out);
3623}
3624
3625void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3626 MCStreamer &Out) {
3627 // The load address pseudo-instruction "la" is used in PC-relative and
3628 // GOT-indirect addressing of global symbols:
3629 // la rdest, symbol
3630 // is an alias for either (for non-PIC)
3631 // lla rdest, symbol
3632 // or (for PIC)
3633 // lga rdest, symbol
3634 if (ParserOptions.IsPicEnabled)
3635 emitLoadGlobalAddress(Inst, IDLoc, Out);
3636 else
3637 emitLoadLocalAddress(Inst, IDLoc, Out);
3638}
3639
3640void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3641 MCStreamer &Out) {
3642 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3643 // initial-exec TLS model addressing of global symbols:
3644 // la.tls.ie rdest, symbol
3645 // expands to
3646 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3647 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3648 MCRegister DestReg = Inst.getOperand(0).getReg();
3649 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3650 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3651 emitAuipcInstPair(DestReg, DestReg, Symbol, ELF::R_RISCV_TLS_GOT_HI20,
3652 SecondOpcode, IDLoc, Out);
3653}
3654
3655void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3656 MCStreamer &Out) {
3657 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3658 // global-dynamic TLS model addressing of global symbols:
3659 // la.tls.gd rdest, symbol
3660 // expands to
3661 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3662 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3663 MCRegister DestReg = Inst.getOperand(0).getReg();
3664 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3665 emitAuipcInstPair(DestReg, DestReg, Symbol, ELF::R_RISCV_TLS_GD_HI20,
3666 RISCV::ADDI, IDLoc, Out);
3667}
3668
3669void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3670 SMLoc IDLoc, MCStreamer &Out,
3671 bool HasTmpReg) {
3672 // The load/store pseudo-instruction does a pc-relative load with
3673 // a symbol.
3674 //
3675 // The expansion looks like this
3676 //
3677 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3678 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3679 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3680 MCRegister DestReg = Inst.getOperand(DestRegOpIdx).getReg();
3681 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3682 MCRegister TmpReg = Inst.getOperand(0).getReg();
3683
3684 // If TmpReg is a GPR pair, get the even register.
3685 if (getRISCVMCRegisterClass(RISCV::GPRPairRegClassID).contains(TmpReg)) {
3686 const MCRegisterInfo *RI = getContext().getRegisterInfo();
3687 TmpReg = RI->getSubReg(TmpReg, RISCV::sub_gpr_even);
3688 }
3689
3690 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3691 emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCV::S_PCREL_HI, Opcode, IDLoc,
3692 Out);
3693}
3694
3695void RISCVAsmParser::emitQCELILoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3696 SMLoc IDLoc, MCStreamer &Out,
3697 bool HasTmpReg) {
3698 // For loads (HasTmpReg=false): operands are [rd, symbol]
3699 // qc.e.li rd, symbol
3700 // lx rd, 0(rd), %qc.access(symbol) [possibly compressed]
3701 //
3702 // For stores (HasTmpReg=true): operands are [rt, rs, symbol]
3703 // qc.e.li rt, symbol
3704 // sx rs, 0(rt), %qc.access(symbol) [possibly compressed]
3705 MCRegister AddrReg = Inst.getOperand(0).getReg();
3706 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3707 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3708
3709 emitToStreamer(Out,
3710 MCInstBuilder(RISCV::QC_E_LI).addReg(AddrReg).addExpr(Symbol));
3711
3712 MCContext &Ctx = getContext();
3713 const MCExpr *AccessExpr =
3715
3716 // We have to manually compress the QCAccess pseudos as the current
3717 // CompressPat mechanism does not support them. Each entry pairs the
3718 // compressed opcode with the subtarget feature it requires.
3719 struct CompressedForm {
3720 unsigned Opcode;
3721 unsigned Feature;
3722 };
3723 std::optional<CompressedForm> Compressed;
3724 switch (Opcode) {
3725 default:
3726 break;
3727 case RISCV::PseudoQCAccessLBU:
3728 Compressed = {RISCV::PseudoQCAccessC_LBU, RISCV::FeatureStdExtZcb};
3729 break;
3730 case RISCV::PseudoQCAccessLH:
3731 Compressed = {RISCV::PseudoQCAccessC_LH, RISCV::FeatureStdExtZcb};
3732 break;
3733 case RISCV::PseudoQCAccessLHU:
3734 Compressed = {RISCV::PseudoQCAccessC_LHU, RISCV::FeatureStdExtZcb};
3735 break;
3736 case RISCV::PseudoQCAccessLW:
3737 Compressed = {RISCV::PseudoQCAccessC_LW, RISCV::FeatureStdExtZca};
3738 break;
3739 case RISCV::PseudoQCAccessSB:
3740 Compressed = {RISCV::PseudoQCAccessC_SB, RISCV::FeatureStdExtZcb};
3741 break;
3742 case RISCV::PseudoQCAccessSH:
3743 Compressed = {RISCV::PseudoQCAccessC_SH, RISCV::FeatureStdExtZcb};
3744 break;
3745 case RISCV::PseudoQCAccessSW:
3746 Compressed = {RISCV::PseudoQCAccessC_SW, RISCV::FeatureStdExtZca};
3747 break;
3748 }
3749
3750 // For stores, both the data register and the address register must be in
3751 // GPRC for the compressed form; for loads AddrReg serves as both.
3752 bool CanUseGPRC =
3753 getRISCVMCRegisterClass(RISCV::GPRCRegClassID).contains(AddrReg);
3754 if (HasTmpReg && CanUseGPRC) {
3755 MCRegister DataReg = Inst.getOperand(1).getReg();
3756 CanUseGPRC =
3757 getRISCVMCRegisterClass(RISCV::GPRCRegClassID).contains(DataReg);
3758 }
3759
3760 bool UseCompressed =
3761 Compressed && getSTI().hasFeature(Compressed->Feature) && CanUseGPRC;
3762
3763 unsigned ActualOpcode = UseCompressed ? Compressed->Opcode : Opcode;
3764 if (HasTmpReg) {
3765 MCRegister DataReg = Inst.getOperand(1).getReg();
3766 emitToStreamer(Out, MCInstBuilder(ActualOpcode)
3767 .addReg(DataReg)
3768 .addReg(AddrReg)
3769 .addImm(0)
3770 .addExpr(AccessExpr));
3771 } else {
3772 emitToStreamer(Out, MCInstBuilder(ActualOpcode)
3773 .addReg(AddrReg)
3774 .addReg(AddrReg)
3775 .addImm(0)
3776 .addExpr(AccessExpr));
3777 }
3778}
3779
3780void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3781 int64_t Width, SMLoc IDLoc,
3782 MCStreamer &Out) {
3783 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3784 // amounts dependent on the XLEN.
3785 //
3786 // The expansion looks like this
3787 //
3788 // SLLI rd, rs, XLEN - Width
3789 // SR[A|R]I rd, rd, XLEN - Width
3790 const MCOperand &DestReg = Inst.getOperand(0);
3791 const MCOperand &SourceReg = Inst.getOperand(1);
3792
3793 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3794 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3795
3796 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3797
3798 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
3799 .addOperand(DestReg)
3800 .addOperand(SourceReg)
3801 .addImm(ShAmt));
3802
3803 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3804 .addOperand(DestReg)
3805 .addOperand(DestReg)
3806 .addImm(ShAmt));
3807}
3808
3809void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3810 MCStreamer &Out) {
3811 if (Inst.getNumOperands() == 4 && !Inst.getOperand(3).getReg()) {
3812 // unmasked va >= x
3813 //
3814 // pseudoinstruction: vmsge{u}.vx vd, va, x
3815 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3816 emitToStreamer(Out, MCInstBuilder(Opcode)
3817 .addOperand(Inst.getOperand(0))
3818 .addOperand(Inst.getOperand(1))
3819 .addOperand(Inst.getOperand(2))
3820 .addReg(MCRegister())
3821 .setLoc(IDLoc));
3822 emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
3823 .addOperand(Inst.getOperand(0))
3824 .addOperand(Inst.getOperand(0))
3825 .addOperand(Inst.getOperand(0))
3826 .setLoc(IDLoc));
3827 } else if (Inst.getNumOperands() == 4) {
3828 // masked va >= x, vd != v0
3829 //
3830 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3831 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3832 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3833 "The destination register should not be V0.");
3834 assert(Inst.getOperand(3).getReg() == RISCV::V0 && "Expected a mask");
3835 emitToStreamer(Out, MCInstBuilder(Opcode)
3836 .addOperand(Inst.getOperand(0))
3837 .addOperand(Inst.getOperand(1))
3838 .addOperand(Inst.getOperand(2))
3839 .addOperand(Inst.getOperand(3))
3840 .setLoc(IDLoc));
3841 emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
3842 .addOperand(Inst.getOperand(0))
3843 .addOperand(Inst.getOperand(0))
3844 .addReg(RISCV::V0)
3845 .setLoc(IDLoc));
3846 } else if (Inst.getNumOperands() == 5 &&
3847 Inst.getOperand(0).getReg() == RISCV::V0) {
3848 // masked va >= x, vd == v0
3849 //
3850 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3851 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3852 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3853 "The temporary vector register should not be V0.");
3854 emitToStreamer(Out, MCInstBuilder(Opcode)
3855 .addOperand(Inst.getOperand(1))
3856 .addOperand(Inst.getOperand(2))
3857 .addOperand(Inst.getOperand(3))
3858 .addReg(MCRegister())
3859 .setLoc(IDLoc));
3860 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3861 .addOperand(Inst.getOperand(0))
3862 .addOperand(Inst.getOperand(0))
3863 .addOperand(Inst.getOperand(1))
3864 .setLoc(IDLoc));
3865 } else if (Inst.getNumOperands() == 5) {
3866 // masked va >= x, any vd
3867 //
3868 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3869 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3870 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3871 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3872 "The temporary vector register should not be V0.");
3873 emitToStreamer(Out, MCInstBuilder(Opcode)
3874 .addOperand(Inst.getOperand(1))
3875 .addOperand(Inst.getOperand(2))
3876 .addOperand(Inst.getOperand(3))
3877 .addReg(MCRegister())
3878 .setLoc(IDLoc));
3879 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3880 .addOperand(Inst.getOperand(1))
3881 .addReg(RISCV::V0)
3882 .addOperand(Inst.getOperand(1))
3883 .setLoc(IDLoc));
3884 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3885 .addOperand(Inst.getOperand(0))
3886 .addOperand(Inst.getOperand(0))
3887 .addReg(RISCV::V0)
3888 .setLoc(IDLoc));
3889 emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
3890 .addOperand(Inst.getOperand(0))
3891 .addOperand(Inst.getOperand(1))
3892 .addOperand(Inst.getOperand(0))
3893 .setLoc(IDLoc));
3894 }
3895}
3896
3897bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3899 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3900 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3901 if (Inst.getOperand(2).getReg() != RISCV::X4) {
3902 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3903 return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
3904 "%tprel_add specifier");
3905 }
3906
3907 return false;
3908}
3909
3910bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3912 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3913 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3914 if (Inst.getOperand(0).getReg() != RISCV::X5) {
3915 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3916 return Error(ErrorLoc, "the output operand must be t0/x5 when using "
3917 "%tlsdesc_call specifier");
3918 }
3919
3920 return false;
3921}
3922
3923std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3924 return RISCVOperand::createReg(MCRegister(), llvm::SMLoc(), llvm::SMLoc());
3925}
3926
3927std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3928 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
3929 llvm::SMLoc());
3930}
3931
3932std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3933 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
3934 llvm::SMLoc());
3935}
3936
3937std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultZeroOffset() {
3938 return RISCVOperand::createExpr(MCConstantExpr::create(0, getContext()),
3939 llvm::SMLoc(), llvm::SMLoc(), isRV64());
3940}
3941
3942static unsigned getNFforLXSEG(unsigned Opcode) {
3943 switch (Opcode) {
3944 default:
3945 return 1;
3946 case RISCV::VLOXSEG2EI8_V:
3947 case RISCV::VLOXSEG2EI16_V:
3948 case RISCV::VLOXSEG2EI32_V:
3949 case RISCV::VLOXSEG2EI64_V:
3950 case RISCV::VLUXSEG2EI8_V:
3951 case RISCV::VLUXSEG2EI16_V:
3952 case RISCV::VLUXSEG2EI32_V:
3953 case RISCV::VLUXSEG2EI64_V:
3954 return 2;
3955 case RISCV::VLOXSEG3EI8_V:
3956 case RISCV::VLOXSEG3EI16_V:
3957 case RISCV::VLOXSEG3EI32_V:
3958 case RISCV::VLOXSEG3EI64_V:
3959 case RISCV::VLUXSEG3EI8_V:
3960 case RISCV::VLUXSEG3EI16_V:
3961 case RISCV::VLUXSEG3EI32_V:
3962 case RISCV::VLUXSEG3EI64_V:
3963 return 3;
3964 case RISCV::VLOXSEG4EI8_V:
3965 case RISCV::VLOXSEG4EI16_V:
3966 case RISCV::VLOXSEG4EI32_V:
3967 case RISCV::VLOXSEG4EI64_V:
3968 case RISCV::VLUXSEG4EI8_V:
3969 case RISCV::VLUXSEG4EI16_V:
3970 case RISCV::VLUXSEG4EI32_V:
3971 case RISCV::VLUXSEG4EI64_V:
3972 return 4;
3973 case RISCV::VLOXSEG5EI8_V:
3974 case RISCV::VLOXSEG5EI16_V:
3975 case RISCV::VLOXSEG5EI32_V:
3976 case RISCV::VLOXSEG5EI64_V:
3977 case RISCV::VLUXSEG5EI8_V:
3978 case RISCV::VLUXSEG5EI16_V:
3979 case RISCV::VLUXSEG5EI32_V:
3980 case RISCV::VLUXSEG5EI64_V:
3981 return 5;
3982 case RISCV::VLOXSEG6EI8_V:
3983 case RISCV::VLOXSEG6EI16_V:
3984 case RISCV::VLOXSEG6EI32_V:
3985 case RISCV::VLOXSEG6EI64_V:
3986 case RISCV::VLUXSEG6EI8_V:
3987 case RISCV::VLUXSEG6EI16_V:
3988 case RISCV::VLUXSEG6EI32_V:
3989 case RISCV::VLUXSEG6EI64_V:
3990 return 6;
3991 case RISCV::VLOXSEG7EI8_V:
3992 case RISCV::VLOXSEG7EI16_V:
3993 case RISCV::VLOXSEG7EI32_V:
3994 case RISCV::VLOXSEG7EI64_V:
3995 case RISCV::VLUXSEG7EI8_V:
3996 case RISCV::VLUXSEG7EI16_V:
3997 case RISCV::VLUXSEG7EI32_V:
3998 case RISCV::VLUXSEG7EI64_V:
3999 return 7;
4000 case RISCV::VLOXSEG8EI8_V:
4001 case RISCV::VLOXSEG8EI16_V:
4002 case RISCV::VLOXSEG8EI32_V:
4003 case RISCV::VLOXSEG8EI64_V:
4004 case RISCV::VLUXSEG8EI8_V:
4005 case RISCV::VLUXSEG8EI16_V:
4006 case RISCV::VLUXSEG8EI32_V:
4007 case RISCV::VLUXSEG8EI64_V:
4008 return 8;
4009 }
4010}
4011
4013 if (getRISCVMCRegisterClass(RISCV::VRM2RegClassID).contains(Reg))
4014 return 2;
4015 if (getRISCVMCRegisterClass(RISCV::VRM4RegClassID).contains(Reg))
4016 return 4;
4017 if (getRISCVMCRegisterClass(RISCV::VRM8RegClassID).contains(Reg))
4018 return 8;
4019 return 1;
4020}
4021
4022static bool isZvvfmmScaleOpcode(unsigned Opcode) {
4023 switch (Opcode) {
4024 case RISCV::VFWMMACC_VV_SCALE:
4025 case RISCV::VFQMMACC_VV_SCALE:
4026 case RISCV::VF8WMMACC_VV_SCALE:
4027 case RISCV::VFWIMMACC_VV:
4028 case RISCV::VFQIMMACC_VV:
4029 case RISCV::VF8WIMMACC_VV:
4030 return true;
4031 default:
4032 return false;
4033 }
4034}
4035
4036bool RISCVAsmParser::validateInstruction(MCInst &Inst,
4038 unsigned Opcode = Inst.getOpcode();
4039
4040 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
4041 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
4042 MCRegister DestReg = Inst.getOperand(0).getReg();
4043 MCRegister TempReg = Inst.getOperand(1).getReg();
4044 if (DestReg == TempReg) {
4045 SMLoc Loc = Operands.back()->getStartLoc();
4046 return Error(Loc, "the temporary vector register cannot be the same as "
4047 "the destination register");
4048 }
4049 }
4050
4051 if (Opcode == RISCV::PseudoVMSGEU_VX_M || Opcode == RISCV::PseudoVMSGE_VX_M) {
4052 MCRegister DestReg = Inst.getOperand(0).getReg();
4053 MCRegister MaskReg = Inst.getOperand(3).getReg();
4054 if (MaskReg == RISCV::V0 && DestReg == RISCV::V0) {
4055 SMLoc Loc = Operands.back()->getStartLoc();
4056 return Error(Loc, "the destination vector register cannot overlap the "
4057 "mask register unless a temporary register is "
4058 "provided");
4059 }
4060 }
4061
4062 if (Opcode == RISCV::CV_INSERT &&
4063 Inst.getOperand(3).getImm() + Inst.getOperand(4).getImm() >= 32)
4064 return Error(Operands[3]->getStartLoc(),
4065 "the sum of the immediate operands must be less than 32");
4066
4067 switch (Opcode) {
4068 default:
4069 break;
4070 case RISCV::TH_LBIA:
4071 case RISCV::TH_LBIB:
4072 case RISCV::TH_LBUIA:
4073 case RISCV::TH_LBUIB:
4074 case RISCV::TH_LHIA:
4075 case RISCV::TH_LHIB:
4076 case RISCV::TH_LHUIA:
4077 case RISCV::TH_LHUIB:
4078 case RISCV::TH_LWIA:
4079 case RISCV::TH_LWIB:
4080 case RISCV::TH_LWUIA:
4081 case RISCV::TH_LWUIB:
4082 case RISCV::TH_LDIA:
4083 case RISCV::TH_LDIB:
4084 if (Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg())
4085 return Error(Operands[1]->getStartLoc(), "rd and rs1 must be different");
4086 break;
4087 case RISCV::TH_LDD:
4088 case RISCV::TH_LWUD:
4089 case RISCV::TH_LWD: {
4090 MCRegister Rd1 = Inst.getOperand(0).getReg();
4091 MCRegister Rd2 = Inst.getOperand(1).getReg();
4092 MCRegister Rs1 = Inst.getOperand(2).getReg();
4093 // The encoding with overlapping rs1, rd1, and rd2 is reserved for XTHead
4094 // load pair.
4095 if (Rs1 == Rd1 || Rs1 == Rd2 || Rd1 == Rd2) {
4096 SMLoc Loc = Operands[1]->getStartLoc();
4097 return Error(Loc, "rs1, rd1, and rd2 cannot overlap");
4098 }
4099 break;
4100 }
4101 }
4102
4103 if (Opcode == RISCV::CM_MVSA01 || Opcode == RISCV::QC_CM_MVSA01) {
4104 MCRegister Rs1 = Inst.getOperand(0).getReg();
4105 MCRegister Rs2 = Inst.getOperand(1).getReg();
4106 if (Rs1 == Rs2) {
4107 SMLoc Loc = Operands[1]->getStartLoc();
4108 return Error(Loc, "rs1 and rs2 must be different");
4109 }
4110 }
4111
4112 if (isZvvfmmScaleOpcode(Opcode)) {
4113 auto CheckOperandDoesNotOverlapV0 = [&](int OperandIdx,
4114 unsigned ParsedIdx) {
4115 if (Inst.getOperand(OperandIdx).getReg() == RISCV::V0)
4116 return Error(Operands[ParsedIdx]->getStartLoc(),
4117 "vd, vs1, and vs2 cannot overlap v0.scale");
4118 return false;
4119 };
4120
4121 int DestIdx =
4122 RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vd);
4123 int VS1Idx =
4124 RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vs1);
4125 int VS2Idx =
4126 RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vs2);
4127 assert(DestIdx >= 0 && VS1Idx >= 0 && VS2Idx >= 0 &&
4128 "Unexpected Zvvfmm scaled operand list");
4129
4130 if (CheckOperandDoesNotOverlapV0(DestIdx, 1) ||
4131 CheckOperandDoesNotOverlapV0(VS1Idx, 2) ||
4132 CheckOperandDoesNotOverlapV0(VS2Idx, 3))
4133 return true;
4134 }
4135
4136 const MCInstrDesc &MCID = MII.get(Opcode);
4137 if (!(MCID.TSFlags & RISCVII::RVVConstraintMask))
4138 return false;
4139
4140 int DestIdx = RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vd);
4141 MCRegister DestReg = Inst.getOperand(DestIdx).getReg();
4142
4143 // Operands[1] or Operands[2] will be the first operand, DestReg.
4144 const MCParsedAsmOperand *ParsedOp = Operands[1].get();
4145 if (!ParsedOp->isReg()) {
4146 // XSfvcp instructions may have an immediate before vd.
4147 // FIXME: Is there a better way to do this?
4148 ParsedOp = Operands[2].get();
4149 }
4150 const MCRegisterInfo *RI = getContext().getRegisterInfo();
4151 unsigned DestEncoding = RI->getEncodingValue(DestReg);
4152 assert(RI->getEncodingValue(ParsedOp->getReg()) == DestEncoding &&
4153 "Can't find parsed dest operand");
4154 SMLoc Loc = ParsedOp->getStartLoc();
4155
4156 unsigned Lmul = getLMULFromVectorRegister(DestReg);
4157 if (MCID.TSFlags & RISCVII::VS2Constraint) {
4158 int VS2Idx =
4159 RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vs2);
4160 assert(VS2Idx >= 0 && "No vs2 operand?");
4161 unsigned CheckEncoding =
4162 RI->getEncodingValue(Inst.getOperand(VS2Idx).getReg());
4163 unsigned NF = getNFforLXSEG(Opcode);
4164 for (unsigned i = 0; i < std::max(NF, Lmul); i++) {
4165 if ((DestEncoding + i) == CheckEncoding)
4166 return Error(Loc, "the destination vector register group cannot overlap"
4167 " the source vector register group");
4168 }
4169 }
4170 if (MCID.TSFlags & RISCVII::VS1Constraint) {
4171 int VS1Idx =
4172 RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vs1);
4173 // FIXME: The vs1 constraint is used on scalar and imm instructions so we
4174 // need to check that the operand exists.
4175 if (VS1Idx >= 0) {
4176 unsigned CheckEncoding =
4177 RI->getEncodingValue(Inst.getOperand(VS1Idx).getReg());
4178 for (unsigned i = 0; i < Lmul; i++) {
4179 if ((DestEncoding + i) == CheckEncoding)
4180 return Error(Loc,
4181 "the destination vector register group cannot overlap"
4182 " the source vector register group");
4183 }
4184 }
4185 }
4186
4187 if (MCID.TSFlags & RISCVII::VMConstraint) {
4188 int VMIdx = RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vm);
4189 assert(VMIdx >= 0 && "No vm operand?");
4190
4191 if (DestReg == RISCV::V0) {
4192 if (MCID.operands()[Inst.getNumOperands() - 1].OperandType !=
4194 return Error(Loc, "the destination vector register group cannot be V0");
4195
4196 // Regardless masked or unmasked version, the number of operands is the
4197 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
4198 // actually. We need to check the operand to see whether it is masked or
4199 // not.
4200 MCRegister CheckReg = Inst.getOperand(VMIdx).getReg();
4201 assert((!CheckReg.isValid() || CheckReg == RISCV::V0) &&
4202 "Unexpected mask operand register");
4203 if (CheckReg.isValid())
4204 return Error(Loc, "the destination vector register group cannot overlap"
4205 " the mask register");
4206 }
4207 }
4208
4210 // smt.vmadot with sp and hp: the vmask operand (only use V0 or V1) must not
4211 // overlap with any of vd, vs1, or vs2.
4212 int VMaskIdx =
4213 RISCV::getNamedOperandIdx(Inst.getOpcode(), RISCV::OpName::vmask);
4214 MCRegister MaskReg = Inst.getOperand(VMaskIdx).getReg();
4215 if (MaskReg != RISCV::V0 && MaskReg != RISCV::V1)
4216 return Error(Operands[VMaskIdx]->getStartLoc(),
4217 "vmask operand only supports v0 or v1");
4218
4219 unsigned MaskEnc = RI->getEncodingValue(MaskReg);
4220 RISCV::OpName RegOps[] = {RISCV::OpName::vd, RISCV::OpName::vs1,
4221 RISCV::OpName::vs2};
4222 for (RISCV::OpName OpN : RegOps) {
4223 int Idx = RISCV::getNamedOperandIdx(Inst.getOpcode(), OpN);
4224 if (Idx < 0 || !Inst.getOperand(Idx).isReg())
4225 continue;
4226 MCRegister Reg = Inst.getOperand(Idx).getReg();
4227 unsigned RegEnc = RI->getEncodingValue(Reg);
4228 unsigned RegLmul = getLMULFromVectorRegister(Reg);
4229 for (unsigned i = 0; i < RegLmul; i++) {
4230 if ((RegEnc + i) == MaskEnc) {
4231 SMLoc Loc = Operands[Idx]->getStartLoc();
4232 return Error(Loc,
4233 Twine("register conflicts with vmask register ") +
4234 RISCVInstPrinter::getRegisterName(CLOpts, MaskReg));
4235 }
4236 }
4237 }
4238 }
4239
4240 return false;
4241}
4242
4243bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
4245 MCStreamer &Out) {
4246 Inst.setLoc(IDLoc);
4247
4248 switch (Inst.getOpcode()) {
4249 default:
4250 break;
4251 case RISCV::MOP_RR_7: {
4252 // Remap mop.rr.7 x0, x0, x1/x5 to sspush x1/x5.
4253 if (Inst.getOperand(0).getReg() == RISCV::X0 &&
4254 Inst.getOperand(1).getReg() == RISCV::X0 &&
4255 (Inst.getOperand(2).getReg() == RISCV::X1 ||
4256 Inst.getOperand(2).getReg() == RISCV::X5)) {
4257 emitToStreamer(
4258 Out, MCInstBuilder(RISCV::SSPUSH).addOperand(Inst.getOperand(2)));
4259 return false;
4260 }
4261 break;
4262 }
4263 case RISCV::MOP_R_28: {
4264 // Remap mop.r.28 x0, x1/x5 to sspopchk x1/x5.
4265 if (Inst.getOperand(0).getReg() == RISCV::X0 &&
4266 (Inst.getOperand(1).getReg() == RISCV::X1 ||
4267 Inst.getOperand(1).getReg() == RISCV::X5)) {
4268 emitToStreamer(
4269 Out, MCInstBuilder(RISCV::SSPOPCHK).addOperand(Inst.getOperand(1)));
4270 return false;
4271 }
4272 // Remap mop.r.28 rN, x0 to ssrdp rN.
4273 if (Inst.getOperand(0).getReg() != RISCV::X0 &&
4274 Inst.getOperand(1).getReg() == RISCV::X0) {
4275 emitToStreamer(
4276 Out, MCInstBuilder(RISCV::SSRDP).addOperand(Inst.getOperand(0)));
4277 return false;
4278 }
4279 break;
4280 }
4281 case RISCV::PseudoC_ADDI_NOP: {
4282 if (Inst.getOperand(2).getImm() == 0)
4283 emitToStreamer(Out, MCInstBuilder(RISCV::C_NOP));
4284 else
4285 emitToStreamer(
4286 Out, MCInstBuilder(RISCV::C_NOP_HINT).addOperand(Inst.getOperand(2)));
4287 return false;
4288 }
4289 case RISCV::PACK: {
4290 // Convert PACK wth RS2==X0 to ZEXT_H_RV32 to match disassembler output.
4291 if (Inst.getOperand(2).getReg() != RISCV::X0)
4292 break;
4293 if (getSTI().hasFeature(RISCV::Feature64Bit))
4294 break;
4295 emitToStreamer(Out, MCInstBuilder(RISCV::ZEXT_H_RV32)
4296 .addOperand(Inst.getOperand(0))
4297 .addOperand(Inst.getOperand(1)));
4298 return false;
4299 }
4300 case RISCV::PACKW: {
4301 // Convert PACKW with RS2==X0 to ZEXT_H_RV64 to match disassembler output.
4302 if (Inst.getOperand(2).getReg() != RISCV::X0)
4303 break;
4304 emitToStreamer(Out, MCInstBuilder(RISCV::ZEXT_H_RV64)
4305 .addOperand(Inst.getOperand(0))
4306 .addOperand(Inst.getOperand(1)));
4307 return false;
4308 }
4309 case RISCV::PseudoLLAImm:
4310 case RISCV::PseudoLAImm:
4311 case RISCV::PseudoLI: {
4312 MCRegister Reg = Inst.getOperand(0).getReg();
4313 const MCOperand &Op1 = Inst.getOperand(1);
4314 if (Op1.isExpr()) {
4315 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
4316 // Just convert to an addi. This allows compatibility with gas.
4317 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
4318 .addReg(Reg)
4319 .addReg(RISCV::X0)
4320 .addExpr(Op1.getExpr()));
4321 return false;
4322 }
4323 int64_t Imm = Inst.getOperand(1).getImm();
4324 // On RV32 the immediate here can either be a signed or an unsigned
4325 // 32-bit number. Sign extension has to be performed to ensure that Imm
4326 // represents the expected signed 64-bit number.
4327 if (!isRV64())
4329 emitLoadImm(Reg, Imm, Out);
4330 return false;
4331 }
4332 case RISCV::PseudoLLA:
4333 emitLoadLocalAddress(Inst, IDLoc, Out);
4334 return false;
4335 case RISCV::PseudoLGA:
4336 emitLoadGlobalAddress(Inst, IDLoc, Out);
4337 return false;
4338 case RISCV::PseudoLA:
4339 emitLoadAddress(Inst, IDLoc, Out);
4340 return false;
4341 case RISCV::PseudoLA_TLS_IE:
4342 emitLoadTLSIEAddress(Inst, IDLoc, Out);
4343 return false;
4344 case RISCV::PseudoLA_TLS_GD:
4345 emitLoadTLSGDAddress(Inst, IDLoc, Out);
4346 return false;
4347 case RISCV::PseudoLB:
4348 emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
4349 return false;
4350 case RISCV::PseudoLBU:
4351 emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
4352 return false;
4353 case RISCV::PseudoLH:
4354 emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
4355 return false;
4356 case RISCV::PseudoLHU:
4357 emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
4358 return false;
4359 case RISCV::PseudoLW:
4360 emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
4361 return false;
4362 case RISCV::PseudoLWU:
4363 emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
4364 return false;
4365 case RISCV::PseudoLD:
4366 emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
4367 return false;
4368 case RISCV::PseudoLD_RV32:
4369 emitLoadStoreSymbol(Inst, RISCV::LD_RV32, IDLoc, Out, /*HasTmpReg=*/false);
4370 return false;
4371 case RISCV::PseudoFLH:
4372 emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
4373 return false;
4374 case RISCV::PseudoFLW:
4375 emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
4376 return false;
4377 case RISCV::PseudoFLD:
4378 emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
4379 return false;
4380 case RISCV::PseudoFLQ:
4381 emitLoadStoreSymbol(Inst, RISCV::FLQ, IDLoc, Out, /*HasTmpReg=*/true);
4382 return false;
4383 case RISCV::PseudoSB:
4384 emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
4385 return false;
4386 case RISCV::PseudoSH:
4387 emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
4388 return false;
4389 case RISCV::PseudoSW:
4390 emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
4391 return false;
4392 case RISCV::PseudoSD:
4393 emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
4394 return false;
4395 case RISCV::PseudoSD_RV32:
4396 emitLoadStoreSymbol(Inst, RISCV::SD_RV32, IDLoc, Out, /*HasTmpReg=*/true);
4397 return false;
4398 case RISCV::PseudoQC_E_LB:
4399 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessLB, IDLoc, Out,
4400 /*HasTmpReg=*/false);
4401 return false;
4402 case RISCV::PseudoQC_E_LBU:
4403 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessLBU, IDLoc, Out,
4404 /*HasTmpReg=*/false);
4405 return false;
4406 case RISCV::PseudoQC_E_LH:
4407 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessLH, IDLoc, Out,
4408 /*HasTmpReg=*/false);
4409 return false;
4410 case RISCV::PseudoQC_E_LHU:
4411 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessLHU, IDLoc, Out,
4412 /*HasTmpReg=*/false);
4413 return false;
4414 case RISCV::PseudoQC_E_LW:
4415 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessLW, IDLoc, Out,
4416 /*HasTmpReg=*/false);
4417 return false;
4418 case RISCV::PseudoQC_E_SB:
4419 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessSB, IDLoc, Out,
4420 /*HasTmpReg=*/true);
4421 return false;
4422 case RISCV::PseudoQC_E_SH:
4423 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessSH, IDLoc, Out,
4424 /*HasTmpReg=*/true);
4425 return false;
4426 case RISCV::PseudoQC_E_SW:
4427 emitQCELILoadStoreSymbol(Inst, RISCV::PseudoQCAccessSW, IDLoc, Out,
4428 /*HasTmpReg=*/true);
4429 return false;
4430 case RISCV::PseudoFSH:
4431 emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
4432 return false;
4433 case RISCV::PseudoFSW:
4434 emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
4435 return false;
4436 case RISCV::PseudoFSD:
4437 emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
4438 return false;
4439 case RISCV::PseudoFSQ:
4440 emitLoadStoreSymbol(Inst, RISCV::FSQ, IDLoc, Out, /*HasTmpReg=*/true);
4441 return false;
4442 case RISCV::PseudoAddTPRel:
4443 if (checkPseudoAddTPRel(Inst, Operands))
4444 return true;
4445 break;
4446 case RISCV::PseudoTLSDESCCall:
4447 if (checkPseudoTLSDESCCall(Inst, Operands))
4448 return true;
4449 break;
4450 case RISCV::PseudoSEXT_B:
4451 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
4452 return false;
4453 case RISCV::PseudoSEXT_H:
4454 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
4455 return false;
4456 case RISCV::PseudoZEXT_H:
4457 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
4458 return false;
4459 case RISCV::PseudoZEXT_W:
4460 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
4461 return false;
4462 case RISCV::PseudoVMSGEU_VX_M:
4463 case RISCV::PseudoVMSGEU_VX_M_T:
4464 emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
4465 return false;
4466 case RISCV::PseudoVMSGE_VX_M:
4467 case RISCV::PseudoVMSGE_VX_M_T:
4468 emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
4469 return false;
4470 case RISCV::PseudoVMSGE_VI:
4471 case RISCV::PseudoVMSLT_VI: {
4472 // These instructions are signed and so is immediate so we can subtract one
4473 // and change the opcode.
4474 int64_t Imm = Inst.getOperand(2).getImm();
4475 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
4476 : RISCV::VMSLE_VI;
4477 emitToStreamer(Out, MCInstBuilder(Opc)
4478 .addOperand(Inst.getOperand(0))
4479 .addOperand(Inst.getOperand(1))
4480 .addImm(Imm - 1)
4481 .addOperand(Inst.getOperand(3))
4482 .setLoc(IDLoc));
4483 return false;
4484 }
4485 case RISCV::PseudoVMSGEU_VI:
4486 case RISCV::PseudoVMSLTU_VI: {
4487 int64_t Imm = Inst.getOperand(2).getImm();
4488 // Unsigned comparisons are tricky because the immediate is signed. If the
4489 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
4490 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
4491 // vmsne v0, v1, v1 which is always false.
4492 if (Imm == 0) {
4493 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
4494 ? RISCV::VMSEQ_VV
4495 : RISCV::VMSNE_VV;
4496 emitToStreamer(Out, MCInstBuilder(Opc)
4497 .addOperand(Inst.getOperand(0))
4498 .addOperand(Inst.getOperand(1))
4499 .addOperand(Inst.getOperand(1))
4500 .addOperand(Inst.getOperand(3))
4501 .setLoc(IDLoc));
4502 } else {
4503 // Other immediate values can subtract one like signed.
4504 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
4505 ? RISCV::VMSGTU_VI
4506 : RISCV::VMSLEU_VI;
4507 emitToStreamer(Out, MCInstBuilder(Opc)
4508 .addOperand(Inst.getOperand(0))
4509 .addOperand(Inst.getOperand(1))
4510 .addImm(Imm - 1)
4511 .addOperand(Inst.getOperand(3))
4512 .setLoc(IDLoc));
4513 }
4514
4515 return false;
4516 }
4517 case RISCV::PseudoCV_ELW:
4518 emitLoadStoreSymbol(Inst, RISCV::CV_ELW, IDLoc, Out, /*HasTmpReg=*/false);
4519 return false;
4520 }
4521
4522 emitToStreamer(Out, Inst);
4523 return false;
4524}
4525
4526extern "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)
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void applyMnemonicAliases(StringRef &Mnemonic, const FeatureBitset &Features, unsigned VariantID)
uint64_t uint64_t
uint64_t Imm
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.
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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")
static bool matchRegisterNameHelper(const MCSubtargetInfo &STI, MCRegister &Reg, StringRef Name)
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
#define RegName(no)
unsigned Opc
const FeatureInfo AllFeatures[]
static bool hasFeature(StringRef Feature, const FeatureBitset &FeatureBits, ArrayRef< SubtargetFeatureKV > ProcFeatures)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
static bool isGPR(MCRegister Reg, const MCRegisterInfo &MRI)
static MCRegister 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 bool isZvvfmmScaleOpcode(unsigned Opcode)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmParser()
static unsigned getNFforLXSEG(unsigned Opcode)
unsigned getLMULFromVectorRegister(MCRegister Reg)
MachineRegisterInfo & MRI
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
const char * Msg
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:479
This file implements the SmallBitVector class.
This file defines the SmallSet 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:170
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
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
LLVM_ABI SMLoc getLoc() const
Definition AsmLexer.cpp:31
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:33
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.
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
void printExpr(raw_ostream &, const MCExpr &) const
const MCTargetOptions & getTargetOptions() const
Definition MCAsmInfo.h:487
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 MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
const MCObjectFileInfo * getObjectFileInfo() const
Definition MCContext.h:413
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:82
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
unsigned getNumOperands() const
Definition MCInst.h:211
SMLoc getLoc() const
Definition MCInst.h:207
void setLoc(SMLoc loc)
Definition MCInst.h:206
unsigned getOpcode() const
Definition MCInst.h:201
ArrayRef< MCOperand > getOperands() const
Definition MCInst.h:213
void addOperand(const MCOperand Op)
Definition MCInst.h:214
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:209
ArrayRef< MCOperandInfo > operands() const
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
int16_t getOpRegClassID(const MCOperandInfo &OpInfo, unsigned HwModeId) const
Return the ID of the register class to use for OpInfo, for the active HwMode HwModeId.
Definition MCInstrInfo.h:79
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition MCInstrInfo.h:96
bool isPositionIndependent() const
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:165
int64_t getImm() const
Definition MCInst.h:83
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:137
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
bool isReg() const
Definition MCInst.h:64
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:72
const MCExpr * getExpr() const
Definition MCInst.h:117
bool isExpr() const
Definition MCInst.h:68
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
virtual SMLoc getStartLoc() const =0
getStartLoc - Get the location of the first token of this operand.
virtual bool isReg() const =0
isReg - Is this a register operand?
virtual MCRegister getReg() const =0
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
uint16_t getEncodingValue(MCRegister Reg) const
Returns the encoding for 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 and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
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.
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const FeatureBitset & getFeatureBits() const
const FeatureBitset & ToggleFeature(uint64_t FB)
Toggle a feature and return the re-computed feature bits.
ArrayRef< SubtargetFeatureKV > getAllProcessorFeatures() const
Return processor features.
virtual unsigned getHwMode(enum HwModeType type=HwMode_Default) const
HwMode ID corresponding to the 'type' parameter is retrieved from the HwMode bit set of the current s...
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:210
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
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
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(const RISCVMCOptions &CLOpts, MCRegister Reg)
constexpr unsigned id() const
Definition Register.h:100
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
constexpr const char * getPointer() const
Definition SMLoc.h:33
constexpr bool isValid() const
Definition SMLoc.h:28
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
char back() const
Get the last character in the string.
Definition StringRef.h:153
A switch()-like statement whose cases are string literals.
StringSwitch & Cases(std::initializer_list< StringLiteral > CaseStrings, T Value)
#define INT64_MIN
Definition DataTypes.h:74
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
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)
bool isRVE(ABI TargetABI)
Expected< ABI > computeTargetABI(const MCSubtargetInfo &STI, StringRef ABIName)
LLVM_ABI const TagNameMap & getRISCVAttributeTags()
static RoundingMode stringToRoundingMode(StringRef Str)
llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatureBits(const MCSubtargetInfo &STI)
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)
const RISCVMCOptions & getCLOpts(const MCTargetOptions &Options)
Specifier parseSpecifierName(StringRef name)
void updateCZceFeatureImplications(MCSubtargetInfo &STI)
uint16_t Specifier
bool isValidYBNDSWImm(int64_t Imm)
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
static SMTVTypeMode stringToSMTVTypeMode(StringRef Str)
static bool isValidSMTVTypeMode(unsigned Mode)
@ Valid
The data is already valid.
LLVM_ABI TargetOptions getTargetOptions(const cl::LibraryOptionsContext &LibraryOptions, const llvm::Triple &TheTriple)
Common utility function tightly tied to the options listed here.
std::function< llvm::json::Value()> Lambda
Definition Mustache.h:84
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:1129
@ Length
Definition DWP.cpp:577
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:166
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 ...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:1013
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:244
Target & getTheRISCV64beTarget()
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
Op::Description Desc
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SmallVectorImpl< std::unique_ptr< MCParsedAsmOperand > > OperandVector
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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:190
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:547
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
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:2068
DWARFExpression::Operation Op
Target & getTheRISCV64Target()
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
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:1788
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:572
constexpr bool valueOr(BoolOrDefault X, bool Default)
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:199
Target & getTheRISCV32beTarget()
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...