LLVM 19.0.0git
RISCVAsmParser.cpp
Go to the documentation of this file.
1//===-- RISCVAsmParser.cpp - Parse RISC-V assembly to MCInst instructions -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
22#include "llvm/MC/MCAssembler.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCExpr.h"
25#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstrInfo.h"
33#include "llvm/MC/MCStreamer.h"
35#include "llvm/MC/MCValue.h"
42
43#include <limits>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "riscv-asm-parser"
48
49STATISTIC(RISCVNumInstrsCompressed,
50 "Number of RISC-V Compressed instructions emitted");
51
52static cl::opt<bool> AddBuildAttributes("riscv-add-build-attributes",
53 cl::init(false));
54
55namespace llvm {
56extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
57} // namespace llvm
58
59namespace {
60struct RISCVOperand;
61
62struct ParserOptionsSet {
63 bool IsPicEnabled;
64};
65
66class RISCVAsmParser : public MCTargetAsmParser {
67 // This tracks the parsing of the 4 operands that make up the vtype portion
68 // of vset(i)vli instructions which are separated by commas. The state names
69 // represent the next expected operand with Done meaning no other operands are
70 // expected.
71 enum VTypeState {
72 VTypeState_SEW,
73 VTypeState_LMUL,
74 VTypeState_TailPolicy,
75 VTypeState_MaskPolicy,
76 VTypeState_Done,
77 };
78
79 SmallVector<FeatureBitset, 4> FeatureBitStack;
80
81 SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
82 ParserOptionsSet ParserOptions;
83
84 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
85 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
86 bool isRVE() const { return getSTI().hasFeature(RISCV::FeatureStdExtE); }
87 bool enableExperimentalExtension() const {
88 return getSTI().hasFeature(RISCV::Experimental);
89 }
90
91 RISCVTargetStreamer &getTargetStreamer() {
92 assert(getParser().getStreamer().getTargetStreamer() &&
93 "do not have a target streamer");
95 return static_cast<RISCVTargetStreamer &>(TS);
96 }
97
99 unsigned Kind) override;
100 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
101
102 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
103 int64_t Lower, int64_t Upper,
104 const Twine &Msg);
105 bool generateImmOutOfRangeError(SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
106 const Twine &Msg);
107
108 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
111 bool MatchingInlineAsm) override;
112
114 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
116 SMLoc &EndLoc) override;
117
119 SMLoc NameLoc, OperandVector &Operands) override;
120
121 ParseStatus parseDirective(AsmToken DirectiveID) override;
122
123 bool parseVTypeToken(const AsmToken &Tok, VTypeState &State, unsigned &Sew,
124 unsigned &Lmul, bool &Fractional, bool &TailAgnostic,
125 bool &MaskAgnostic);
126 bool generateVTypeError(SMLoc ErrorLoc);
127
128 // Helper to actually emit an instruction to the MCStreamer. Also, when
129 // possible, compression of the instruction is performed.
130 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
131
132 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
133 // synthesize the desired immedate value into the destination register.
134 void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
135
136 // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
137 // helpers such as emitLoadLocalAddress and emitLoadAddress.
138 void emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
139 const MCExpr *Symbol, RISCVMCExpr::VariantKind VKHi,
140 unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
141
142 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
143 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
144
145 // Helper to emit pseudo instruction "lga" used in GOT-rel addressing.
146 void emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
147
148 // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
149 void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
150
151 // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
152 // addressing.
153 void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
154
155 // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
156 // addressing.
157 void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
158
159 // Helper to emit pseudo load/store instruction with a symbol.
160 void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
161 MCStreamer &Out, bool HasTmpReg);
162
163 // Helper to emit pseudo sign/zero extend instruction.
164 void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
165 SMLoc IDLoc, MCStreamer &Out);
166
167 // Helper to emit pseudo vmsge{u}.vx instruction.
168 void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
169
170 // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
171 // Enforcing this using a restricted register class for the second input
172 // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
173 // 'add' is an overloaded mnemonic.
174 bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
175
176 // Checks that a PseudoTLSDESCCall is using x5/t0 in its output operand.
177 // Enforcing this using a restricted register class for the output
178 // operand of PseudoTLSDESCCall results in a poor diagnostic due to the fact
179 // 'jalr' is an overloaded mnemonic.
180 bool checkPseudoTLSDESCCall(MCInst &Inst, OperandVector &Operands);
181
182 // Check instruction constraints.
183 bool validateInstruction(MCInst &Inst, OperandVector &Operands);
184
185 /// Helper for processing MC instructions that have been successfully matched
186 /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
187 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
188 /// in this method.
189 bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
190 MCStreamer &Out);
191
192// Auto-generated instruction matching functions
193#define GET_ASSEMBLER_HEADER
194#include "RISCVGenAsmMatcher.inc"
195
196 ParseStatus parseCSRSystemRegister(OperandVector &Operands);
199 ParseStatus parseRegister(OperandVector &Operands, bool AllowParens = false);
200 ParseStatus parseMemOpBaseReg(OperandVector &Operands);
201 ParseStatus parseZeroOffsetMemOp(OperandVector &Operands);
202 ParseStatus parseOperandWithModifier(OperandVector &Operands);
203 ParseStatus parseBareSymbol(OperandVector &Operands);
204 ParseStatus parseCallSymbol(OperandVector &Operands);
205 ParseStatus parsePseudoJumpSymbol(OperandVector &Operands);
206 ParseStatus parseJALOffset(OperandVector &Operands);
207 ParseStatus parseVTypeI(OperandVector &Operands);
208 ParseStatus parseMaskReg(OperandVector &Operands);
209 ParseStatus parseInsnDirectiveOpcode(OperandVector &Operands);
210 ParseStatus parseInsnCDirectiveOpcode(OperandVector &Operands);
211 ParseStatus parseGPRAsFPR(OperandVector &Operands);
212 template <bool IsRV64Inst> ParseStatus parseGPRPair(OperandVector &Operands);
213 ParseStatus parseGPRPair(OperandVector &Operands, bool IsRV64Inst);
214 ParseStatus parseFRMArg(OperandVector &Operands);
215 ParseStatus parseFenceArg(OperandVector &Operands);
216 ParseStatus parseReglist(OperandVector &Operands);
217 ParseStatus parseRegReg(OperandVector &Operands);
218 ParseStatus parseRetval(OperandVector &Operands);
219 ParseStatus parseZcmpStackAdj(OperandVector &Operands,
220 bool ExpectNegative = false);
221 ParseStatus parseZcmpNegStackAdj(OperandVector &Operands) {
222 return parseZcmpStackAdj(Operands, /*ExpectNegative*/ true);
223 }
224
225 bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
226
227 bool parseDirectiveOption();
228 bool parseDirectiveAttribute();
229 bool parseDirectiveInsn(SMLoc L);
230 bool parseDirectiveVariantCC();
231
232 /// Helper to reset target features for a new arch string. It
233 /// also records the new arch string that is expanded by RISCVISAInfo
234 /// and reports error for invalid arch string.
235 bool resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
236 bool FromOptionDirective);
237
238 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
239 if (!(getSTI().hasFeature(Feature))) {
240 MCSubtargetInfo &STI = copySTI();
242 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
243 }
244 }
245
246 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
247 if (getSTI().hasFeature(Feature)) {
248 MCSubtargetInfo &STI = copySTI();
250 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
251 }
252 }
253
254 void pushFeatureBits() {
255 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
256 "These two stacks must be kept synchronized");
257 FeatureBitStack.push_back(getSTI().getFeatureBits());
258 ParserOptionsStack.push_back(ParserOptions);
259 }
260
261 bool popFeatureBits() {
262 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
263 "These two stacks must be kept synchronized");
264 if (FeatureBitStack.empty())
265 return true;
266
267 FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
268 copySTI().setFeatureBits(FeatureBits);
269 setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
270
271 ParserOptions = ParserOptionsStack.pop_back_val();
272
273 return false;
274 }
275
276 std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
277 std::unique_ptr<RISCVOperand> defaultFRMArgOp() const;
278 std::unique_ptr<RISCVOperand> defaultFRMArgLegacyOp() const;
279
280public:
281 enum RISCVMatchResultTy {
282 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
283 Match_RequiresEvenGPRs,
284#define GET_OPERAND_DIAGNOSTIC_TYPES
285#include "RISCVGenAsmMatcher.inc"
286#undef GET_OPERAND_DIAGNOSTIC_TYPES
287 };
288
289 static bool classifySymbolRef(const MCExpr *Expr,
291 static bool isSymbolDiff(const MCExpr *Expr);
292
293 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
294 const MCInstrInfo &MII, const MCTargetOptions &Options)
295 : MCTargetAsmParser(Options, STI, MII) {
297
298 Parser.addAliasForDirective(".half", ".2byte");
299 Parser.addAliasForDirective(".hword", ".2byte");
300 Parser.addAliasForDirective(".word", ".4byte");
301 Parser.addAliasForDirective(".dword", ".8byte");
302 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
303
304 auto ABIName = StringRef(Options.ABIName);
305 if (ABIName.ends_with("f") && !getSTI().hasFeature(RISCV::FeatureStdExtF)) {
306 errs() << "Hard-float 'f' ABI can't be used for a target that "
307 "doesn't support the F instruction set extension (ignoring "
308 "target-abi)\n";
309 } else if (ABIName.ends_with("d") &&
310 !getSTI().hasFeature(RISCV::FeatureStdExtD)) {
311 errs() << "Hard-float 'd' ABI can't be used for a target that "
312 "doesn't support the D instruction set extension (ignoring "
313 "target-abi)\n";
314 }
315
316 // Use computeTargetABI to check if ABIName is valid. If invalid, output
317 // error message.
319 ABIName);
320
321 const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
322 ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
323
325 getTargetStreamer().emitTargetAttributes(STI, /*EmitStackAlign*/ false);
326 }
327};
328
329/// RISCVOperand - Instances of this class represent a parsed machine
330/// instruction
331struct RISCVOperand final : public MCParsedAsmOperand {
332
333 enum class KindTy {
334 Token,
335 Register,
336 Immediate,
337 FPImmediate,
338 SystemRegister,
339 VType,
340 FRM,
341 Fence,
342 Rlist,
343 Spimm,
344 RegReg,
345 } Kind;
346
347 struct RegOp {
348 MCRegister RegNum;
349 bool IsGPRAsFPR;
350 };
351
352 struct ImmOp {
353 const MCExpr *Val;
354 bool IsRV64;
355 };
356
357 struct FPImmOp {
358 uint64_t Val;
359 };
360
361 struct SysRegOp {
362 const char *Data;
363 unsigned Length;
364 unsigned Encoding;
365 // FIXME: Add the Encoding parsed fields as needed for checks,
366 // e.g.: read/write or user/supervisor/machine privileges.
367 };
368
369 struct VTypeOp {
370 unsigned Val;
371 };
372
373 struct FRMOp {
375 };
376
377 struct FenceOp {
378 unsigned Val;
379 };
380
381 struct RlistOp {
382 unsigned Val;
383 };
384
385 struct SpimmOp {
386 unsigned Val;
387 };
388
389 struct RegRegOp {
390 MCRegister Reg1;
391 MCRegister Reg2;
392 };
393
394 SMLoc StartLoc, EndLoc;
395 union {
396 StringRef Tok;
397 RegOp Reg;
398 ImmOp Imm;
399 FPImmOp FPImm;
400 struct SysRegOp SysReg;
401 struct VTypeOp VType;
402 struct FRMOp FRM;
403 struct FenceOp Fence;
404 struct RlistOp Rlist;
405 struct SpimmOp Spimm;
406 struct RegRegOp RegReg;
407 };
408
409 RISCVOperand(KindTy K) : Kind(K) {}
410
411public:
412 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
413 Kind = o.Kind;
414 StartLoc = o.StartLoc;
415 EndLoc = o.EndLoc;
416 switch (Kind) {
417 case KindTy::Register:
418 Reg = o.Reg;
419 break;
420 case KindTy::Immediate:
421 Imm = o.Imm;
422 break;
423 case KindTy::FPImmediate:
424 FPImm = o.FPImm;
425 break;
426 case KindTy::Token:
427 Tok = o.Tok;
428 break;
429 case KindTy::SystemRegister:
430 SysReg = o.SysReg;
431 break;
432 case KindTy::VType:
433 VType = o.VType;
434 break;
435 case KindTy::FRM:
436 FRM = o.FRM;
437 break;
438 case KindTy::Fence:
439 Fence = o.Fence;
440 break;
441 case KindTy::Rlist:
442 Rlist = o.Rlist;
443 break;
444 case KindTy::Spimm:
445 Spimm = o.Spimm;
446 break;
447 case KindTy::RegReg:
448 RegReg = o.RegReg;
449 break;
450 }
451 }
452
453 bool isToken() const override { return Kind == KindTy::Token; }
454 bool isReg() const override { return Kind == KindTy::Register; }
455 bool isV0Reg() const {
456 return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
457 }
458 bool isAnyReg() const {
459 return Kind == KindTy::Register &&
460 (RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum) ||
461 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg.RegNum) ||
462 RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg.RegNum));
463 }
464 bool isAnyRegC() const {
465 return Kind == KindTy::Register &&
466 (RISCVMCRegisterClasses[RISCV::GPRCRegClassID].contains(
467 Reg.RegNum) ||
468 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(
469 Reg.RegNum));
470 }
471 bool isImm() const override { return Kind == KindTy::Immediate; }
472 bool isMem() const override { return false; }
473 bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
474 bool isRegReg() const { return Kind == KindTy::RegReg; }
475 bool isRlist() const { return Kind == KindTy::Rlist; }
476 bool isSpimm() const { return Kind == KindTy::Spimm; }
477
478 bool isGPR() const {
479 return Kind == KindTy::Register &&
480 RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum);
481 }
482
483 bool isGPRAsFPR() const { return isGPR() && Reg.IsGPRAsFPR; }
484
485 bool isGPRPair() const {
486 return Kind == KindTy::Register &&
487 RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(
488 Reg.RegNum);
489 }
490
491 static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
493 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
494 VK = RE->getKind();
495 return RE->evaluateAsConstant(Imm);
496 }
497
498 if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
500 Imm = CE->getValue();
501 return true;
502 }
503
504 return false;
505 }
506
507 // True if operand is a symbol with no modifiers, or a constant with no
508 // modifiers and isShiftedInt<N-1, 1>(Op).
509 template <int N> bool isBareSimmNLsb0() const {
510 int64_t Imm;
512 if (!isImm())
513 return false;
514 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
515 bool IsValid;
516 if (!IsConstantImm)
517 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
518 else
519 IsValid = isShiftedInt<N - 1, 1>(Imm);
520 return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
521 }
522
523 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
524
525 bool isBareSymbol() const {
526 int64_t Imm;
528 // Must be of 'immediate' type but not a constant.
529 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
530 return false;
531 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
533 }
534
535 bool isCallSymbol() const {
536 int64_t Imm;
538 // Must be of 'immediate' type but not a constant.
539 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
540 return false;
541 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
544 }
545
546 bool isPseudoJumpSymbol() const {
547 int64_t Imm;
549 // Must be of 'immediate' type but not a constant.
550 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
551 return false;
552 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
554 }
555
556 bool isTPRelAddSymbol() const {
557 int64_t Imm;
559 // Must be of 'immediate' type but not a constant.
560 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
561 return false;
562 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
564 }
565
566 bool isTLSDESCCallSymbol() const {
567 int64_t Imm;
569 // Must be of 'immediate' type but not a constant.
570 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
571 return false;
572 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
574 }
575
576 bool isCSRSystemRegister() const { return isSystemRegister(); }
577
578 bool isVTypeImm(unsigned N) const {
579 int64_t Imm;
581 if (!isImm())
582 return false;
583 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
584 return IsConstantImm && isUIntN(N, Imm) && VK == RISCVMCExpr::VK_RISCV_None;
585 }
586
587 // If the last operand of the vsetvli/vsetvli instruction is a constant
588 // expression, KindTy is Immediate.
589 bool isVTypeI10() const {
590 if (Kind == KindTy::Immediate)
591 return isVTypeImm(10);
592 return Kind == KindTy::VType;
593 }
594 bool isVTypeI11() const {
595 if (Kind == KindTy::Immediate)
596 return isVTypeImm(11);
597 return Kind == KindTy::VType;
598 }
599
600 /// Return true if the operand is a valid for the fence instruction e.g.
601 /// ('iorw').
602 bool isFenceArg() const { return Kind == KindTy::Fence; }
603
604 /// Return true if the operand is a valid floating point rounding mode.
605 bool isFRMArg() const { return Kind == KindTy::FRM; }
606 bool isFRMArgLegacy() const { return Kind == KindTy::FRM; }
607 bool isRTZArg() const { return isFRMArg() && FRM.FRM == RISCVFPRndMode::RTZ; }
608
609 /// Return true if the operand is a valid fli.s floating-point immediate.
610 bool isLoadFPImm() const {
611 if (isImm())
612 return isUImm5();
613 if (Kind != KindTy::FPImmediate)
614 return false;
616 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
617 // Don't allow decimal version of the minimum value. It is a different value
618 // for each supported data type.
619 return Idx >= 0 && Idx != 1;
620 }
621
622 bool isImmXLenLI() const {
623 int64_t Imm;
625 if (!isImm())
626 return false;
627 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
628 if (VK == RISCVMCExpr::VK_RISCV_LO ||
632 return true;
633 // Given only Imm, ensuring that the actually specified constant is either
634 // a signed or unsigned 64-bit number is unfortunately impossible.
635 if (IsConstantImm) {
636 return VK == RISCVMCExpr::VK_RISCV_None &&
637 (isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
638 }
639
640 return RISCVAsmParser::isSymbolDiff(getImm());
641 }
642
643 bool isImmXLenLI_Restricted() const {
644 int64_t Imm;
646 if (!isImm())
647 return false;
648 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
649 // 'la imm' supports constant immediates only.
650 return IsConstantImm && (VK == RISCVMCExpr::VK_RISCV_None) &&
651 (isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
652 }
653
654 bool isUImmLog2XLen() const {
655 int64_t Imm;
657 if (!isImm())
658 return false;
659 if (!evaluateConstantImm(getImm(), Imm, VK) ||
661 return false;
662 return (isRV64Imm() && isUInt<6>(Imm)) || isUInt<5>(Imm);
663 }
664
665 bool isUImmLog2XLenNonZero() const {
666 int64_t Imm;
668 if (!isImm())
669 return false;
670 if (!evaluateConstantImm(getImm(), Imm, VK) ||
672 return false;
673 if (Imm == 0)
674 return false;
675 return (isRV64Imm() && isUInt<6>(Imm)) || isUInt<5>(Imm);
676 }
677
678 bool isUImmLog2XLenHalf() const {
679 int64_t Imm;
681 if (!isImm())
682 return false;
683 if (!evaluateConstantImm(getImm(), Imm, VK) ||
685 return false;
686 return (isRV64Imm() && isUInt<5>(Imm)) || isUInt<4>(Imm);
687 }
688
689 template <unsigned N> bool IsUImm() const {
690 int64_t Imm;
692 if (!isImm())
693 return false;
694 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
695 return IsConstantImm && isUInt<N>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
696 }
697
698 bool isUImm1() const { return IsUImm<1>(); }
699 bool isUImm2() const { return IsUImm<2>(); }
700 bool isUImm3() const { return IsUImm<3>(); }
701 bool isUImm4() const { return IsUImm<4>(); }
702 bool isUImm5() const { return IsUImm<5>(); }
703 bool isUImm6() const { return IsUImm<6>(); }
704 bool isUImm7() const { return IsUImm<7>(); }
705 bool isUImm8() const { return IsUImm<8>(); }
706 bool isUImm20() const { return IsUImm<20>(); }
707
708 bool isUImm8GE32() const {
709 int64_t Imm;
711 if (!isImm())
712 return false;
713 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
714 return IsConstantImm && isUInt<8>(Imm) && Imm >= 32 &&
716 }
717
718 bool isRnumArg() const {
719 int64_t Imm;
721 if (!isImm())
722 return false;
723 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
724 return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(10) &&
726 }
727
728 bool isRnumArg_0_7() const {
729 int64_t Imm;
731 if (!isImm())
732 return false;
733 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
734 return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(7) &&
736 }
737
738 bool isRnumArg_1_10() const {
739 int64_t Imm;
741 if (!isImm())
742 return false;
743 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
744 return IsConstantImm && Imm >= INT64_C(1) && Imm <= INT64_C(10) &&
746 }
747
748 bool isRnumArg_2_14() const {
749 int64_t Imm;
751 if (!isImm())
752 return false;
753 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
754 return IsConstantImm && Imm >= INT64_C(2) && Imm <= INT64_C(14) &&
756 }
757
758 bool isSImm5() const {
759 if (!isImm())
760 return false;
762 int64_t Imm;
763 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
764 return IsConstantImm && isInt<5>(fixImmediateForRV32(Imm, isRV64Imm())) &&
766 }
767
768 bool isSImm6() const {
769 if (!isImm())
770 return false;
772 int64_t Imm;
773 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
774 return IsConstantImm && isInt<6>(fixImmediateForRV32(Imm, isRV64Imm())) &&
776 }
777
778 bool isSImm6NonZero() const {
779 if (!isImm())
780 return false;
782 int64_t Imm;
783 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
784 return IsConstantImm && Imm != 0 &&
785 isInt<6>(fixImmediateForRV32(Imm, isRV64Imm())) &&
787 }
788
789 bool isCLUIImm() const {
790 if (!isImm())
791 return false;
792 int64_t Imm;
794 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
795 return IsConstantImm && (Imm != 0) &&
796 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
798 }
799
800 bool isUImm2Lsb0() const {
801 if (!isImm())
802 return false;
803 int64_t Imm;
805 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
806 return IsConstantImm && isShiftedUInt<1, 1>(Imm) &&
808 }
809
810 bool isUImm7Lsb00() const {
811 if (!isImm())
812 return false;
813 int64_t Imm;
815 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
816 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
818 }
819
820 bool isUImm8Lsb00() const {
821 if (!isImm())
822 return false;
823 int64_t Imm;
825 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
826 return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
828 }
829
830 bool isUImm8Lsb000() const {
831 if (!isImm())
832 return false;
833 int64_t Imm;
835 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
836 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
838 }
839
840 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
841
842 bool isUImm9Lsb000() const {
843 if (!isImm())
844 return false;
845 int64_t Imm;
847 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
848 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
850 }
851
852 bool isUImm10Lsb00NonZero() const {
853 if (!isImm())
854 return false;
855 int64_t Imm;
857 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
858 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
860 }
861
862 // If this a RV32 and the immediate is a uimm32, sign extend it to 32 bits.
863 // This allows writing 'addi a0, a0, 0xffffffff'.
864 static int64_t fixImmediateForRV32(int64_t Imm, bool IsRV64Imm) {
865 if (IsRV64Imm || !isUInt<32>(Imm))
866 return Imm;
867 return SignExtend64<32>(Imm);
868 }
869
870 bool isSImm12() const {
872 int64_t Imm;
873 bool IsValid;
874 if (!isImm())
875 return false;
876 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
877 if (!IsConstantImm)
878 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
879 else
880 IsValid = isInt<12>(fixImmediateForRV32(Imm, isRV64Imm()));
881 return IsValid && ((IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None) ||
887 }
888
889 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
890
891 bool isSImm12Lsb00000() const {
892 if (!isImm())
893 return false;
895 int64_t Imm;
896 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
897 return IsConstantImm && isShiftedInt<7, 5>(Imm) &&
899 }
900
901 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
902
903 bool isSImm10Lsb0000NonZero() const {
904 if (!isImm())
905 return false;
906 int64_t Imm;
908 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
909 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
911 }
912
913 bool isUImm20LUI() const {
915 int64_t Imm;
916 bool IsValid;
917 if (!isImm())
918 return false;
919 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
920 if (!IsConstantImm) {
921 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
922 return IsValid && (VK == RISCVMCExpr::VK_RISCV_HI ||
924 } else {
925 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
928 }
929 }
930
931 bool isUImm20AUIPC() const {
933 int64_t Imm;
934 bool IsValid;
935 if (!isImm())
936 return false;
937 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
938 if (!IsConstantImm) {
939 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
940 return IsValid && (VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
945 }
946
947 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
953 }
954
955 bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
956
957 bool isImmZero() const {
958 if (!isImm())
959 return false;
960 int64_t Imm;
962 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
963 return IsConstantImm && (Imm == 0) && VK == RISCVMCExpr::VK_RISCV_None;
964 }
965
966 bool isSImm5Plus1() const {
967 if (!isImm())
968 return false;
970 int64_t Imm;
971 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
972 return IsConstantImm &&
973 isInt<5>(fixImmediateForRV32(Imm, isRV64Imm()) - 1) &&
975 }
976
977 /// getStartLoc - Gets location of the first token of this operand
978 SMLoc getStartLoc() const override { return StartLoc; }
979 /// getEndLoc - Gets location of the last token of this operand
980 SMLoc getEndLoc() const override { return EndLoc; }
981 /// True if this operand is for an RV64 instruction
982 bool isRV64Imm() const {
983 assert(Kind == KindTy::Immediate && "Invalid type access!");
984 return Imm.IsRV64;
985 }
986
987 MCRegister getReg() const override {
988 assert(Kind == KindTy::Register && "Invalid type access!");
989 return Reg.RegNum;
990 }
991
992 StringRef getSysReg() const {
993 assert(Kind == KindTy::SystemRegister && "Invalid type access!");
994 return StringRef(SysReg.Data, SysReg.Length);
995 }
996
997 const MCExpr *getImm() const {
998 assert(Kind == KindTy::Immediate && "Invalid type access!");
999 return Imm.Val;
1000 }
1001
1002 uint64_t getFPConst() const {
1003 assert(Kind == KindTy::FPImmediate && "Invalid type access!");
1004 return FPImm.Val;
1005 }
1006
1007 StringRef getToken() const {
1008 assert(Kind == KindTy::Token && "Invalid type access!");
1009 return Tok;
1010 }
1011
1012 unsigned getVType() const {
1013 assert(Kind == KindTy::VType && "Invalid type access!");
1014 return VType.Val;
1015 }
1016
1017 RISCVFPRndMode::RoundingMode getFRM() const {
1018 assert(Kind == KindTy::FRM && "Invalid type access!");
1019 return FRM.FRM;
1020 }
1021
1022 unsigned getFence() const {
1023 assert(Kind == KindTy::Fence && "Invalid type access!");
1024 return Fence.Val;
1025 }
1026
1027 void print(raw_ostream &OS) const override {
1028 auto RegName = [](MCRegister Reg) {
1029 if (Reg)
1031 else
1032 return "noreg";
1033 };
1034
1035 switch (Kind) {
1036 case KindTy::Immediate:
1037 OS << *getImm();
1038 break;
1039 case KindTy::FPImmediate:
1040 break;
1041 case KindTy::Register:
1042 OS << "<register " << RegName(getReg()) << ">";
1043 break;
1044 case KindTy::Token:
1045 OS << "'" << getToken() << "'";
1046 break;
1047 case KindTy::SystemRegister:
1048 OS << "<sysreg: " << getSysReg() << '>';
1049 break;
1050 case KindTy::VType:
1051 OS << "<vtype: ";
1052 RISCVVType::printVType(getVType(), OS);
1053 OS << '>';
1054 break;
1055 case KindTy::FRM:
1056 OS << "<frm: ";
1057 roundingModeToString(getFRM());
1058 OS << '>';
1059 break;
1060 case KindTy::Fence:
1061 OS << "<fence: ";
1062 OS << getFence();
1063 OS << '>';
1064 break;
1065 case KindTy::Rlist:
1066 OS << "<rlist: ";
1067 RISCVZC::printRlist(Rlist.Val, OS);
1068 OS << '>';
1069 break;
1070 case KindTy::Spimm:
1071 OS << "<Spimm: ";
1072 OS << Spimm.Val;
1073 OS << '>';
1074 break;
1075 case KindTy::RegReg:
1076 OS << "<RegReg: Reg1 " << RegName(RegReg.Reg1);
1077 OS << " Reg2 " << RegName(RegReg.Reg2);
1078 break;
1079 }
1080 }
1081
1082 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S) {
1083 auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
1084 Op->Tok = Str;
1085 Op->StartLoc = S;
1086 Op->EndLoc = S;
1087 return Op;
1088 }
1089
1090 static std::unique_ptr<RISCVOperand>
1091 createReg(unsigned RegNo, SMLoc S, SMLoc E, bool IsGPRAsFPR = false) {
1092 auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
1093 Op->Reg.RegNum = RegNo;
1094 Op->Reg.IsGPRAsFPR = IsGPRAsFPR;
1095 Op->StartLoc = S;
1096 Op->EndLoc = E;
1097 return Op;
1098 }
1099
1100 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
1101 SMLoc E, bool IsRV64) {
1102 auto Op = std::make_unique<RISCVOperand>(KindTy::Immediate);
1103 Op->Imm.Val = Val;
1104 Op->Imm.IsRV64 = IsRV64;
1105 Op->StartLoc = S;
1106 Op->EndLoc = E;
1107 return Op;
1108 }
1109
1110 static std::unique_ptr<RISCVOperand> createFPImm(uint64_t Val, SMLoc S) {
1111 auto Op = std::make_unique<RISCVOperand>(KindTy::FPImmediate);
1112 Op->FPImm.Val = Val;
1113 Op->StartLoc = S;
1114 Op->EndLoc = S;
1115 return Op;
1116 }
1117
1118 static std::unique_ptr<RISCVOperand> createSysReg(StringRef Str, SMLoc S,
1119 unsigned Encoding) {
1120 auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
1121 Op->SysReg.Data = Str.data();
1122 Op->SysReg.Length = Str.size();
1123 Op->SysReg.Encoding = Encoding;
1124 Op->StartLoc = S;
1125 Op->EndLoc = S;
1126 return Op;
1127 }
1128
1129 static std::unique_ptr<RISCVOperand>
1130 createFRMArg(RISCVFPRndMode::RoundingMode FRM, SMLoc S) {
1131 auto Op = std::make_unique<RISCVOperand>(KindTy::FRM);
1132 Op->FRM.FRM = FRM;
1133 Op->StartLoc = S;
1134 Op->EndLoc = S;
1135 return Op;
1136 }
1137
1138 static std::unique_ptr<RISCVOperand> createFenceArg(unsigned Val, SMLoc S) {
1139 auto Op = std::make_unique<RISCVOperand>(KindTy::Fence);
1140 Op->Fence.Val = Val;
1141 Op->StartLoc = S;
1142 Op->EndLoc = S;
1143 return Op;
1144 }
1145
1146 static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S) {
1147 auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
1148 Op->VType.Val = VTypeI;
1149 Op->StartLoc = S;
1150 Op->EndLoc = S;
1151 return Op;
1152 }
1153
1154 static std::unique_ptr<RISCVOperand> createRlist(unsigned RlistEncode,
1155 SMLoc S) {
1156 auto Op = std::make_unique<RISCVOperand>(KindTy::Rlist);
1157 Op->Rlist.Val = RlistEncode;
1158 Op->StartLoc = S;
1159 return Op;
1160 }
1161
1162 static std::unique_ptr<RISCVOperand> createRegReg(unsigned Reg1No,
1163 unsigned Reg2No, SMLoc S) {
1164 auto Op = std::make_unique<RISCVOperand>(KindTy::RegReg);
1165 Op->RegReg.Reg1 = Reg1No;
1166 Op->RegReg.Reg2 = Reg2No;
1167 Op->StartLoc = S;
1168 Op->EndLoc = S;
1169 return Op;
1170 }
1171
1172 static std::unique_ptr<RISCVOperand> createSpimm(unsigned Spimm, SMLoc S) {
1173 auto Op = std::make_unique<RISCVOperand>(KindTy::Spimm);
1174 Op->Spimm.Val = Spimm;
1175 Op->StartLoc = S;
1176 return Op;
1177 }
1178
1179 static void addExpr(MCInst &Inst, const MCExpr *Expr, bool IsRV64Imm) {
1180 assert(Expr && "Expr shouldn't be null!");
1181 int64_t Imm = 0;
1183 bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
1184
1185 if (IsConstant)
1186 Inst.addOperand(
1187 MCOperand::createImm(fixImmediateForRV32(Imm, IsRV64Imm)));
1188 else
1190 }
1191
1192 // Used by the TableGen Code
1193 void addRegOperands(MCInst &Inst, unsigned N) const {
1194 assert(N == 1 && "Invalid number of operands!");
1196 }
1197
1198 void addImmOperands(MCInst &Inst, unsigned N) const {
1199 assert(N == 1 && "Invalid number of operands!");
1200 addExpr(Inst, getImm(), isRV64Imm());
1201 }
1202
1203 void addFPImmOperands(MCInst &Inst, unsigned N) const {
1204 assert(N == 1 && "Invalid number of operands!");
1205 if (isImm()) {
1206 addExpr(Inst, getImm(), isRV64Imm());
1207 return;
1208 }
1209
1211 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
1213 }
1214
1215 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
1216 assert(N == 1 && "Invalid number of operands!");
1217 Inst.addOperand(MCOperand::createImm(Fence.Val));
1218 }
1219
1220 void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1221 assert(N == 1 && "Invalid number of operands!");
1222 Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
1223 }
1224
1225 // Support non-canonical syntax:
1226 // "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
1227 // "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
1228 void addVTypeIOperands(MCInst &Inst, unsigned N) const {
1229 assert(N == 1 && "Invalid number of operands!");
1230 int64_t Imm = 0;
1231 if (Kind == KindTy::Immediate) {
1233 [[maybe_unused]] bool IsConstantImm =
1234 evaluateConstantImm(getImm(), Imm, VK);
1235 assert(IsConstantImm && "Invalid VTypeI Operand!");
1236 } else {
1237 Imm = getVType();
1238 }
1240 }
1241
1242 void addRlistOperands(MCInst &Inst, unsigned N) const {
1243 assert(N == 1 && "Invalid number of operands!");
1244 Inst.addOperand(MCOperand::createImm(Rlist.Val));
1245 }
1246
1247 void addRegRegOperands(MCInst &Inst, unsigned N) const {
1248 assert(N == 2 && "Invalid number of operands!");
1251 }
1252
1253 void addSpimmOperands(MCInst &Inst, unsigned N) const {
1254 assert(N == 1 && "Invalid number of operands!");
1255 Inst.addOperand(MCOperand::createImm(Spimm.Val));
1256 }
1257
1258 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
1259 assert(N == 1 && "Invalid number of operands!");
1260 Inst.addOperand(MCOperand::createImm(getFRM()));
1261 }
1262};
1263} // end anonymous namespace.
1264
1265#define GET_REGISTER_MATCHER
1266#define GET_SUBTARGET_FEATURE_NAME
1267#define GET_MATCHER_IMPLEMENTATION
1268#define GET_MNEMONIC_SPELL_CHECKER
1269#include "RISCVGenAsmMatcher.inc"
1270
1272 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1273 return Reg - RISCV::F0_D + RISCV::F0_H;
1274}
1275
1277 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1278 return Reg - RISCV::F0_D + RISCV::F0_F;
1279}
1280
1282 unsigned Kind) {
1283 unsigned RegClassID;
1284 if (Kind == MCK_VRM2)
1285 RegClassID = RISCV::VRM2RegClassID;
1286 else if (Kind == MCK_VRM4)
1287 RegClassID = RISCV::VRM4RegClassID;
1288 else if (Kind == MCK_VRM8)
1289 RegClassID = RISCV::VRM8RegClassID;
1290 else
1291 return 0;
1292 return RI.getMatchingSuperReg(Reg, RISCV::sub_vrm1_0,
1293 &RISCVMCRegisterClasses[RegClassID]);
1294}
1295
1296unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1297 unsigned Kind) {
1298 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
1299 if (!Op.isReg())
1300 return Match_InvalidOperand;
1301
1302 MCRegister Reg = Op.getReg();
1303 bool IsRegFPR64 =
1304 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
1305 bool IsRegFPR64C =
1306 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
1307 bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
1308
1309 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
1310 // register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
1311 if ((IsRegFPR64 && Kind == MCK_FPR32) ||
1312 (IsRegFPR64C && Kind == MCK_FPR32C)) {
1313 Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
1314 return Match_Success;
1315 }
1316 // As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
1317 // register from FPR64 to FPR16 if necessary.
1318 if (IsRegFPR64 && Kind == MCK_FPR16) {
1319 Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
1320 return Match_Success;
1321 }
1322 // As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
1323 // the register from VR to VRM2/VRM4/VRM8 if necessary.
1324 if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
1325 Op.Reg.RegNum = convertVRToVRMx(*getContext().getRegisterInfo(), Reg, Kind);
1326 if (Op.Reg.RegNum == 0)
1327 return Match_InvalidOperand;
1328 return Match_Success;
1329 }
1330 return Match_InvalidOperand;
1331}
1332
1333unsigned RISCVAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1334 const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
1335
1336 for (unsigned I = 0; I < MCID.NumOperands; ++I) {
1337 if (MCID.operands()[I].RegClass == RISCV::GPRPairRegClassID) {
1338 const auto &Op = Inst.getOperand(I);
1339 assert(Op.isReg());
1340
1341 MCRegister Reg = Op.getReg();
1342 if (RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(Reg))
1343 continue;
1344
1345 // FIXME: We should form a paired register during parsing/matching.
1346 if (((Reg.id() - RISCV::X0) & 1) != 0)
1347 return Match_RequiresEvenGPRs;
1348 }
1349 }
1350
1351 return Match_Success;
1352}
1353
1354bool RISCVAsmParser::generateImmOutOfRangeError(
1355 SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
1356 const Twine &Msg = "immediate must be an integer in the range") {
1357 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
1358}
1359
1360bool RISCVAsmParser::generateImmOutOfRangeError(
1361 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
1362 const Twine &Msg = "immediate must be an integer in the range") {
1363 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1364 return generateImmOutOfRangeError(ErrorLoc, Lower, Upper, Msg);
1365}
1366
1367bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1369 MCStreamer &Out,
1371 bool MatchingInlineAsm) {
1372 MCInst Inst;
1373 FeatureBitset MissingFeatures;
1374
1375 auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
1376 MatchingInlineAsm);
1377 switch (Result) {
1378 default:
1379 break;
1380 case Match_Success:
1381 if (validateInstruction(Inst, Operands))
1382 return true;
1383 return processInstruction(Inst, IDLoc, Operands, Out);
1384 case Match_MissingFeature: {
1385 assert(MissingFeatures.any() && "Unknown missing features!");
1386 bool FirstFeature = true;
1387 std::string Msg = "instruction requires the following:";
1388 for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
1389 if (MissingFeatures[i]) {
1390 Msg += FirstFeature ? " " : ", ";
1391 Msg += getSubtargetFeatureName(i);
1392 FirstFeature = false;
1393 }
1394 }
1395 return Error(IDLoc, Msg);
1396 }
1397 case Match_MnemonicFail: {
1398 FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1399 std::string Suggestion = RISCVMnemonicSpellCheck(
1400 ((RISCVOperand &)*Operands[0]).getToken(), FBS, 0);
1401 return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
1402 }
1403 case Match_InvalidOperand: {
1404 SMLoc ErrorLoc = IDLoc;
1405 if (ErrorInfo != ~0ULL) {
1406 if (ErrorInfo >= Operands.size())
1407 return Error(ErrorLoc, "too few operands for instruction");
1408
1409 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1410 if (ErrorLoc == SMLoc())
1411 ErrorLoc = IDLoc;
1412 }
1413 return Error(ErrorLoc, "invalid operand for instruction");
1414 }
1415 }
1416
1417 // Handle the case when the error message is of specific type
1418 // other than the generic Match_InvalidOperand, and the
1419 // corresponding operand is missing.
1420 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
1421 SMLoc ErrorLoc = IDLoc;
1422 if (ErrorInfo != ~0ULL && ErrorInfo >= Operands.size())
1423 return Error(ErrorLoc, "too few operands for instruction");
1424 }
1425
1426 switch (Result) {
1427 default:
1428 break;
1429 case Match_RequiresEvenGPRs:
1430 return Error(IDLoc,
1431 "double precision floating point operands must use even "
1432 "numbered X register");
1433 case Match_InvalidImmXLenLI:
1434 if (isRV64()) {
1435 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1436 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
1437 }
1438 return generateImmOutOfRangeError(Operands, ErrorInfo,
1439 std::numeric_limits<int32_t>::min(),
1440 std::numeric_limits<uint32_t>::max());
1441 case Match_InvalidImmXLenLI_Restricted:
1442 if (isRV64()) {
1443 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1444 return Error(ErrorLoc, "operand either must be a constant 64-bit integer "
1445 "or a bare symbol name");
1446 }
1447 return generateImmOutOfRangeError(
1448 Operands, ErrorInfo, std::numeric_limits<int32_t>::min(),
1449 std::numeric_limits<uint32_t>::max(),
1450 "operand either must be a bare symbol name or an immediate integer in "
1451 "the range");
1452 case Match_InvalidImmZero: {
1453 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1454 return Error(ErrorLoc, "immediate must be zero");
1455 }
1456 case Match_InvalidUImmLog2XLen:
1457 if (isRV64())
1458 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1459 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1460 case Match_InvalidUImmLog2XLenNonZero:
1461 if (isRV64())
1462 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
1463 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
1464 case Match_InvalidUImmLog2XLenHalf:
1465 if (isRV64())
1466 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1467 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1468 case Match_InvalidUImm1:
1469 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 1) - 1);
1470 case Match_InvalidUImm2:
1471 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 2) - 1);
1472 case Match_InvalidUImm2Lsb0:
1473 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 2,
1474 "immediate must be one of");
1475 case Match_InvalidUImm3:
1476 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 3) - 1);
1477 case Match_InvalidUImm4:
1478 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1479 case Match_InvalidUImm5:
1480 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1481 case Match_InvalidUImm6:
1482 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1483 case Match_InvalidUImm7:
1484 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 7) - 1);
1485 case Match_InvalidUImm8:
1486 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 8) - 1);
1487 case Match_InvalidUImm8GE32:
1488 return generateImmOutOfRangeError(Operands, ErrorInfo, 32, (1 << 8) - 1);
1489 case Match_InvalidSImm5:
1490 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4),
1491 (1 << 4) - 1);
1492 case Match_InvalidSImm6:
1493 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
1494 (1 << 5) - 1);
1495 case Match_InvalidSImm6NonZero:
1496 return generateImmOutOfRangeError(
1497 Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
1498 "immediate must be non-zero in the range");
1499 case Match_InvalidCLUIImm:
1500 return generateImmOutOfRangeError(
1501 Operands, ErrorInfo, 1, (1 << 5) - 1,
1502 "immediate must be in [0xfffe0, 0xfffff] or");
1503 case Match_InvalidUImm7Lsb00:
1504 return generateImmOutOfRangeError(
1505 Operands, ErrorInfo, 0, (1 << 7) - 4,
1506 "immediate must be a multiple of 4 bytes in the range");
1507 case Match_InvalidUImm8Lsb00:
1508 return generateImmOutOfRangeError(
1509 Operands, ErrorInfo, 0, (1 << 8) - 4,
1510 "immediate must be a multiple of 4 bytes in the range");
1511 case Match_InvalidUImm8Lsb000:
1512 return generateImmOutOfRangeError(
1513 Operands, ErrorInfo, 0, (1 << 8) - 8,
1514 "immediate must be a multiple of 8 bytes in the range");
1515 case Match_InvalidSImm9Lsb0:
1516 return generateImmOutOfRangeError(
1517 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
1518 "immediate must be a multiple of 2 bytes in the range");
1519 case Match_InvalidUImm9Lsb000:
1520 return generateImmOutOfRangeError(
1521 Operands, ErrorInfo, 0, (1 << 9) - 8,
1522 "immediate must be a multiple of 8 bytes in the range");
1523 case Match_InvalidUImm10Lsb00NonZero:
1524 return generateImmOutOfRangeError(
1525 Operands, ErrorInfo, 4, (1 << 10) - 4,
1526 "immediate must be a multiple of 4 bytes in the range");
1527 case Match_InvalidSImm10Lsb0000NonZero:
1528 return generateImmOutOfRangeError(
1529 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
1530 "immediate must be a multiple of 16 bytes and non-zero in the range");
1531 case Match_InvalidSImm12:
1532 return generateImmOutOfRangeError(
1533 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
1534 "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an "
1535 "integer in the range");
1536 case Match_InvalidSImm12Lsb0:
1537 return generateImmOutOfRangeError(
1538 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
1539 "immediate must be a multiple of 2 bytes in the range");
1540 case Match_InvalidSImm12Lsb00000:
1541 return generateImmOutOfRangeError(
1542 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 32,
1543 "immediate must be a multiple of 32 bytes in the range");
1544 case Match_InvalidSImm13Lsb0:
1545 return generateImmOutOfRangeError(
1546 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
1547 "immediate must be a multiple of 2 bytes in the range");
1548 case Match_InvalidUImm20LUI:
1549 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
1550 "operand must be a symbol with "
1551 "%hi/%tprel_hi modifier or an integer in "
1552 "the range");
1553 case Match_InvalidUImm20:
1554 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
1555 case Match_InvalidUImm20AUIPC:
1556 return generateImmOutOfRangeError(
1557 Operands, ErrorInfo, 0, (1 << 20) - 1,
1558 "operand must be a symbol with a "
1559 "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi modifier or "
1560 "an integer in the range");
1561 case Match_InvalidSImm21Lsb0JAL:
1562 return generateImmOutOfRangeError(
1563 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
1564 "immediate must be a multiple of 2 bytes in the range");
1565 case Match_InvalidCSRSystemRegister: {
1566 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
1567 "operand must be a valid system register "
1568 "name or an integer in the range");
1569 }
1570 case Match_InvalidLoadFPImm: {
1571 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1572 return Error(ErrorLoc, "operand must be a valid floating-point constant");
1573 }
1574 case Match_InvalidBareSymbol: {
1575 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1576 return Error(ErrorLoc, "operand must be a bare symbol name");
1577 }
1578 case Match_InvalidPseudoJumpSymbol: {
1579 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1580 return Error(ErrorLoc, "operand must be a valid jump target");
1581 }
1582 case Match_InvalidCallSymbol: {
1583 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1584 return Error(ErrorLoc, "operand must be a bare symbol name");
1585 }
1586 case Match_InvalidTPRelAddSymbol: {
1587 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1588 return Error(ErrorLoc, "operand must be a symbol with %tprel_add modifier");
1589 }
1590 case Match_InvalidTLSDESCCallSymbol: {
1591 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1592 return Error(ErrorLoc,
1593 "operand must be a symbol with %tlsdesc_call modifier");
1594 }
1595 case Match_InvalidRTZArg: {
1596 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1597 return Error(ErrorLoc, "operand must be 'rtz' floating-point rounding mode");
1598 }
1599 case Match_InvalidVTypeI: {
1600 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1601 return generateVTypeError(ErrorLoc);
1602 }
1603 case Match_InvalidVMaskRegister: {
1604 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1605 return Error(ErrorLoc, "operand must be v0.t");
1606 }
1607 case Match_InvalidSImm5Plus1: {
1608 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4) + 1,
1609 (1 << 4),
1610 "immediate must be in the range");
1611 }
1612 case Match_InvalidRlist: {
1613 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1614 return Error(
1615 ErrorLoc,
1616 "operand must be {ra [, s0[-sN]]} or {x1 [, x8[-x9][, x18[-xN]]]}");
1617 }
1618 case Match_InvalidStackAdj: {
1619 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1620 return Error(
1621 ErrorLoc,
1622 "stack adjustment is invalid for this instruction and register list; "
1623 "refer to Zc spec for a detailed range of stack adjustment");
1624 }
1625 case Match_InvalidRnumArg: {
1626 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 10);
1627 }
1628 case Match_InvalidRegReg: {
1629 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1630 return Error(ErrorLoc, "operands must be register and register");
1631 }
1632 }
1633
1634 llvm_unreachable("Unknown match type detected!");
1635}
1636
1637// Attempts to match Name as a register (either using the default name or
1638// alternative ABI names), setting RegNo to the matching register. Upon
1639// failure, returns a non-valid MCRegister. If IsRVE, then registers x16-x31
1640// will be rejected.
1641MCRegister RISCVAsmParser::matchRegisterNameHelper(StringRef Name) const {
1643 // The 16-/32- and 64-bit FPRs have the same asm name. Check that the initial
1644 // match always matches the 64-bit variant, and not the 16/32-bit one.
1645 assert(!(Reg >= RISCV::F0_H && Reg <= RISCV::F31_H));
1646 assert(!(Reg >= RISCV::F0_F && Reg <= RISCV::F31_F));
1647 // The default FPR register class is based on the tablegen enum ordering.
1648 static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1649 static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1650 if (!Reg)
1652 if (isRVE() && Reg >= RISCV::X16 && Reg <= RISCV::X31)
1653 Reg = RISCV::NoRegister;
1654 return Reg;
1655}
1656
1657bool RISCVAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1658 SMLoc &EndLoc) {
1659 if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
1660 return Error(StartLoc, "invalid register name");
1661 return false;
1662}
1663
1664ParseStatus RISCVAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1665 SMLoc &EndLoc) {
1666 const AsmToken &Tok = getParser().getTok();
1667 StartLoc = Tok.getLoc();
1668 EndLoc = Tok.getEndLoc();
1669 StringRef Name = getLexer().getTok().getIdentifier();
1670
1672 if (!Reg)
1673 return ParseStatus::NoMatch;
1674
1675 getParser().Lex(); // Eat identifier token.
1676 return ParseStatus::Success;
1677}
1678
1679ParseStatus RISCVAsmParser::parseRegister(OperandVector &Operands,
1680 bool AllowParens) {
1681 SMLoc FirstS = getLoc();
1682 bool HadParens = false;
1683 AsmToken LParen;
1684
1685 // If this is an LParen and a parenthesised register name is allowed, parse it
1686 // atomically.
1687 if (AllowParens && getLexer().is(AsmToken::LParen)) {
1688 AsmToken Buf[2];
1689 size_t ReadCount = getLexer().peekTokens(Buf);
1690 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1691 HadParens = true;
1692 LParen = getParser().getTok();
1693 getParser().Lex(); // Eat '('
1694 }
1695 }
1696
1697 switch (getLexer().getKind()) {
1698 default:
1699 if (HadParens)
1700 getLexer().UnLex(LParen);
1701 return ParseStatus::NoMatch;
1703 StringRef Name = getLexer().getTok().getIdentifier();
1705
1706 if (!RegNo) {
1707 if (HadParens)
1708 getLexer().UnLex(LParen);
1709 return ParseStatus::NoMatch;
1710 }
1711 if (HadParens)
1712 Operands.push_back(RISCVOperand::createToken("(", FirstS));
1713 SMLoc S = getLoc();
1715 getLexer().Lex();
1716 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
1717 }
1718
1719 if (HadParens) {
1720 getParser().Lex(); // Eat ')'
1721 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
1722 }
1723
1724 return ParseStatus::Success;
1725}
1726
1727ParseStatus RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
1728 SMLoc S = getLoc();
1729 SMLoc E;
1730 const MCExpr *Res;
1731
1732 switch (getLexer().getKind()) {
1733 default:
1734 return ParseStatus::NoMatch;
1735 case AsmToken::LParen:
1736 case AsmToken::Minus:
1737 case AsmToken::Plus:
1738 case AsmToken::Exclaim:
1739 case AsmToken::Tilde:
1740 case AsmToken::Integer:
1741 case AsmToken::String: {
1742 if (getParser().parseExpression(Res, E))
1743 return ParseStatus::Failure;
1744
1745 auto *CE = dyn_cast<MCConstantExpr>(Res);
1746 if (CE) {
1747 int64_t Imm = CE->getValue();
1748 if (isUInt<7>(Imm)) {
1749 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1750 return ParseStatus::Success;
1751 }
1752 }
1753
1754 break;
1755 }
1756 case AsmToken::Identifier: {
1758 if (getParser().parseIdentifier(Identifier))
1759 return ParseStatus::Failure;
1760
1761 auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Identifier);
1762 if (Opcode) {
1763 assert(isUInt<7>(Opcode->Value) && (Opcode->Value & 0x3) == 3 &&
1764 "Unexpected opcode");
1765 Res = MCConstantExpr::create(Opcode->Value, getContext());
1767 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1768 return ParseStatus::Success;
1769 }
1770
1771 break;
1772 }
1773 case AsmToken::Percent:
1774 break;
1775 }
1776
1777 return generateImmOutOfRangeError(
1778 S, 0, 127,
1779 "opcode must be a valid opcode name or an immediate in the range");
1780}
1781
1782ParseStatus RISCVAsmParser::parseInsnCDirectiveOpcode(OperandVector &Operands) {
1783 SMLoc S = getLoc();
1784 SMLoc E;
1785 const MCExpr *Res;
1786
1787 switch (getLexer().getKind()) {
1788 default:
1789 return ParseStatus::NoMatch;
1790 case AsmToken::LParen:
1791 case AsmToken::Minus:
1792 case AsmToken::Plus:
1793 case AsmToken::Exclaim:
1794 case AsmToken::Tilde:
1795 case AsmToken::Integer:
1796 case AsmToken::String: {
1797 if (getParser().parseExpression(Res, E))
1798 return ParseStatus::Failure;
1799
1800 auto *CE = dyn_cast<MCConstantExpr>(Res);
1801 if (CE) {
1802 int64_t Imm = CE->getValue();
1803 if (Imm >= 0 && Imm <= 2) {
1804 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1805 return ParseStatus::Success;
1806 }
1807 }
1808
1809 break;
1810 }
1811 case AsmToken::Identifier: {
1813 if (getParser().parseIdentifier(Identifier))
1814 return ParseStatus::Failure;
1815
1816 unsigned Opcode;
1817 if (Identifier == "C0")
1818 Opcode = 0;
1819 else if (Identifier == "C1")
1820 Opcode = 1;
1821 else if (Identifier == "C2")
1822 Opcode = 2;
1823 else
1824 break;
1825
1826 Res = MCConstantExpr::create(Opcode, getContext());
1828 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1829 return ParseStatus::Success;
1830 }
1831 case AsmToken::Percent: {
1832 // Discard operand with modifier.
1833 break;
1834 }
1835 }
1836
1837 return generateImmOutOfRangeError(
1838 S, 0, 2,
1839 "opcode must be a valid opcode name or an immediate in the range");
1840}
1841
1842ParseStatus RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1843 SMLoc S = getLoc();
1844 const MCExpr *Res;
1845
1846 switch (getLexer().getKind()) {
1847 default:
1848 return ParseStatus::NoMatch;
1849 case AsmToken::LParen:
1850 case AsmToken::Minus:
1851 case AsmToken::Plus:
1852 case AsmToken::Exclaim:
1853 case AsmToken::Tilde:
1854 case AsmToken::Integer:
1855 case AsmToken::String: {
1856 if (getParser().parseExpression(Res))
1857 return ParseStatus::Failure;
1858
1859 auto *CE = dyn_cast<MCConstantExpr>(Res);
1860 if (CE) {
1861 int64_t Imm = CE->getValue();
1862 if (isUInt<12>(Imm)) {
1863 auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
1864 // Accept an immediate representing a named or un-named Sys Reg
1865 // if the range is valid, regardless of the required features.
1866 Operands.push_back(
1867 RISCVOperand::createSysReg(SysReg ? SysReg->Name : "", S, Imm));
1868 return ParseStatus::Success;
1869 }
1870 }
1871
1872 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
1873 }
1874 case AsmToken::Identifier: {
1876 if (getParser().parseIdentifier(Identifier))
1877 return ParseStatus::Failure;
1878
1879 auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
1880 if (!SysReg)
1881 SysReg = RISCVSysReg::lookupSysRegByAltName(Identifier);
1882 if (!SysReg)
1883 if ((SysReg = RISCVSysReg::lookupSysRegByDeprecatedName(Identifier)))
1884 Warning(S, "'" + Identifier + "' is a deprecated alias for '" +
1885 SysReg->Name + "'");
1886
1887 // Accept a named Sys Reg if the required features are present.
1888 if (SysReg) {
1889 if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits()))
1890 return Error(S, "system register use requires an option to be enabled");
1891 Operands.push_back(
1892 RISCVOperand::createSysReg(Identifier, S, SysReg->Encoding));
1893 return ParseStatus::Success;
1894 }
1895
1896 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1,
1897 "operand must be a valid system register "
1898 "name or an integer in the range");
1899 }
1900 case AsmToken::Percent: {
1901 // Discard operand with modifier.
1902 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
1903 }
1904 }
1905
1906 return ParseStatus::NoMatch;
1907}
1908
1909ParseStatus RISCVAsmParser::parseFPImm(OperandVector &Operands) {
1910 SMLoc S = getLoc();
1911
1912 // Parse special floats (inf/nan/min) representation.
1913 if (getTok().is(AsmToken::Identifier)) {
1914 StringRef Identifier = getTok().getIdentifier();
1915 if (Identifier.compare_insensitive("inf") == 0) {
1916 Operands.push_back(
1917 RISCVOperand::createImm(MCConstantExpr::create(30, getContext()), S,
1918 getTok().getEndLoc(), isRV64()));
1919 } else if (Identifier.compare_insensitive("nan") == 0) {
1920 Operands.push_back(
1921 RISCVOperand::createImm(MCConstantExpr::create(31, getContext()), S,
1922 getTok().getEndLoc(), isRV64()));
1923 } else if (Identifier.compare_insensitive("min") == 0) {
1924 Operands.push_back(
1925 RISCVOperand::createImm(MCConstantExpr::create(1, getContext()), S,
1926 getTok().getEndLoc(), isRV64()));
1927 } else {
1928 return TokError("invalid floating point literal");
1929 }
1930
1931 Lex(); // Eat the token.
1932
1933 return ParseStatus::Success;
1934 }
1935
1936 // Handle negation, as that still comes through as a separate token.
1937 bool IsNegative = parseOptionalToken(AsmToken::Minus);
1938
1939 const AsmToken &Tok = getTok();
1940 if (!Tok.is(AsmToken::Real))
1941 return TokError("invalid floating point immediate");
1942
1943 // Parse FP representation.
1944 APFloat RealVal(APFloat::IEEEdouble());
1945 auto StatusOrErr =
1946 RealVal.convertFromString(Tok.getString(), APFloat::rmTowardZero);
1947 if (errorToBool(StatusOrErr.takeError()))
1948 return TokError("invalid floating point representation");
1949
1950 if (IsNegative)
1951 RealVal.changeSign();
1952
1953 Operands.push_back(RISCVOperand::createFPImm(
1954 RealVal.bitcastToAPInt().getZExtValue(), S));
1955
1956 Lex(); // Eat the token.
1957
1958 return ParseStatus::Success;
1959}
1960
1961ParseStatus RISCVAsmParser::parseImmediate(OperandVector &Operands) {
1962 SMLoc S = getLoc();
1963 SMLoc E;
1964 const MCExpr *Res;
1965
1966 switch (getLexer().getKind()) {
1967 default:
1968 return ParseStatus::NoMatch;
1969 case AsmToken::LParen:
1970 case AsmToken::Dot:
1971 case AsmToken::Minus:
1972 case AsmToken::Plus:
1973 case AsmToken::Exclaim:
1974 case AsmToken::Tilde:
1975 case AsmToken::Integer:
1976 case AsmToken::String:
1978 if (getParser().parseExpression(Res, E))
1979 return ParseStatus::Failure;
1980 break;
1981 case AsmToken::Percent:
1982 return parseOperandWithModifier(Operands);
1983 }
1984
1985 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1986 return ParseStatus::Success;
1987}
1988
1989ParseStatus RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1990 SMLoc S = getLoc();
1991 SMLoc E;
1992
1993 if (parseToken(AsmToken::Percent, "expected '%' for operand modifier"))
1994 return ParseStatus::Failure;
1995
1996 if (getLexer().getKind() != AsmToken::Identifier)
1997 return Error(getLoc(), "expected valid identifier for operand modifier");
1998 StringRef Identifier = getParser().getTok().getIdentifier();
2001 return Error(getLoc(), "unrecognized operand modifier");
2002
2003 getParser().Lex(); // Eat the identifier
2004 if (parseToken(AsmToken::LParen, "expected '('"))
2005 return ParseStatus::Failure;
2006
2007 const MCExpr *SubExpr;
2008 if (getParser().parseParenExpression(SubExpr, E))
2009 return ParseStatus::Failure;
2010
2011 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
2012 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
2013 return ParseStatus::Success;
2014}
2015
2016ParseStatus RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
2017 SMLoc S = getLoc();
2018 const MCExpr *Res;
2019
2020 if (getLexer().getKind() != AsmToken::Identifier)
2021 return ParseStatus::NoMatch;
2022
2024 AsmToken Tok = getLexer().getTok();
2025
2026 if (getParser().parseIdentifier(Identifier))
2027 return ParseStatus::Failure;
2028
2030
2031 if (Identifier.consume_back("@plt"))
2032 return Error(getLoc(), "'@plt' operand not valid for instruction");
2033
2034 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2035
2036 if (Sym->isVariable()) {
2037 const MCExpr *V = Sym->getVariableValue(/*SetUsed=*/false);
2038 if (!isa<MCSymbolRefExpr>(V)) {
2039 getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
2040 return ParseStatus::NoMatch;
2041 }
2042 Res = V;
2043 } else
2045
2046 MCBinaryExpr::Opcode Opcode;
2047 switch (getLexer().getKind()) {
2048 default:
2049 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2050 return ParseStatus::Success;
2051 case AsmToken::Plus:
2052 Opcode = MCBinaryExpr::Add;
2053 getLexer().Lex();
2054 break;
2055 case AsmToken::Minus:
2056 Opcode = MCBinaryExpr::Sub;
2057 getLexer().Lex();
2058 break;
2059 }
2060
2061 const MCExpr *Expr;
2062 if (getParser().parseExpression(Expr, E))
2063 return ParseStatus::Failure;
2064 Res = MCBinaryExpr::create(Opcode, Res, Expr, getContext());
2065 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2066 return ParseStatus::Success;
2067}
2068
2069ParseStatus RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
2070 SMLoc S = getLoc();
2071 const MCExpr *Res;
2072
2073 if (getLexer().getKind() != AsmToken::Identifier)
2074 return ParseStatus::NoMatch;
2075
2076 // Avoid parsing the register in `call rd, foo` as a call symbol.
2077 if (getLexer().peekTok().getKind() != AsmToken::EndOfStatement)
2078 return ParseStatus::NoMatch;
2079
2081 if (getParser().parseIdentifier(Identifier))
2082 return ParseStatus::Failure;
2083
2085
2087 (void)Identifier.consume_back("@plt");
2088
2089 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2091 Res = RISCVMCExpr::create(Res, Kind, getContext());
2092 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2093 return ParseStatus::Success;
2094}
2095
2096ParseStatus RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
2097 SMLoc S = getLoc();
2098 SMLoc E;
2099 const MCExpr *Res;
2100
2101 if (getParser().parseExpression(Res, E))
2102 return ParseStatus::Failure;
2103
2104 if (Res->getKind() != MCExpr::ExprKind::SymbolRef ||
2105 cast<MCSymbolRefExpr>(Res)->getKind() ==
2106 MCSymbolRefExpr::VariantKind::VK_PLT)
2107 return Error(S, "operand must be a valid jump target");
2108
2109 Res = RISCVMCExpr::create(Res, RISCVMCExpr::VK_RISCV_CALL, getContext());
2110 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2111 return ParseStatus::Success;
2112}
2113
2114ParseStatus RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
2115 // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
2116 // both being acceptable forms. When parsing `jal ra, foo` this function
2117 // will be called for the `ra` register operand in an attempt to match the
2118 // single-operand alias. parseJALOffset must fail for this case. It would
2119 // seem logical to try parse the operand using parseImmediate and return
2120 // NoMatch if the next token is a comma (meaning we must be parsing a jal in
2121 // the second form rather than the first). We can't do this as there's no
2122 // way of rewinding the lexer state. Instead, return NoMatch if this operand
2123 // is an identifier and is followed by a comma.
2124 if (getLexer().is(AsmToken::Identifier) &&
2125 getLexer().peekTok().is(AsmToken::Comma))
2126 return ParseStatus::NoMatch;
2127
2128 return parseImmediate(Operands);
2129}
2130
2131bool RISCVAsmParser::parseVTypeToken(const AsmToken &Tok, VTypeState &State,
2132 unsigned &Sew, unsigned &Lmul,
2133 bool &Fractional, bool &TailAgnostic,
2134 bool &MaskAgnostic) {
2135 if (Tok.isNot(AsmToken::Identifier))
2136 return true;
2137
2139
2140 switch (State) {
2141 case VTypeState_SEW:
2142 if (!Identifier.consume_front("e"))
2143 break;
2144 if (Identifier.getAsInteger(10, Sew))
2145 break;
2146 if (!RISCVVType::isValidSEW(Sew))
2147 break;
2148 State = VTypeState_LMUL;
2149 return false;
2150 case VTypeState_LMUL: {
2151 if (!Identifier.consume_front("m"))
2152 break;
2153 Fractional = Identifier.consume_front("f");
2154 if (Identifier.getAsInteger(10, Lmul))
2155 break;
2156 if (!RISCVVType::isValidLMUL(Lmul, Fractional))
2157 break;
2158
2159 if (Fractional) {
2160 unsigned ELEN = STI->hasFeature(RISCV::FeatureStdExtZve64x) ? 64 : 32;
2161 unsigned MinLMUL = ELEN / 8;
2162 if (Lmul > MinLMUL)
2163 Warning(Tok.getLoc(),
2164 "use of vtype encodings with LMUL < SEWMIN/ELEN == mf" +
2165 Twine(MinLMUL) + " is reserved");
2166 }
2167
2168 State = VTypeState_TailPolicy;
2169 return false;
2170 }
2171 case VTypeState_TailPolicy:
2172 if (Identifier == "ta")
2173 TailAgnostic = true;
2174 else if (Identifier == "tu")
2175 TailAgnostic = false;
2176 else
2177 break;
2178 State = VTypeState_MaskPolicy;
2179 return false;
2180 case VTypeState_MaskPolicy:
2181 if (Identifier == "ma")
2182 MaskAgnostic = true;
2183 else if (Identifier == "mu")
2184 MaskAgnostic = false;
2185 else
2186 break;
2187 State = VTypeState_Done;
2188 return false;
2189 case VTypeState_Done:
2190 // Extra token?
2191 break;
2192 }
2193
2194 return true;
2195}
2196
2197ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2198 SMLoc S = getLoc();
2199
2200 unsigned Sew = 0;
2201 unsigned Lmul = 0;
2202 bool Fractional = false;
2203 bool TailAgnostic = false;
2204 bool MaskAgnostic = false;
2205
2206 VTypeState State = VTypeState_SEW;
2207 SMLoc SEWLoc = S;
2208
2209 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2210 MaskAgnostic))
2211 return ParseStatus::NoMatch;
2212
2213 getLexer().Lex();
2214
2215 while (parseOptionalToken(AsmToken::Comma)) {
2216 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2217 MaskAgnostic))
2218 break;
2219
2220 getLexer().Lex();
2221 }
2222
2223 if (getLexer().is(AsmToken::EndOfStatement) && State == VTypeState_Done) {
2224 RISCVII::VLMUL VLMUL = RISCVVType::encodeLMUL(Lmul, Fractional);
2225 if (Fractional) {
2226 unsigned ELEN = STI->hasFeature(RISCV::FeatureStdExtZve64x) ? 64 : 32;
2227 unsigned MaxSEW = ELEN / Lmul;
2228 // If MaxSEW < 8, we should have printed warning about reserved LMUL.
2229 if (MaxSEW >= 8 && Sew > MaxSEW)
2230 Warning(SEWLoc,
2231 "use of vtype encodings with SEW > " + Twine(MaxSEW) +
2232 " and LMUL == mf" + Twine(Lmul) +
2233 " may not be compatible with all RVV implementations");
2234 }
2235
2236 unsigned VTypeI =
2237 RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
2238 Operands.push_back(RISCVOperand::createVType(VTypeI, S));
2239 return ParseStatus::Success;
2240 }
2241
2242 return generateVTypeError(S);
2243}
2244
2245bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2246 return Error(
2247 ErrorLoc,
2248 "operand must be "
2249 "e[8|16|32|64],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2250}
2251
2252ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2253 if (getLexer().isNot(AsmToken::Identifier))
2254 return ParseStatus::NoMatch;
2255
2256 StringRef Name = getLexer().getTok().getIdentifier();
2257 if (!Name.consume_back(".t"))
2258 return Error(getLoc(), "expected '.t' suffix");
2260
2261 if (!RegNo)
2262 return ParseStatus::NoMatch;
2263 if (RegNo != RISCV::V0)
2264 return ParseStatus::NoMatch;
2265 SMLoc S = getLoc();
2267 getLexer().Lex();
2268 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
2269 return ParseStatus::Success;
2270}
2271
2272ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
2273 if (getLexer().isNot(AsmToken::Identifier))
2274 return ParseStatus::NoMatch;
2275
2276 StringRef Name = getLexer().getTok().getIdentifier();
2278
2279 if (!RegNo)
2280 return ParseStatus::NoMatch;
2281 SMLoc S = getLoc();
2283 getLexer().Lex();
2284 Operands.push_back(RISCVOperand::createReg(
2285 RegNo, S, E, !getSTI().hasFeature(RISCV::FeatureStdExtF)));
2286 return ParseStatus::Success;
2287}
2288
2289template <bool IsRV64>
2290ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
2291 return parseGPRPair(Operands, IsRV64);
2292}
2293
2294ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
2295 bool IsRV64Inst) {
2296 // If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
2297 // RV64 as it will prevent matching the RV64 version of the same instruction
2298 // that doesn't use a GPRPair.
2299 // If this is an RV64 GPRPair instruction, there is no RV32 version so we can
2300 // still parse as a pair.
2301 if (!IsRV64Inst && isRV64())
2302 return ParseStatus::NoMatch;
2303
2304 if (getLexer().isNot(AsmToken::Identifier))
2305 return ParseStatus::NoMatch;
2306
2307 StringRef Name = getLexer().getTok().getIdentifier();
2309
2310 if (!RegNo)
2311 return ParseStatus::NoMatch;
2312
2313 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(RegNo))
2314 return ParseStatus::NoMatch;
2315
2316 if ((RegNo - RISCV::X0) & 1)
2317 return TokError("register must be even");
2318
2319 SMLoc S = getLoc();
2321 getLexer().Lex();
2322
2323 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2324 unsigned Pair = RI->getMatchingSuperReg(
2325 RegNo, RISCV::sub_gpr_even,
2326 &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2327 Operands.push_back(RISCVOperand::createReg(Pair, S, E));
2328 return ParseStatus::Success;
2329}
2330
2331ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2332 if (getLexer().isNot(AsmToken::Identifier))
2333 return TokError(
2334 "operand must be a valid floating point rounding mode mnemonic");
2335
2336 StringRef Str = getLexer().getTok().getIdentifier();
2338
2339 if (FRM == RISCVFPRndMode::Invalid)
2340 return TokError(
2341 "operand must be a valid floating point rounding mode mnemonic");
2342
2343 Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
2344 Lex(); // Eat identifier token.
2345 return ParseStatus::Success;
2346}
2347
2348ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2349 const AsmToken &Tok = getLexer().getTok();
2350
2351 if (Tok.is(AsmToken::Integer)) {
2352 if (Tok.getIntVal() != 0)
2353 goto ParseFail;
2354
2355 Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
2356 Lex();
2357 return ParseStatus::Success;
2358 }
2359
2360 if (Tok.is(AsmToken::Identifier)) {
2361 StringRef Str = Tok.getIdentifier();
2362
2363 // Letters must be unique, taken from 'iorw', and in ascending order. This
2364 // holds as long as each individual character is one of 'iorw' and is
2365 // greater than the previous character.
2366 unsigned Imm = 0;
2367 bool Valid = true;
2368 char Prev = '\0';
2369 for (char c : Str) {
2370 switch (c) {
2371 default:
2372 Valid = false;
2373 break;
2374 case 'i':
2376 break;
2377 case 'o':
2379 break;
2380 case 'r':
2382 break;
2383 case 'w':
2385 break;
2386 }
2387
2388 if (c <= Prev) {
2389 Valid = false;
2390 break;
2391 }
2392 Prev = c;
2393 }
2394
2395 if (!Valid)
2396 goto ParseFail;
2397
2398 Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
2399 Lex();
2400 return ParseStatus::Success;
2401 }
2402
2403ParseFail:
2404 return TokError("operand must be formed of letters selected in-order from "
2405 "'iorw' or be 0");
2406}
2407
2408ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2409 if (parseToken(AsmToken::LParen, "expected '('"))
2410 return ParseStatus::Failure;
2411 Operands.push_back(RISCVOperand::createToken("(", getLoc()));
2412
2413 if (!parseRegister(Operands).isSuccess())
2414 return Error(getLoc(), "expected register");
2415
2416 if (parseToken(AsmToken::RParen, "expected ')'"))
2417 return ParseStatus::Failure;
2418 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
2419
2420 return ParseStatus::Success;
2421}
2422
2423ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2424 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2425 // as one of their register operands, such as `(a0)`. This just denotes that
2426 // the register (in this case `a0`) contains a memory address.
2427 //
2428 // Normally, we would be able to parse these by putting the parens into the
2429 // instruction string. However, GNU as also accepts a zero-offset memory
2430 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2431 // with parseImmediate followed by parseMemOpBaseReg, but these instructions
2432 // do not accept an immediate operand, and we do not want to add a "dummy"
2433 // operand that is silently dropped.
2434 //
2435 // Instead, we use this custom parser. This will: allow (and discard) an
2436 // offset if it is zero; require (and discard) parentheses; and add only the
2437 // parsed register operand to `Operands`.
2438 //
2439 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2440 // which will only print the register surrounded by parentheses (which GNU as
2441 // also uses as its canonical representation for these operands).
2442 std::unique_ptr<RISCVOperand> OptionalImmOp;
2443
2444 if (getLexer().isNot(AsmToken::LParen)) {
2445 // Parse an Integer token. We do not accept arbritrary constant expressions
2446 // in the offset field (because they may include parens, which complicates
2447 // parsing a lot).
2448 int64_t ImmVal;
2449 SMLoc ImmStart = getLoc();
2450 if (getParser().parseIntToken(ImmVal,
2451 "expected '(' or optional integer offset"))
2452 return ParseStatus::Failure;
2453
2454 // Create a RISCVOperand for checking later (so the error messages are
2455 // nicer), but we don't add it to Operands.
2456 SMLoc ImmEnd = getLoc();
2457 OptionalImmOp =
2458 RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
2459 ImmStart, ImmEnd, isRV64());
2460 }
2461
2462 if (parseToken(AsmToken::LParen,
2463 OptionalImmOp ? "expected '(' after optional integer offset"
2464 : "expected '(' or optional integer offset"))
2465 return ParseStatus::Failure;
2466
2467 if (!parseRegister(Operands).isSuccess())
2468 return Error(getLoc(), "expected register");
2469
2470 if (parseToken(AsmToken::RParen, "expected ')'"))
2471 return ParseStatus::Failure;
2472
2473 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2474 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2475 return Error(
2476 OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
2477 SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2478
2479 return ParseStatus::Success;
2480}
2481
2482ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2483 // RR : a2(a1)
2484 if (getLexer().getKind() != AsmToken::Identifier)
2485 return ParseStatus::NoMatch;
2486
2487 StringRef RegName = getLexer().getTok().getIdentifier();
2489 if (!Reg)
2490 return Error(getLoc(), "invalid register");
2491 getLexer().Lex();
2492
2493 if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
2494 return ParseStatus::Failure;
2495
2496 if (getLexer().getKind() != AsmToken::Identifier)
2497 return Error(getLoc(), "expected register");
2498
2499 StringRef Reg2Name = getLexer().getTok().getIdentifier();
2500 MCRegister Reg2 = matchRegisterNameHelper(Reg2Name);
2501 if (!Reg2)
2502 return Error(getLoc(), "invalid register");
2503 getLexer().Lex();
2504
2505 if (parseToken(AsmToken::RParen, "expected ')'"))
2506 return ParseStatus::Failure;
2507
2508 Operands.push_back(RISCVOperand::createRegReg(Reg, Reg2, getLoc()));
2509
2510 return ParseStatus::Success;
2511}
2512
2513ParseStatus RISCVAsmParser::parseReglist(OperandVector &Operands) {
2514 // Rlist: {ra [, s0[-sN]]}
2515 // XRlist: {x1 [, x8[-x9][, x18[-xN]]]}
2516 SMLoc S = getLoc();
2517
2518 if (parseToken(AsmToken::LCurly, "register list must start with '{'"))
2519 return ParseStatus::Failure;
2520
2521 bool IsEABI = isRVE();
2522
2523 if (getLexer().isNot(AsmToken::Identifier))
2524 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2525
2526 StringRef RegName = getLexer().getTok().getIdentifier();
2528 MCRegister RegEnd;
2529 if (RegStart != RISCV::X1)
2530 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2531 getLexer().Lex();
2532
2533 // parse case like ,s0
2534 if (parseOptionalToken(AsmToken::Comma)) {
2535 if (getLexer().isNot(AsmToken::Identifier))
2536 return Error(getLoc(), "invalid register");
2537 StringRef RegName = getLexer().getTok().getIdentifier();
2538 RegStart = matchRegisterNameHelper(RegName);
2539 if (!RegStart)
2540 return Error(getLoc(), "invalid register");
2541 if (RegStart != RISCV::X8)
2542 return Error(getLoc(),
2543 "continuous register list must start from 's0' or 'x8'");
2544 getLexer().Lex(); // eat reg
2545 }
2546
2547 // parse case like -s1
2548 if (parseOptionalToken(AsmToken::Minus)) {
2549 StringRef EndName = getLexer().getTok().getIdentifier();
2550 // FIXME: the register mapping and checks of EABI is wrong
2551 RegEnd = matchRegisterNameHelper(EndName);
2552 if (!RegEnd)
2553 return Error(getLoc(), "invalid register");
2554 if (IsEABI && RegEnd != RISCV::X9)
2555 return Error(getLoc(), "contiguous register list of EABI can only be "
2556 "'s0-s1' or 'x8-x9' pair");
2557 getLexer().Lex();
2558 }
2559
2560 if (!IsEABI) {
2561 // parse extra part like ', x18[-x20]' for XRegList
2562 if (parseOptionalToken(AsmToken::Comma)) {
2563 if (RegEnd != RISCV::X9)
2564 return Error(
2565 getLoc(),
2566 "first contiguous registers pair of register list must be 'x8-x9'");
2567
2568 // parse ', x18' for extra part
2569 if (getLexer().isNot(AsmToken::Identifier))
2570 return Error(getLoc(), "invalid register");
2571 StringRef EndName = getLexer().getTok().getIdentifier();
2572 if (MatchRegisterName(EndName) != RISCV::X18)
2573 return Error(getLoc(),
2574 "second contiguous registers pair of register list "
2575 "must start from 'x18'");
2576 getLexer().Lex();
2577
2578 // parse '-x20' for extra part
2579 if (parseOptionalToken(AsmToken::Minus)) {
2580 if (getLexer().isNot(AsmToken::Identifier))
2581 return Error(getLoc(), "invalid register");
2582 EndName = getLexer().getTok().getIdentifier();
2583 if (MatchRegisterName(EndName) == RISCV::NoRegister)
2584 return Error(getLoc(), "invalid register");
2585 getLexer().Lex();
2586 }
2587 RegEnd = MatchRegisterName(EndName);
2588 }
2589 }
2590
2591 if (RegEnd == RISCV::X26)
2592 return Error(getLoc(), "invalid register list, {ra, s0-s10} or {x1, x8-x9, "
2593 "x18-x26} is not supported");
2594
2595 if (parseToken(AsmToken::RCurly, "register list must end with '}'"))
2596 return ParseStatus::Failure;
2597
2598 if (RegEnd == RISCV::NoRegister)
2599 RegEnd = RegStart;
2600
2601 auto Encode = RISCVZC::encodeRlist(RegEnd, IsEABI);
2602 if (Encode == RISCVZC::INVALID_RLIST)
2603 return Error(S, "invalid register list");
2604 Operands.push_back(RISCVOperand::createRlist(Encode, S));
2605
2606 return ParseStatus::Success;
2607}
2608
2609ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
2610 bool ExpectNegative) {
2611 bool Negative = parseOptionalToken(AsmToken::Minus);
2612
2613 SMLoc S = getLoc();
2614 int64_t StackAdjustment = getLexer().getTok().getIntVal();
2615 unsigned Spimm = 0;
2616 unsigned RlistVal = static_cast<RISCVOperand *>(Operands[1].get())->Rlist.Val;
2617
2618 if (Negative != ExpectNegative ||
2619 !RISCVZC::getSpimm(RlistVal, Spimm, StackAdjustment, isRV64()))
2620 return ParseStatus::NoMatch;
2621 Operands.push_back(RISCVOperand::createSpimm(Spimm << 4, S));
2622 getLexer().Lex();
2623 return ParseStatus::Success;
2624}
2625
2626/// Looks at a token type and creates the relevant operand from this
2627/// information, adding to Operands. If operand was parsed, returns false, else
2628/// true.
2629bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2630 // Check if the current operand has a custom associated parser, if so, try to
2631 // custom parse the operand, or fallback to the general approach.
2633 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
2634 if (Result.isSuccess())
2635 return false;
2636 if (Result.isFailure())
2637 return true;
2638
2639 // Attempt to parse token as a register.
2640 if (parseRegister(Operands, true).isSuccess())
2641 return false;
2642
2643 // Attempt to parse token as an immediate
2644 if (parseImmediate(Operands).isSuccess()) {
2645 // Parse memory base register if present
2646 if (getLexer().is(AsmToken::LParen))
2647 return !parseMemOpBaseReg(Operands).isSuccess();
2648 return false;
2649 }
2650
2651 // Finally we have exhausted all options and must declare defeat.
2652 Error(getLoc(), "unknown operand");
2653 return true;
2654}
2655
2656bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
2657 StringRef Name, SMLoc NameLoc,
2659 // Ensure that if the instruction occurs when relaxation is enabled,
2660 // relocations are forced for the file. Ideally this would be done when there
2661 // is enough information to reliably determine if the instruction itself may
2662 // cause relaxations. Unfortunately instruction processing stage occurs in the
2663 // same pass as relocation emission, so it's too late to set a 'sticky bit'
2664 // for the entire file.
2665 if (getSTI().hasFeature(RISCV::FeatureRelax)) {
2666 auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
2667 if (Assembler != nullptr) {
2668 RISCVAsmBackend &MAB =
2669 static_cast<RISCVAsmBackend &>(Assembler->getBackend());
2670 MAB.setForceRelocs();
2671 }
2672 }
2673
2674 // First operand is token for instruction
2675 Operands.push_back(RISCVOperand::createToken(Name, NameLoc));
2676
2677 // If there are no more operands, then finish
2678 if (getLexer().is(AsmToken::EndOfStatement)) {
2679 getParser().Lex(); // Consume the EndOfStatement.
2680 return false;
2681 }
2682
2683 // Parse first operand
2684 if (parseOperand(Operands, Name))
2685 return true;
2686
2687 // Parse until end of statement, consuming commas between operands
2688 while (parseOptionalToken(AsmToken::Comma)) {
2689 // Parse next operand
2690 if (parseOperand(Operands, Name))
2691 return true;
2692 }
2693
2694 if (getParser().parseEOL("unexpected token")) {
2695 getParser().eatToEndOfStatement();
2696 return true;
2697 }
2698 return false;
2699}
2700
2701bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2704
2705 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
2706 Kind = RE->getKind();
2707 Expr = RE->getSubExpr();
2708 }
2709
2710 MCValue Res;
2711 MCFixup Fixup;
2712 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup))
2713 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None;
2714 return false;
2715}
2716
2717bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
2718 MCValue Res;
2719 MCFixup Fixup;
2720 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup)) {
2721 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None && Res.getSymA() &&
2722 Res.getSymB();
2723 }
2724 return false;
2725}
2726
2727ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
2728 StringRef IDVal = DirectiveID.getString();
2729
2730 if (IDVal == ".option")
2731 return parseDirectiveOption();
2732 if (IDVal == ".attribute")
2733 return parseDirectiveAttribute();
2734 if (IDVal == ".insn")
2735 return parseDirectiveInsn(DirectiveID.getLoc());
2736 if (IDVal == ".variant_cc")
2737 return parseDirectiveVariantCC();
2738
2739 return ParseStatus::NoMatch;
2740}
2741
2742bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
2743 bool FromOptionDirective) {
2744 for (auto &Feature : RISCVFeatureKV)
2746 clearFeatureBits(Feature.Value, Feature.Key);
2747
2748 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
2749 Arch, /*EnableExperimentalExtension=*/true,
2750 /*ExperimentalExtensionVersionCheck=*/true);
2751 if (!ParseResult) {
2752 std::string Buffer;
2753 raw_string_ostream OutputErrMsg(Buffer);
2754 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2755 OutputErrMsg << "invalid arch name '" << Arch << "', "
2756 << ErrMsg.getMessage();
2757 });
2758
2759 return Error(Loc, OutputErrMsg.str());
2760 }
2761 auto &ISAInfo = *ParseResult;
2762
2763 for (auto &Feature : RISCVFeatureKV)
2764 if (ISAInfo->hasExtension(Feature.Key))
2765 setFeatureBits(Feature.Value, Feature.Key);
2766
2767 if (FromOptionDirective) {
2768 if (ISAInfo->getXLen() == 32 && isRV64())
2769 return Error(Loc, "bad arch string switching from rv64 to rv32");
2770 else if (ISAInfo->getXLen() == 64 && !isRV64())
2771 return Error(Loc, "bad arch string switching from rv32 to rv64");
2772 }
2773
2774 if (ISAInfo->getXLen() == 32)
2775 clearFeatureBits(RISCV::Feature64Bit, "64bit");
2776 else if (ISAInfo->getXLen() == 64)
2777 setFeatureBits(RISCV::Feature64Bit, "64bit");
2778 else
2779 return Error(Loc, "bad arch string " + Arch);
2780
2781 Result = ISAInfo->toString();
2782 return false;
2783}
2784
2785bool RISCVAsmParser::parseDirectiveOption() {
2786 MCAsmParser &Parser = getParser();
2787 // Get the option token.
2788 AsmToken Tok = Parser.getTok();
2789
2790 // At the moment only identifiers are supported.
2791 if (parseToken(AsmToken::Identifier, "expected identifier"))
2792 return true;
2793
2795
2796 if (Option == "push") {
2797 if (Parser.parseEOL())
2798 return true;
2799
2800 getTargetStreamer().emitDirectiveOptionPush();
2801 pushFeatureBits();
2802 return false;
2803 }
2804
2805 if (Option == "pop") {
2806 SMLoc StartLoc = Parser.getTok().getLoc();
2807 if (Parser.parseEOL())
2808 return true;
2809
2810 getTargetStreamer().emitDirectiveOptionPop();
2811 if (popFeatureBits())
2812 return Error(StartLoc, ".option pop with no .option push");
2813
2814 return false;
2815 }
2816
2817 if (Option == "arch") {
2819 do {
2820 if (Parser.parseComma())
2821 return true;
2822
2824 if (parseOptionalToken(AsmToken::Plus))
2825 Type = RISCVOptionArchArgType::Plus;
2826 else if (parseOptionalToken(AsmToken::Minus))
2827 Type = RISCVOptionArchArgType::Minus;
2828 else if (!Args.empty())
2829 return Error(Parser.getTok().getLoc(),
2830 "unexpected token, expected + or -");
2831 else
2832 Type = RISCVOptionArchArgType::Full;
2833
2834 if (Parser.getTok().isNot(AsmToken::Identifier))
2835 return Error(Parser.getTok().getLoc(),
2836 "unexpected token, expected identifier");
2837
2838 StringRef Arch = Parser.getTok().getString();
2839 SMLoc Loc = Parser.getTok().getLoc();
2840 Parser.Lex();
2841
2842 if (Type == RISCVOptionArchArgType::Full) {
2843 std::string Result;
2844 if (resetToArch(Arch, Loc, Result, true))
2845 return true;
2846
2847 Args.emplace_back(Type, Result);
2848 break;
2849 }
2850
2851 if (isDigit(Arch.back()))
2852 return Error(
2853 Loc, "extension version number parsing not currently implemented");
2854
2855 std::string Feature = RISCVISAInfo::getTargetFeatureForExtension(Arch);
2856 if (!enableExperimentalExtension() &&
2857 StringRef(Feature).starts_with("experimental-"))
2858 return Error(Loc, "unexpected experimental extensions");
2859 auto Ext = llvm::lower_bound(RISCVFeatureKV, Feature);
2860 if (Ext == std::end(RISCVFeatureKV) || StringRef(Ext->Key) != Feature)
2861 return Error(Loc, "unknown extension feature");
2862
2863 Args.emplace_back(Type, Arch.str());
2864
2865 if (Type == RISCVOptionArchArgType::Plus) {
2866 FeatureBitset OldFeatureBits = STI->getFeatureBits();
2867
2868 setFeatureBits(Ext->Value, Ext->Key);
2869 auto ParseResult = RISCVFeatures::parseFeatureBits(isRV64(), STI->getFeatureBits());
2870 if (!ParseResult) {
2871 copySTI().setFeatureBits(OldFeatureBits);
2872 setAvailableFeatures(ComputeAvailableFeatures(OldFeatureBits));
2873
2874 std::string Buffer;
2875 raw_string_ostream OutputErrMsg(Buffer);
2876 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2877 OutputErrMsg << ErrMsg.getMessage();
2878 });
2879
2880 return Error(Loc, OutputErrMsg.str());
2881 }
2882 } else {
2883 assert(Type == RISCVOptionArchArgType::Minus);
2884 // It is invalid to disable an extension that there are other enabled
2885 // extensions depend on it.
2886 // TODO: Make use of RISCVISAInfo to handle this
2887 for (auto &Feature : RISCVFeatureKV) {
2888 if (getSTI().hasFeature(Feature.Value) &&
2889 Feature.Implies.test(Ext->Value))
2890 return Error(Loc, Twine("can't disable ") + Ext->Key +
2891 " extension; " + Feature.Key +
2892 " extension requires " + Ext->Key +
2893 " extension");
2894 }
2895
2896 clearFeatureBits(Ext->Value, Ext->Key);
2897 }
2898 } while (Parser.getTok().isNot(AsmToken::EndOfStatement));
2899
2900 if (Parser.parseEOL())
2901 return true;
2902
2903 getTargetStreamer().emitDirectiveOptionArch(Args);
2904 return false;
2905 }
2906
2907 if (Option == "rvc") {
2908 if (Parser.parseEOL())
2909 return true;
2910
2911 getTargetStreamer().emitDirectiveOptionRVC();
2912 setFeatureBits(RISCV::FeatureStdExtC, "c");
2913 return false;
2914 }
2915
2916 if (Option == "norvc") {
2917 if (Parser.parseEOL())
2918 return true;
2919
2920 getTargetStreamer().emitDirectiveOptionNoRVC();
2921 clearFeatureBits(RISCV::FeatureStdExtC, "c");
2922 clearFeatureBits(RISCV::FeatureStdExtZca, "zca");
2923 return false;
2924 }
2925
2926 if (Option == "pic") {
2927 if (Parser.parseEOL())
2928 return true;
2929
2930 getTargetStreamer().emitDirectiveOptionPIC();
2931 ParserOptions.IsPicEnabled = true;
2932 return false;
2933 }
2934
2935 if (Option == "nopic") {
2936 if (Parser.parseEOL())
2937 return true;
2938
2939 getTargetStreamer().emitDirectiveOptionNoPIC();
2940 ParserOptions.IsPicEnabled = false;
2941 return false;
2942 }
2943
2944 if (Option == "relax") {
2945 if (Parser.parseEOL())
2946 return true;
2947
2948 getTargetStreamer().emitDirectiveOptionRelax();
2949 setFeatureBits(RISCV::FeatureRelax, "relax");
2950 return false;
2951 }
2952
2953 if (Option == "norelax") {
2954 if (Parser.parseEOL())
2955 return true;
2956
2957 getTargetStreamer().emitDirectiveOptionNoRelax();
2958 clearFeatureBits(RISCV::FeatureRelax, "relax");
2959 return false;
2960 }
2961
2962 // Unknown option.
2963 Warning(Parser.getTok().getLoc(), "unknown option, expected 'push', 'pop', "
2964 "'rvc', 'norvc', 'arch', 'relax' or "
2965 "'norelax'");
2966 Parser.eatToEndOfStatement();
2967 return false;
2968}
2969
2970/// parseDirectiveAttribute
2971/// ::= .attribute expression ',' ( expression | "string" )
2972/// ::= .attribute identifier ',' ( expression | "string" )
2973bool RISCVAsmParser::parseDirectiveAttribute() {
2974 MCAsmParser &Parser = getParser();
2975 int64_t Tag;
2976 SMLoc TagLoc;
2977 TagLoc = Parser.getTok().getLoc();
2978 if (Parser.getTok().is(AsmToken::Identifier)) {
2979 StringRef Name = Parser.getTok().getIdentifier();
2980 std::optional<unsigned> Ret =
2982 if (!Ret)
2983 return Error(TagLoc, "attribute name not recognised: " + Name);
2984 Tag = *Ret;
2985 Parser.Lex();
2986 } else {
2987 const MCExpr *AttrExpr;
2988
2989 TagLoc = Parser.getTok().getLoc();
2990 if (Parser.parseExpression(AttrExpr))
2991 return true;
2992
2993 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
2994 if (check(!CE, TagLoc, "expected numeric constant"))
2995 return true;
2996
2997 Tag = CE->getValue();
2998 }
2999
3000 if (Parser.parseComma())
3001 return true;
3002
3003 StringRef StringValue;
3004 int64_t IntegerValue = 0;
3005 bool IsIntegerValue = true;
3006
3007 // RISC-V attributes have a string value if the tag number is odd
3008 // and an integer value if the tag number is even.
3009 if (Tag % 2)
3010 IsIntegerValue = false;
3011
3012 SMLoc ValueExprLoc = Parser.getTok().getLoc();
3013 if (IsIntegerValue) {
3014 const MCExpr *ValueExpr;
3015 if (Parser.parseExpression(ValueExpr))
3016 return true;
3017
3018 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
3019 if (!CE)
3020 return Error(ValueExprLoc, "expected numeric constant");
3021 IntegerValue = CE->getValue();
3022 } else {
3023 if (Parser.getTok().isNot(AsmToken::String))
3024 return Error(Parser.getTok().getLoc(), "expected string constant");
3025
3026 StringValue = Parser.getTok().getStringContents();
3027 Parser.Lex();
3028 }
3029
3030 if (Parser.parseEOL())
3031 return true;
3032
3033 if (IsIntegerValue)
3034 getTargetStreamer().emitAttribute(Tag, IntegerValue);
3035 else if (Tag != RISCVAttrs::ARCH)
3036 getTargetStreamer().emitTextAttribute(Tag, StringValue);
3037 else {
3038 std::string Result;
3039 if (resetToArch(StringValue, ValueExprLoc, Result, false))
3040 return true;
3041
3042 // Then emit the arch string.
3043 getTargetStreamer().emitTextAttribute(Tag, Result);
3044 }
3045
3046 return false;
3047}
3048
3049bool isValidInsnFormat(StringRef Format, bool AllowC) {
3050 return StringSwitch<bool>(Format)
3051 .Cases("r", "r4", "i", "b", "sb", "u", "j", "uj", "s", true)
3052 .Cases("cr", "ci", "ciw", "css", "cl", "cs", "ca", "cb", "cj", AllowC)
3053 .Default(false);
3054}
3055
3056/// parseDirectiveInsn
3057/// ::= .insn [ format encoding, (operands (, operands)*) ]
3058bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
3059 MCAsmParser &Parser = getParser();
3060
3061 // Expect instruction format as identifier.
3063 SMLoc ErrorLoc = Parser.getTok().getLoc();
3064 if (Parser.parseIdentifier(Format))
3065 return Error(ErrorLoc, "expected instruction format");
3066
3067 bool AllowC = getSTI().hasFeature(RISCV::FeatureStdExtC) ||
3068 getSTI().hasFeature(RISCV::FeatureStdExtZca);
3069 if (!isValidInsnFormat(Format, AllowC))
3070 return Error(ErrorLoc, "invalid instruction format");
3071
3072 std::string FormatName = (".insn_" + Format).str();
3073
3076
3077 if (ParseInstruction(Info, FormatName, L, Operands))
3078 return true;
3079
3080 unsigned Opcode;
3082 return MatchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
3083 ErrorInfo,
3084 /*MatchingInlineAsm=*/false);
3085}
3086
3087/// parseDirectiveVariantCC
3088/// ::= .variant_cc symbol
3089bool RISCVAsmParser::parseDirectiveVariantCC() {
3091 if (getParser().parseIdentifier(Name))
3092 return TokError("expected symbol name");
3093 if (parseEOL())
3094 return true;
3095 getTargetStreamer().emitDirectiveVariantCC(
3096 *getContext().getOrCreateSymbol(Name));
3097 return false;
3098}
3099
3100void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
3101 MCInst CInst;
3102 bool Res = RISCVRVC::compress(CInst, Inst, getSTI());
3103 if (Res)
3104 ++RISCVNumInstrsCompressed;
3105 S.emitInstruction((Res ? CInst : Inst), getSTI());
3106}
3107
3108void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
3109 MCStreamer &Out) {
3111 RISCVMatInt::generateMCInstSeq(Value, getSTI(), DestReg, Seq);
3112
3113 for (MCInst &Inst : Seq) {
3114 emitToStreamer(Out, Inst);
3115 }
3116}
3117
3118void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
3119 const MCExpr *Symbol,
3121 unsigned SecondOpcode, SMLoc IDLoc,
3122 MCStreamer &Out) {
3123 // A pair of instructions for PC-relative addressing; expands to
3124 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3125 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3126 MCContext &Ctx = getContext();
3127
3128 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
3129 Out.emitLabel(TmpLabel);
3130
3131 const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
3132 emitToStreamer(
3133 Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
3134
3135 const MCExpr *RefToLinkTmpLabel =
3138
3139 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3140 .addOperand(DestReg)
3141 .addOperand(TmpReg)
3142 .addExpr(RefToLinkTmpLabel));
3143}
3144
3145void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3146 MCStreamer &Out) {
3147 // The load local address pseudo-instruction "lla" is used in PC-relative
3148 // addressing of local symbols:
3149 // lla rdest, symbol
3150 // expands to
3151 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3152 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3153 MCOperand DestReg = Inst.getOperand(0);
3154 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3155 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3156 RISCV::ADDI, IDLoc, Out);
3157}
3158
3159void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3160 MCStreamer &Out) {
3161 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3162 // addressing of global symbols:
3163 // lga rdest, symbol
3164 // expands to
3165 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3166 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3167 MCOperand DestReg = Inst.getOperand(0);
3168 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3169 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3170 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_GOT_HI,
3171 SecondOpcode, IDLoc, Out);
3172}
3173
3174void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3175 MCStreamer &Out) {
3176 // The load address pseudo-instruction "la" is used in PC-relative and
3177 // GOT-indirect addressing of global symbols:
3178 // la rdest, symbol
3179 // is an alias for either (for non-PIC)
3180 // lla rdest, symbol
3181 // or (for PIC)
3182 // lga rdest, symbol
3183 if (ParserOptions.IsPicEnabled)
3184 emitLoadGlobalAddress(Inst, IDLoc, Out);
3185 else
3186 emitLoadLocalAddress(Inst, IDLoc, Out);
3187}
3188
3189void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3190 MCStreamer &Out) {
3191 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3192 // initial-exec TLS model addressing of global symbols:
3193 // la.tls.ie rdest, symbol
3194 // expands to
3195 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3196 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3197 MCOperand DestReg = Inst.getOperand(0);
3198 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3199 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3200 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
3201 SecondOpcode, IDLoc, Out);
3202}
3203
3204void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3205 MCStreamer &Out) {
3206 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3207 // global-dynamic TLS model addressing of global symbols:
3208 // la.tls.gd rdest, symbol
3209 // expands to
3210 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3211 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3212 MCOperand DestReg = Inst.getOperand(0);
3213 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3214 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
3215 RISCV::ADDI, IDLoc, Out);
3216}
3217
3218void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3219 SMLoc IDLoc, MCStreamer &Out,
3220 bool HasTmpReg) {
3221 // The load/store pseudo-instruction does a pc-relative load with
3222 // a symbol.
3223 //
3224 // The expansion looks like this
3225 //
3226 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3227 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3228 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3229 MCOperand DestReg = Inst.getOperand(DestRegOpIdx);
3230 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3231 MCOperand TmpReg = Inst.getOperand(0);
3232 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3233 emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3234 Opcode, IDLoc, Out);
3235}
3236
3237void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3238 int64_t Width, SMLoc IDLoc,
3239 MCStreamer &Out) {
3240 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3241 // amounts dependent on the XLEN.
3242 //
3243 // The expansion looks like this
3244 //
3245 // SLLI rd, rs, XLEN - Width
3246 // SR[A|R]I rd, rd, XLEN - Width
3247 MCOperand DestReg = Inst.getOperand(0);
3248 MCOperand SourceReg = Inst.getOperand(1);
3249
3250 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3251 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3252
3253 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3254
3255 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
3256 .addOperand(DestReg)
3257 .addOperand(SourceReg)
3258 .addImm(ShAmt));
3259
3260 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3261 .addOperand(DestReg)
3262 .addOperand(DestReg)
3263 .addImm(ShAmt));
3264}
3265
3266void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3267 MCStreamer &Out) {
3268 if (Inst.getNumOperands() == 3) {
3269 // unmasked va >= x
3270 //
3271 // pseudoinstruction: vmsge{u}.vx vd, va, x
3272 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3273 emitToStreamer(Out, MCInstBuilder(Opcode)
3274 .addOperand(Inst.getOperand(0))
3275 .addOperand(Inst.getOperand(1))
3276 .addOperand(Inst.getOperand(2))
3277 .addReg(RISCV::NoRegister)
3278 .setLoc(IDLoc));
3279 emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
3280 .addOperand(Inst.getOperand(0))
3281 .addOperand(Inst.getOperand(0))
3282 .addOperand(Inst.getOperand(0))
3283 .setLoc(IDLoc));
3284 } else if (Inst.getNumOperands() == 4) {
3285 // masked va >= x, vd != v0
3286 //
3287 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3288 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3289 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3290 "The destination register should not be V0.");
3291 emitToStreamer(Out, MCInstBuilder(Opcode)
3292 .addOperand(Inst.getOperand(0))
3293 .addOperand(Inst.getOperand(1))
3294 .addOperand(Inst.getOperand(2))
3295 .addOperand(Inst.getOperand(3))
3296 .setLoc(IDLoc));
3297 emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
3298 .addOperand(Inst.getOperand(0))
3299 .addOperand(Inst.getOperand(0))
3300 .addReg(RISCV::V0)
3301 .setLoc(IDLoc));
3302 } else if (Inst.getNumOperands() == 5 &&
3303 Inst.getOperand(0).getReg() == RISCV::V0) {
3304 // masked va >= x, vd == v0
3305 //
3306 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3307 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3308 assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
3309 "The destination register should be V0.");
3310 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3311 "The temporary vector register should not be V0.");
3312 emitToStreamer(Out, MCInstBuilder(Opcode)
3313 .addOperand(Inst.getOperand(1))
3314 .addOperand(Inst.getOperand(2))
3315 .addOperand(Inst.getOperand(3))
3316 .addReg(RISCV::NoRegister)
3317 .setLoc(IDLoc));
3318 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3319 .addOperand(Inst.getOperand(0))
3320 .addOperand(Inst.getOperand(0))
3321 .addOperand(Inst.getOperand(1))
3322 .setLoc(IDLoc));
3323 } else if (Inst.getNumOperands() == 5) {
3324 // masked va >= x, any vd
3325 //
3326 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3327 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3328 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3329 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3330 "The temporary vector register should not be V0.");
3331 emitToStreamer(Out, MCInstBuilder(Opcode)
3332 .addOperand(Inst.getOperand(1))
3333 .addOperand(Inst.getOperand(2))
3334 .addOperand(Inst.getOperand(3))
3335 .addReg(RISCV::NoRegister)
3336 .setLoc(IDLoc));
3337 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3338 .addOperand(Inst.getOperand(1))
3339 .addReg(RISCV::V0)
3340 .addOperand(Inst.getOperand(1))
3341 .setLoc(IDLoc));
3342 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3343 .addOperand(Inst.getOperand(0))
3344 .addOperand(Inst.getOperand(0))
3345 .addReg(RISCV::V0)
3346 .setLoc(IDLoc));
3347 emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
3348 .addOperand(Inst.getOperand(0))
3349 .addOperand(Inst.getOperand(1))
3350 .addOperand(Inst.getOperand(0))
3351 .setLoc(IDLoc));
3352 }
3353}
3354
3355bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3357 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3358 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3359 if (Inst.getOperand(2).getReg() != RISCV::X4) {
3360 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3361 return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
3362 "%tprel_add modifier");
3363 }
3364
3365 return false;
3366}
3367
3368bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3370 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3371 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3372 if (Inst.getOperand(0).getReg() != RISCV::X5) {
3373 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3374 return Error(ErrorLoc, "the output operand must be t0/x5 when using "
3375 "%tlsdesc_call modifier");
3376 }
3377
3378 return false;
3379}
3380
3381std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3382 return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
3383 llvm::SMLoc());
3384}
3385
3386std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3387 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
3388 llvm::SMLoc());
3389}
3390
3391std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3392 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
3393 llvm::SMLoc());
3394}
3395
3396bool RISCVAsmParser::validateInstruction(MCInst &Inst,
3398 unsigned Opcode = Inst.getOpcode();
3399
3400 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
3401 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
3402 unsigned DestReg = Inst.getOperand(0).getReg();
3403 unsigned TempReg = Inst.getOperand(1).getReg();
3404 if (DestReg == TempReg) {
3405 SMLoc Loc = Operands.back()->getStartLoc();
3406 return Error(Loc, "the temporary vector register cannot be the same as "
3407 "the destination register");
3408 }
3409 }
3410
3411 if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
3412 Opcode == RISCV::TH_LWD) {
3413 unsigned Rd1 = Inst.getOperand(0).getReg();
3414 unsigned Rd2 = Inst.getOperand(1).getReg();
3415 unsigned Rs1 = Inst.getOperand(2).getReg();
3416 // The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
3417 if (Rs1 == Rd1 && Rs1 == Rd2) {
3418 SMLoc Loc = Operands[1]->getStartLoc();
3419 return Error(Loc, "rs1, rd1, and rd2 cannot all be the same");
3420 }
3421 }
3422
3423 if (Opcode == RISCV::CM_MVSA01) {
3424 unsigned Rd1 = Inst.getOperand(0).getReg();
3425 unsigned Rd2 = Inst.getOperand(1).getReg();
3426 if (Rd1 == Rd2) {
3427 SMLoc Loc = Operands[1]->getStartLoc();
3428 return Error(Loc, "rs1 and rs2 must be different");
3429 }
3430 }
3431
3432 bool IsTHeadMemPair32 = (Opcode == RISCV::TH_LWD ||
3433 Opcode == RISCV::TH_LWUD || Opcode == RISCV::TH_SWD);
3434 bool IsTHeadMemPair64 = (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_SDD);
3435 // The last operand of XTHeadMemPair instructions must be constant 3 or 4
3436 // depending on the data width.
3437 if (IsTHeadMemPair32 && Inst.getOperand(4).getImm() != 3) {
3438 SMLoc Loc = Operands.back()->getStartLoc();
3439 return Error(Loc, "operand must be constant 3");
3440 } else if (IsTHeadMemPair64 && Inst.getOperand(4).getImm() != 4) {
3441 SMLoc Loc = Operands.back()->getStartLoc();
3442 return Error(Loc, "operand must be constant 4");
3443 }
3444
3445 const MCInstrDesc &MCID = MII.get(Opcode);
3446 if (!(MCID.TSFlags & RISCVII::ConstraintMask))
3447 return false;
3448
3449 if (Opcode == RISCV::VC_V_XVW || Opcode == RISCV::VC_V_IVW ||
3450 Opcode == RISCV::VC_V_FVW || Opcode == RISCV::VC_V_VVW) {
3451 // Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for VC_V_XVW.
3452 unsigned VCIXDst = Inst.getOperand(0).getReg();
3453 SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
3454 if (MCID.TSFlags & RISCVII::VS1Constraint) {
3455 unsigned VCIXRs1 = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3456 if (VCIXDst == VCIXRs1)
3457 return Error(VCIXDstLoc, "the destination vector register group cannot"
3458 " overlap the source vector register group");
3459 }
3460 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3461 unsigned VCIXRs2 = Inst.getOperand(Inst.getNumOperands() - 2).getReg();
3462 if (VCIXDst == VCIXRs2)
3463 return Error(VCIXDstLoc, "the destination vector register group cannot"
3464 " overlap the source vector register group");
3465 }
3466 return false;
3467 }
3468
3469 unsigned DestReg = Inst.getOperand(0).getReg();
3470 unsigned Offset = 0;
3471 int TiedOp = MCID.getOperandConstraint(1, MCOI::TIED_TO);
3472 if (TiedOp == 0)
3473 Offset = 1;
3474
3475 // Operands[1] will be the first operand, DestReg.
3476 SMLoc Loc = Operands[1]->getStartLoc();
3477 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3478 unsigned CheckReg = Inst.getOperand(Offset + 1).getReg();
3479 if (DestReg == CheckReg)
3480 return Error(Loc, "the destination vector register group cannot overlap"
3481 " the source vector register group");
3482 }
3483 if ((MCID.TSFlags & RISCVII::VS1Constraint) && Inst.getOperand(Offset + 2).isReg()) {
3484 unsigned CheckReg = Inst.getOperand(Offset + 2).getReg();
3485 if (DestReg == CheckReg)
3486 return Error(Loc, "the destination vector register group cannot overlap"
3487 " the source vector register group");
3488 }
3489 if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
3490 // vadc, vsbc are special cases. These instructions have no mask register.
3491 // The destination register could not be V0.
3492 if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
3493 Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
3494 Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
3495 Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
3496 Opcode == RISCV::VMERGE_VXM)
3497 return Error(Loc, "the destination vector register group cannot be V0");
3498
3499 // Regardless masked or unmasked version, the number of operands is the
3500 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
3501 // actually. We need to check the last operand to ensure whether it is
3502 // masked or not.
3503 unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3504 assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
3505 "Unexpected register for mask operand");
3506
3507 if (DestReg == CheckReg)
3508 return Error(Loc, "the destination vector register group cannot overlap"
3509 " the mask register");
3510 }
3511 return false;
3512}
3513
3514bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
3516 MCStreamer &Out) {
3517 Inst.setLoc(IDLoc);
3518
3519 switch (Inst.getOpcode()) {
3520 default:
3521 break;
3522 case RISCV::PseudoLLAImm:
3523 case RISCV::PseudoLAImm:
3524 case RISCV::PseudoLI: {
3525 MCRegister Reg = Inst.getOperand(0).getReg();
3526 const MCOperand &Op1 = Inst.getOperand(1);
3527 if (Op1.isExpr()) {
3528 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
3529 // Just convert to an addi. This allows compatibility with gas.
3530 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
3531 .addReg(Reg)
3532 .addReg(RISCV::X0)
3533 .addExpr(Op1.getExpr()));
3534 return false;
3535 }
3536 int64_t Imm = Inst.getOperand(1).getImm();
3537 // On RV32 the immediate here can either be a signed or an unsigned
3538 // 32-bit number. Sign extension has to be performed to ensure that Imm
3539 // represents the expected signed 64-bit number.
3540 if (!isRV64())
3541 Imm = SignExtend64<32>(Imm);
3542 emitLoadImm(Reg, Imm, Out);
3543 return false;
3544 }
3545 case RISCV::PseudoLLA:
3546 emitLoadLocalAddress(Inst, IDLoc, Out);
3547 return false;
3548 case RISCV::PseudoLGA:
3549 emitLoadGlobalAddress(Inst, IDLoc, Out);
3550 return false;
3551 case RISCV::PseudoLA:
3552 emitLoadAddress(Inst, IDLoc, Out);
3553 return false;
3554 case RISCV::PseudoLA_TLS_IE:
3555 emitLoadTLSIEAddress(Inst, IDLoc, Out);
3556 return false;
3557 case RISCV::PseudoLA_TLS_GD:
3558 emitLoadTLSGDAddress(Inst, IDLoc, Out);
3559 return false;
3560 case RISCV::PseudoLB:
3561 emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
3562 return false;
3563 case RISCV::PseudoLBU:
3564 emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
3565 return false;
3566 case RISCV::PseudoLH:
3567 emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
3568 return false;
3569 case RISCV::PseudoLHU:
3570 emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
3571 return false;
3572 case RISCV::PseudoLW:
3573 emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
3574 return false;
3575 case RISCV::PseudoLWU:
3576 emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
3577 return false;
3578 case RISCV::PseudoLD:
3579 emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
3580 return false;
3581 case RISCV::PseudoFLH:
3582 emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
3583 return false;
3584 case RISCV::PseudoFLW:
3585 emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
3586 return false;
3587 case RISCV::PseudoFLD:
3588 emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
3589 return false;
3590 case RISCV::PseudoSB:
3591 emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
3592 return false;
3593 case RISCV::PseudoSH:
3594 emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
3595 return false;
3596 case RISCV::PseudoSW:
3597 emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
3598 return false;
3599 case RISCV::PseudoSD:
3600 emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
3601 return false;
3602 case RISCV::PseudoFSH:
3603 emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
3604 return false;
3605 case RISCV::PseudoFSW:
3606 emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
3607 return false;
3608 case RISCV::PseudoFSD:
3609 emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
3610 return false;
3611 case RISCV::PseudoAddTPRel:
3612 if (checkPseudoAddTPRel(Inst, Operands))
3613 return true;
3614 break;
3615 case RISCV::PseudoTLSDESCCall:
3616 if (checkPseudoTLSDESCCall(Inst, Operands))
3617 return true;
3618 break;
3619 case RISCV::PseudoSEXT_B:
3620 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
3621 return false;
3622 case RISCV::PseudoSEXT_H:
3623 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
3624 return false;
3625 case RISCV::PseudoZEXT_H:
3626 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
3627 return false;
3628 case RISCV::PseudoZEXT_W:
3629 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
3630 return false;
3631 case RISCV::PseudoVMSGEU_VX:
3632 case RISCV::PseudoVMSGEU_VX_M:
3633 case RISCV::PseudoVMSGEU_VX_M_T:
3634 emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
3635 return false;
3636 case RISCV::PseudoVMSGE_VX:
3637 case RISCV::PseudoVMSGE_VX_M:
3638 case RISCV::PseudoVMSGE_VX_M_T:
3639 emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
3640 return false;
3641 case RISCV::PseudoVMSGE_VI:
3642 case RISCV::PseudoVMSLT_VI: {
3643 // These instructions are signed and so is immediate so we can subtract one
3644 // and change the opcode.
3645 int64_t Imm = Inst.getOperand(2).getImm();
3646 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
3647 : RISCV::VMSLE_VI;
3648 emitToStreamer(Out, MCInstBuilder(Opc)
3649 .addOperand(Inst.getOperand(0))
3650 .addOperand(Inst.getOperand(1))
3651 .addImm(Imm - 1)
3652 .addOperand(Inst.getOperand(3))
3653 .setLoc(IDLoc));
3654 return false;
3655 }
3656 case RISCV::PseudoVMSGEU_VI:
3657 case RISCV::PseudoVMSLTU_VI: {
3658 int64_t Imm = Inst.getOperand(2).getImm();
3659 // Unsigned comparisons are tricky because the immediate is signed. If the
3660 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
3661 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
3662 // vmsne v0, v1, v1 which is always false.
3663 if (Imm == 0) {
3664 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3665 ? RISCV::VMSEQ_VV
3666 : RISCV::VMSNE_VV;
3667 emitToStreamer(Out, MCInstBuilder(Opc)
3668 .addOperand(Inst.getOperand(0))
3669 .addOperand(Inst.getOperand(1))
3670 .addOperand(Inst.getOperand(1))
3671 .addOperand(Inst.getOperand(3))
3672 .setLoc(IDLoc));
3673 } else {
3674 // Other immediate values can subtract one like signed.
3675 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3676 ? RISCV::VMSGTU_VI
3677 : RISCV::VMSLEU_VI;
3678 emitToStreamer(Out, MCInstBuilder(Opc)
3679 .addOperand(Inst.getOperand(0))
3680 .addOperand(Inst.getOperand(1))
3681 .addImm(Imm - 1)
3682 .addOperand(Inst.getOperand(3))
3683 .setLoc(IDLoc));
3684 }
3685
3686 return false;
3687 }
3688 }
3689
3690 emitToStreamer(Out, Inst);
3691 return false;
3692}
3693
3697}
static MCRegister MatchRegisterName(StringRef Name)
static const char * getSubtargetFeatureName(uint64_t Val)
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static bool matchRegisterNameHelper(const MCSubtargetInfo &STI, MCRegister &Reg, StringRef Name)
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define check(cond)
#define RegName(no)
static LVOptions Options
Definition: LVOptions.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
unsigned Reg
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
PowerPC TLS Dynamic Call Fixup
if(VerifyEach)
bool isValidInsnFormat(StringRef Format, bool AllowC)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmParser()
static MCRegister convertFPR64ToFPR32(MCRegister Reg)
static cl::opt< bool > AddBuildAttributes("riscv-add-build-attributes", cl::init(false))
static MCRegister convertFPR64ToFPR16(MCRegister Reg)
static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg, unsigned Kind)
static bool isDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)
Class for arbitrary precision integers.
Definition: APInt.h:77
Target independent representation for an assembler token.
Definition: MCAsmMacro.h:21
SMLoc getLoc() const
Definition: MCAsmLexer.cpp:26
int64_t getIntVal() const
Definition: MCAsmMacro.h:115
bool isNot(TokenKind K) const
Definition: MCAsmMacro.h:83
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition: MCAsmMacro.h:110
StringRef getStringContents() const
Get the contents of a string token (without quotes).
Definition: MCAsmMacro.h:90
bool is(TokenKind K) const
Definition: MCAsmMacro.h:82
SMLoc getEndLoc() const
Definition: MCAsmLexer.cpp:30
StringRef getIdentifier() const
Get the identifier string for the current token, which should be an identifier or a string.
Definition: MCAsmMacro.h:99
This class represents an Operation in the Expression.
Encoding
Size and signedness of expression operations' operands.
Base class for user error types.
Definition: Error.h:352
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Container class for subtarget features.
constexpr size_t size() const
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:123
virtual void eatToEndOfStatement()=0
Skip to the end of the current statement, for error recovery.
virtual MCStreamer & getStreamer()=0
Return the output streamer for the assembler.
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression.
const AsmToken & getTok() const
Get the current AsmToken from the stream.
Definition: MCAsmParser.cpp:40
virtual bool parseIdentifier(StringRef &Res)=0
Parse an identifier or string (as a quoted identifier) and set Res to the identifier contents.
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 MCContext & getContext()=0
static const MCBinaryExpr * create(Opcode Op, const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition: MCExpr.cpp:183
@ Sub
Subtraction.
Definition: MCExpr.h:517
@ Add
Addition.
Definition: MCExpr.h:495
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:81
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:416
MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
Definition: MCContext.cpp:324
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:809
ExprKind getKind() const
Definition: MCExpr.h:81
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
unsigned getNumOperands() const
Definition: MCInst.h:208
void setLoc(SMLoc loc)
Definition: MCInst.h:203
unsigned getOpcode() const
Definition: MCInst.h:198
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
ArrayRef< MCOperandInfo > operands() const
Definition: MCInstrDesc.h:239
unsigned short NumOperands
Definition: MCInstrDesc.h:206
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
Definition: MCInstrDesc.h:219
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:63
bool isPositionIndependent() const
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:36
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:134
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:162
int64_t getImm() const
Definition: MCInst.h:80
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:141
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:69
bool isReg() const
Definition: MCInst.h:61
const MCExpr * getExpr() const
Definition: MCInst.h:114
bool isExpr() const
Definition: MCInst.h:65
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx, const MCRegisterClass *RC) const
Return a super-register of the specified register Reg so its sub-register of index SubIdx is Reg.
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Streaming machine code generation interface.
Definition: MCStreamer.h:212
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:424
MCTargetStreamer * getTargetStreamer()
Definition: MCStreamer.h:306
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
void setFeatureBits(const FeatureBitset &FeatureBits_)
const Triple & getTargetTriple() const
const FeatureBitset & getFeatureBits() const
FeatureBitset ToggleFeature(uint64_t FB)
Toggle a feature and return the re-computed feature bits.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:397
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
MCTargetAsmParser - Generic interface to target specific assembly parsers.
virtual ParseStatus parseDirective(AsmToken DirectiveID)
Parses a target-specific assembler directive.
MCSubtargetInfo & copySTI()
Create a copy of STI and return a non-const reference to it.
virtual bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc)=0
virtual ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc)=0
tryParseRegister - parse one register if possible
void setAvailableFeatures(const FeatureBitset &Value)
const MCSubtargetInfo & getSTI() const
virtual unsigned validateTargetOperandClass(MCParsedAsmOperand &Op, unsigned Kind)
Allow a target to add special case operand matching for things that tblgen doesn't/can't handle effec...
virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands)=0
ParseInstruction - Parse one assembly instruction.
virtual unsigned checkTargetMatchPredicate(MCInst &Inst)
checkTargetMatchPredicate - Validate the instruction match against any complex target predicates not ...
virtual bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm)=0
MatchAndEmitInstruction - Recognize a series of operands of a parsed instruction as an actual MCInst ...
Target specific streamer interface.
Definition: MCStreamer.h:93
This represents an "assembler immediate".
Definition: MCValue.h:36
uint32_t getRefKind() const
Definition: MCValue.h:46
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:44
Ternary parse status returned by various parse* methods.
static constexpr StatusTy Failure
static constexpr StatusTy Success
static constexpr StatusTy NoMatch
static bool isSupportedExtensionFeature(StringRef Ext)
static std::string getTargetFeatureForExtension(StringRef Ext)
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true, bool IgnoreUnknown=false)
Parse RISC-V ISA info from arch string.
static const char * getRegisterName(MCRegister Reg)
static const RISCVMCExpr * create(const MCExpr *Expr, VariantKind Kind, MCContext &Ctx)
Definition: RISCVMCExpr.cpp:31
static VariantKind getVariantKindForName(StringRef name)
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
Represents a range in source code.
Definition: SMLoc.h:48
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
This class wraps a string in an Error.
Definition: Error.h:1235
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:223
char back() const
back - Get the last character in the string.
Definition: StringRef.h:146
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:90
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
uint16_t StackAdjustment(const RuntimeFunction &RF)
StackAdjustment - calculated stack adjustment in words.
Definition: ARMWinEH.h:199
std::optional< unsigned > attrTypeFromString(StringRef tag, TagNameMap tagNameMap)
ABI computeTargetABI(const Triple &TT, const FeatureBitset &FeatureBits, StringRef ABIName)
const TagNameMap & getRISCVAttributeTags()
static RoundingMode stringToRoundingMode(StringRef Str)
llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatureBits(bool IsRV64, const FeatureBitset &FeatureBits)
int getLoadFPImm(APFloat FPImm)
getLoadFPImm - Return a 5-bit binary encoding of the floating-point immediate value.
void generateMCInstSeq(int64_t Val, const MCSubtargetInfo &STI, MCRegister DestReg, SmallVectorImpl< MCInst > &Insts)
bool compress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
static bool isValidLMUL(unsigned LMUL, bool Fractional)
static RISCVII::VLMUL encodeLMUL(unsigned LMUL, bool Fractional)
static bool isValidSEW(unsigned SEW)
void printVType(unsigned VType, raw_ostream &OS)
unsigned encodeVTYPE(RISCVII::VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic)
unsigned encodeRlist(MCRegister EndReg, bool IsRV32E=false)
void printRlist(unsigned SlistEncode, raw_ostream &OS)
static bool getSpimm(unsigned RlistVal, unsigned &SpimmVal, int64_t StackAdjustment, bool IsRV64)
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
Format
The format used for serializing/deserializing remarks.
Definition: RemarkFormat.h:25
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition: Error.h:1071
@ Offset
Definition: DWP.cpp:456
@ Length
Definition: DWP.cpp:456
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:239
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:167
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:970
Target & getTheRISCV32Target()
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1954
DWARFExpression::Operation Op
Target & getTheRISCV64Target()
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition: MathExtras.h:170
const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures]
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...
Used to provide key value pairs for feature and CPU bit flags.