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 == 1 && "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 State = VTypeState_TailPolicy;
2159 return false;
2160 }
2161 case VTypeState_TailPolicy:
2162 if (Identifier == "ta")
2163 TailAgnostic = true;
2164 else if (Identifier == "tu")
2165 TailAgnostic = false;
2166 else
2167 break;
2168 State = VTypeState_MaskPolicy;
2169 return false;
2170 case VTypeState_MaskPolicy:
2171 if (Identifier == "ma")
2172 MaskAgnostic = true;
2173 else if (Identifier == "mu")
2174 MaskAgnostic = false;
2175 else
2176 break;
2177 State = VTypeState_Done;
2178 return false;
2179 case VTypeState_Done:
2180 // Extra token?
2181 break;
2182 }
2183
2184 return true;
2185}
2186
2187ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2188 SMLoc S = getLoc();
2189
2190 unsigned Sew = 0;
2191 unsigned Lmul = 0;
2192 bool Fractional = false;
2193 bool TailAgnostic = false;
2194 bool MaskAgnostic = false;
2195
2196 VTypeState State = VTypeState_SEW;
2197
2198 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2199 MaskAgnostic))
2200 return ParseStatus::NoMatch;
2201
2202 getLexer().Lex();
2203
2204 while (parseOptionalToken(AsmToken::Comma)) {
2205 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2206 MaskAgnostic))
2207 break;
2208
2209 getLexer().Lex();
2210 }
2211
2212 if (getLexer().is(AsmToken::EndOfStatement) && State == VTypeState_Done) {
2213 RISCVII::VLMUL VLMUL = RISCVVType::encodeLMUL(Lmul, Fractional);
2214
2215 unsigned VTypeI =
2216 RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
2217 Operands.push_back(RISCVOperand::createVType(VTypeI, S));
2218 return ParseStatus::Success;
2219 }
2220
2221 return generateVTypeError(S);
2222}
2223
2224bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2225 return Error(
2226 ErrorLoc,
2227 "operand must be "
2228 "e[8|16|32|64|128|256|512|1024],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2229}
2230
2231ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2232 if (getLexer().isNot(AsmToken::Identifier))
2233 return ParseStatus::NoMatch;
2234
2235 StringRef Name = getLexer().getTok().getIdentifier();
2236 if (!Name.consume_back(".t"))
2237 return Error(getLoc(), "expected '.t' suffix");
2239
2240 if (!RegNo)
2241 return ParseStatus::NoMatch;
2242 if (RegNo != RISCV::V0)
2243 return ParseStatus::NoMatch;
2244 SMLoc S = getLoc();
2246 getLexer().Lex();
2247 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
2248 return ParseStatus::Success;
2249}
2250
2251ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
2252 if (getLexer().isNot(AsmToken::Identifier))
2253 return ParseStatus::NoMatch;
2254
2255 StringRef Name = getLexer().getTok().getIdentifier();
2257
2258 if (!RegNo)
2259 return ParseStatus::NoMatch;
2260 SMLoc S = getLoc();
2262 getLexer().Lex();
2263 Operands.push_back(RISCVOperand::createReg(
2264 RegNo, S, E, !getSTI().hasFeature(RISCV::FeatureStdExtF)));
2265 return ParseStatus::Success;
2266}
2267
2268template <bool IsRV64>
2269ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
2270 return parseGPRPair(Operands, IsRV64);
2271}
2272
2273ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
2274 bool IsRV64Inst) {
2275 // If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
2276 // RV64 as it will prevent matching the RV64 version of the same instruction
2277 // that doesn't use a GPRPair.
2278 // If this is an RV64 GPRPair instruction, there is no RV32 version so we can
2279 // still parse as a pair.
2280 if (!IsRV64Inst && isRV64())
2281 return ParseStatus::NoMatch;
2282
2283 if (getLexer().isNot(AsmToken::Identifier))
2284 return ParseStatus::NoMatch;
2285
2286 StringRef Name = getLexer().getTok().getIdentifier();
2288
2289 if (!RegNo)
2290 return ParseStatus::NoMatch;
2291
2292 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(RegNo))
2293 return ParseStatus::NoMatch;
2294
2295 if ((RegNo - RISCV::X0) & 1)
2296 return TokError("register must be even");
2297
2298 SMLoc S = getLoc();
2300 getLexer().Lex();
2301
2302 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2303 unsigned Pair = RI->getMatchingSuperReg(
2304 RegNo, RISCV::sub_gpr_even,
2305 &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2306 Operands.push_back(RISCVOperand::createReg(Pair, S, E));
2307 return ParseStatus::Success;
2308}
2309
2310ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2311 if (getLexer().isNot(AsmToken::Identifier))
2312 return TokError(
2313 "operand must be a valid floating point rounding mode mnemonic");
2314
2315 StringRef Str = getLexer().getTok().getIdentifier();
2317
2318 if (FRM == RISCVFPRndMode::Invalid)
2319 return TokError(
2320 "operand must be a valid floating point rounding mode mnemonic");
2321
2322 Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
2323 Lex(); // Eat identifier token.
2324 return ParseStatus::Success;
2325}
2326
2327ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2328 const AsmToken &Tok = getLexer().getTok();
2329
2330 if (Tok.is(AsmToken::Integer)) {
2331 if (Tok.getIntVal() != 0)
2332 goto ParseFail;
2333
2334 Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
2335 Lex();
2336 return ParseStatus::Success;
2337 }
2338
2339 if (Tok.is(AsmToken::Identifier)) {
2340 StringRef Str = Tok.getIdentifier();
2341
2342 // Letters must be unique, taken from 'iorw', and in ascending order. This
2343 // holds as long as each individual character is one of 'iorw' and is
2344 // greater than the previous character.
2345 unsigned Imm = 0;
2346 bool Valid = true;
2347 char Prev = '\0';
2348 for (char c : Str) {
2349 switch (c) {
2350 default:
2351 Valid = false;
2352 break;
2353 case 'i':
2355 break;
2356 case 'o':
2358 break;
2359 case 'r':
2361 break;
2362 case 'w':
2364 break;
2365 }
2366
2367 if (c <= Prev) {
2368 Valid = false;
2369 break;
2370 }
2371 Prev = c;
2372 }
2373
2374 if (!Valid)
2375 goto ParseFail;
2376
2377 Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
2378 Lex();
2379 return ParseStatus::Success;
2380 }
2381
2382ParseFail:
2383 return TokError("operand must be formed of letters selected in-order from "
2384 "'iorw' or be 0");
2385}
2386
2387ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2388 if (parseToken(AsmToken::LParen, "expected '('"))
2389 return ParseStatus::Failure;
2390 Operands.push_back(RISCVOperand::createToken("(", getLoc()));
2391
2392 if (!parseRegister(Operands).isSuccess())
2393 return Error(getLoc(), "expected register");
2394
2395 if (parseToken(AsmToken::RParen, "expected ')'"))
2396 return ParseStatus::Failure;
2397 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
2398
2399 return ParseStatus::Success;
2400}
2401
2402ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2403 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2404 // as one of their register operands, such as `(a0)`. This just denotes that
2405 // the register (in this case `a0`) contains a memory address.
2406 //
2407 // Normally, we would be able to parse these by putting the parens into the
2408 // instruction string. However, GNU as also accepts a zero-offset memory
2409 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2410 // with parseImmediate followed by parseMemOpBaseReg, but these instructions
2411 // do not accept an immediate operand, and we do not want to add a "dummy"
2412 // operand that is silently dropped.
2413 //
2414 // Instead, we use this custom parser. This will: allow (and discard) an
2415 // offset if it is zero; require (and discard) parentheses; and add only the
2416 // parsed register operand to `Operands`.
2417 //
2418 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2419 // which will only print the register surrounded by parentheses (which GNU as
2420 // also uses as its canonical representation for these operands).
2421 std::unique_ptr<RISCVOperand> OptionalImmOp;
2422
2423 if (getLexer().isNot(AsmToken::LParen)) {
2424 // Parse an Integer token. We do not accept arbritrary constant expressions
2425 // in the offset field (because they may include parens, which complicates
2426 // parsing a lot).
2427 int64_t ImmVal;
2428 SMLoc ImmStart = getLoc();
2429 if (getParser().parseIntToken(ImmVal,
2430 "expected '(' or optional integer offset"))
2431 return ParseStatus::Failure;
2432
2433 // Create a RISCVOperand for checking later (so the error messages are
2434 // nicer), but we don't add it to Operands.
2435 SMLoc ImmEnd = getLoc();
2436 OptionalImmOp =
2437 RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
2438 ImmStart, ImmEnd, isRV64());
2439 }
2440
2441 if (parseToken(AsmToken::LParen,
2442 OptionalImmOp ? "expected '(' after optional integer offset"
2443 : "expected '(' or optional integer offset"))
2444 return ParseStatus::Failure;
2445
2446 if (!parseRegister(Operands).isSuccess())
2447 return Error(getLoc(), "expected register");
2448
2449 if (parseToken(AsmToken::RParen, "expected ')'"))
2450 return ParseStatus::Failure;
2451
2452 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2453 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2454 return Error(
2455 OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
2456 SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2457
2458 return ParseStatus::Success;
2459}
2460
2461ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2462 // RR : a2(a1)
2463 if (getLexer().getKind() != AsmToken::Identifier)
2464 return ParseStatus::NoMatch;
2465
2466 StringRef RegName = getLexer().getTok().getIdentifier();
2468 if (!Reg)
2469 return Error(getLoc(), "invalid register");
2470 getLexer().Lex();
2471
2472 if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
2473 return ParseStatus::Failure;
2474
2475 if (getLexer().getKind() != AsmToken::Identifier)
2476 return Error(getLoc(), "expected register");
2477
2478 StringRef Reg2Name = getLexer().getTok().getIdentifier();
2479 MCRegister Reg2 = matchRegisterNameHelper(Reg2Name);
2480 if (!Reg2)
2481 return Error(getLoc(), "invalid register");
2482 getLexer().Lex();
2483
2484 if (parseToken(AsmToken::RParen, "expected ')'"))
2485 return ParseStatus::Failure;
2486
2487 Operands.push_back(RISCVOperand::createRegReg(Reg, Reg2, getLoc()));
2488
2489 return ParseStatus::Success;
2490}
2491
2492ParseStatus RISCVAsmParser::parseReglist(OperandVector &Operands) {
2493 // Rlist: {ra [, s0[-sN]]}
2494 // XRlist: {x1 [, x8[-x9][, x18[-xN]]]}
2495 SMLoc S = getLoc();
2496
2497 if (parseToken(AsmToken::LCurly, "register list must start with '{'"))
2498 return ParseStatus::Failure;
2499
2500 bool IsEABI = isRVE();
2501
2502 if (getLexer().isNot(AsmToken::Identifier))
2503 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2504
2505 StringRef RegName = getLexer().getTok().getIdentifier();
2507 MCRegister RegEnd;
2508 if (RegStart != RISCV::X1)
2509 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2510 getLexer().Lex();
2511
2512 // parse case like ,s0
2513 if (parseOptionalToken(AsmToken::Comma)) {
2514 if (getLexer().isNot(AsmToken::Identifier))
2515 return Error(getLoc(), "invalid register");
2516 StringRef RegName = getLexer().getTok().getIdentifier();
2517 RegStart = matchRegisterNameHelper(RegName);
2518 if (!RegStart)
2519 return Error(getLoc(), "invalid register");
2520 if (RegStart != RISCV::X8)
2521 return Error(getLoc(),
2522 "continuous register list must start from 's0' or 'x8'");
2523 getLexer().Lex(); // eat reg
2524 }
2525
2526 // parse case like -s1
2527 if (parseOptionalToken(AsmToken::Minus)) {
2528 StringRef EndName = getLexer().getTok().getIdentifier();
2529 // FIXME: the register mapping and checks of EABI is wrong
2530 RegEnd = matchRegisterNameHelper(EndName);
2531 if (!RegEnd)
2532 return Error(getLoc(), "invalid register");
2533 if (IsEABI && RegEnd != RISCV::X9)
2534 return Error(getLoc(), "contiguous register list of EABI can only be "
2535 "'s0-s1' or 'x8-x9' pair");
2536 getLexer().Lex();
2537 }
2538
2539 if (!IsEABI) {
2540 // parse extra part like ', x18[-x20]' for XRegList
2541 if (parseOptionalToken(AsmToken::Comma)) {
2542 if (RegEnd != RISCV::X9)
2543 return Error(
2544 getLoc(),
2545 "first contiguous registers pair of register list must be 'x8-x9'");
2546
2547 // parse ', x18' for extra part
2548 if (getLexer().isNot(AsmToken::Identifier))
2549 return Error(getLoc(), "invalid register");
2550 StringRef EndName = getLexer().getTok().getIdentifier();
2551 if (MatchRegisterName(EndName) != RISCV::X18)
2552 return Error(getLoc(),
2553 "second contiguous registers pair of register list "
2554 "must start from 'x18'");
2555 getLexer().Lex();
2556
2557 // parse '-x20' for extra part
2558 if (parseOptionalToken(AsmToken::Minus)) {
2559 if (getLexer().isNot(AsmToken::Identifier))
2560 return Error(getLoc(), "invalid register");
2561 EndName = getLexer().getTok().getIdentifier();
2562 if (MatchRegisterName(EndName) == RISCV::NoRegister)
2563 return Error(getLoc(), "invalid register");
2564 getLexer().Lex();
2565 }
2566 RegEnd = MatchRegisterName(EndName);
2567 }
2568 }
2569
2570 if (RegEnd == RISCV::X26)
2571 return Error(getLoc(), "invalid register list, {ra, s0-s10} or {x1, x8-x9, "
2572 "x18-x26} is not supported");
2573
2574 if (parseToken(AsmToken::RCurly, "register list must end with '}'"))
2575 return ParseStatus::Failure;
2576
2577 if (RegEnd == RISCV::NoRegister)
2578 RegEnd = RegStart;
2579
2580 auto Encode = RISCVZC::encodeRlist(RegEnd, IsEABI);
2581 if (Encode == RISCVZC::INVALID_RLIST)
2582 return Error(S, "invalid register list");
2583 Operands.push_back(RISCVOperand::createRlist(Encode, S));
2584
2585 return ParseStatus::Success;
2586}
2587
2588ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
2589 bool ExpectNegative) {
2590 bool Negative = parseOptionalToken(AsmToken::Minus);
2591
2592 SMLoc S = getLoc();
2593 int64_t StackAdjustment = getLexer().getTok().getIntVal();
2594 unsigned Spimm = 0;
2595 unsigned RlistVal = static_cast<RISCVOperand *>(Operands[1].get())->Rlist.Val;
2596
2597 if (Negative != ExpectNegative ||
2598 !RISCVZC::getSpimm(RlistVal, Spimm, StackAdjustment, isRV64()))
2599 return ParseStatus::NoMatch;
2600 Operands.push_back(RISCVOperand::createSpimm(Spimm << 4, S));
2601 getLexer().Lex();
2602 return ParseStatus::Success;
2603}
2604
2605/// Looks at a token type and creates the relevant operand from this
2606/// information, adding to Operands. If operand was parsed, returns false, else
2607/// true.
2608bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2609 // Check if the current operand has a custom associated parser, if so, try to
2610 // custom parse the operand, or fallback to the general approach.
2612 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
2613 if (Result.isSuccess())
2614 return false;
2615 if (Result.isFailure())
2616 return true;
2617
2618 // Attempt to parse token as a register.
2619 if (parseRegister(Operands, true).isSuccess())
2620 return false;
2621
2622 // Attempt to parse token as an immediate
2623 if (parseImmediate(Operands).isSuccess()) {
2624 // Parse memory base register if present
2625 if (getLexer().is(AsmToken::LParen))
2626 return !parseMemOpBaseReg(Operands).isSuccess();
2627 return false;
2628 }
2629
2630 // Finally we have exhausted all options and must declare defeat.
2631 Error(getLoc(), "unknown operand");
2632 return true;
2633}
2634
2635bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
2636 StringRef Name, SMLoc NameLoc,
2638 // Ensure that if the instruction occurs when relaxation is enabled,
2639 // relocations are forced for the file. Ideally this would be done when there
2640 // is enough information to reliably determine if the instruction itself may
2641 // cause relaxations. Unfortunately instruction processing stage occurs in the
2642 // same pass as relocation emission, so it's too late to set a 'sticky bit'
2643 // for the entire file.
2644 if (getSTI().hasFeature(RISCV::FeatureRelax)) {
2645 auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
2646 if (Assembler != nullptr) {
2647 RISCVAsmBackend &MAB =
2648 static_cast<RISCVAsmBackend &>(Assembler->getBackend());
2649 MAB.setForceRelocs();
2650 }
2651 }
2652
2653 // First operand is token for instruction
2654 Operands.push_back(RISCVOperand::createToken(Name, NameLoc));
2655
2656 // If there are no more operands, then finish
2657 if (getLexer().is(AsmToken::EndOfStatement)) {
2658 getParser().Lex(); // Consume the EndOfStatement.
2659 return false;
2660 }
2661
2662 // Parse first operand
2663 if (parseOperand(Operands, Name))
2664 return true;
2665
2666 // Parse until end of statement, consuming commas between operands
2667 while (parseOptionalToken(AsmToken::Comma)) {
2668 // Parse next operand
2669 if (parseOperand(Operands, Name))
2670 return true;
2671 }
2672
2673 if (getParser().parseEOL("unexpected token")) {
2674 getParser().eatToEndOfStatement();
2675 return true;
2676 }
2677 return false;
2678}
2679
2680bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2683
2684 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
2685 Kind = RE->getKind();
2686 Expr = RE->getSubExpr();
2687 }
2688
2689 MCValue Res;
2690 MCFixup Fixup;
2691 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup))
2692 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None;
2693 return false;
2694}
2695
2696bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
2697 MCValue Res;
2698 MCFixup Fixup;
2699 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup)) {
2700 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None && Res.getSymA() &&
2701 Res.getSymB();
2702 }
2703 return false;
2704}
2705
2706ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
2707 StringRef IDVal = DirectiveID.getString();
2708
2709 if (IDVal == ".option")
2710 return parseDirectiveOption();
2711 if (IDVal == ".attribute")
2712 return parseDirectiveAttribute();
2713 if (IDVal == ".insn")
2714 return parseDirectiveInsn(DirectiveID.getLoc());
2715 if (IDVal == ".variant_cc")
2716 return parseDirectiveVariantCC();
2717
2718 return ParseStatus::NoMatch;
2719}
2720
2721bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
2722 bool FromOptionDirective) {
2723 for (auto &Feature : RISCVFeatureKV)
2725 clearFeatureBits(Feature.Value, Feature.Key);
2726
2727 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
2728 Arch, /*EnableExperimentalExtension=*/true,
2729 /*ExperimentalExtensionVersionCheck=*/true);
2730 if (!ParseResult) {
2731 std::string Buffer;
2732 raw_string_ostream OutputErrMsg(Buffer);
2733 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2734 OutputErrMsg << "invalid arch name '" << Arch << "', "
2735 << ErrMsg.getMessage();
2736 });
2737
2738 return Error(Loc, OutputErrMsg.str());
2739 }
2740 auto &ISAInfo = *ParseResult;
2741
2742 for (auto &Feature : RISCVFeatureKV)
2743 if (ISAInfo->hasExtension(Feature.Key))
2744 setFeatureBits(Feature.Value, Feature.Key);
2745
2746 if (FromOptionDirective) {
2747 if (ISAInfo->getXLen() == 32 && isRV64())
2748 return Error(Loc, "bad arch string switching from rv64 to rv32");
2749 else if (ISAInfo->getXLen() == 64 && !isRV64())
2750 return Error(Loc, "bad arch string switching from rv32 to rv64");
2751 }
2752
2753 if (ISAInfo->getXLen() == 32)
2754 clearFeatureBits(RISCV::Feature64Bit, "64bit");
2755 else if (ISAInfo->getXLen() == 64)
2756 setFeatureBits(RISCV::Feature64Bit, "64bit");
2757 else
2758 return Error(Loc, "bad arch string " + Arch);
2759
2760 Result = ISAInfo->toString();
2761 return false;
2762}
2763
2764bool RISCVAsmParser::parseDirectiveOption() {
2765 MCAsmParser &Parser = getParser();
2766 // Get the option token.
2767 AsmToken Tok = Parser.getTok();
2768
2769 // At the moment only identifiers are supported.
2770 if (parseToken(AsmToken::Identifier, "expected identifier"))
2771 return true;
2772
2774
2775 if (Option == "push") {
2776 if (Parser.parseEOL())
2777 return true;
2778
2779 getTargetStreamer().emitDirectiveOptionPush();
2780 pushFeatureBits();
2781 return false;
2782 }
2783
2784 if (Option == "pop") {
2785 SMLoc StartLoc = Parser.getTok().getLoc();
2786 if (Parser.parseEOL())
2787 return true;
2788
2789 getTargetStreamer().emitDirectiveOptionPop();
2790 if (popFeatureBits())
2791 return Error(StartLoc, ".option pop with no .option push");
2792
2793 return false;
2794 }
2795
2796 if (Option == "arch") {
2798 do {
2799 if (Parser.parseComma())
2800 return true;
2801
2803 if (parseOptionalToken(AsmToken::Plus))
2804 Type = RISCVOptionArchArgType::Plus;
2805 else if (parseOptionalToken(AsmToken::Minus))
2806 Type = RISCVOptionArchArgType::Minus;
2807 else if (!Args.empty())
2808 return Error(Parser.getTok().getLoc(),
2809 "unexpected token, expected + or -");
2810 else
2811 Type = RISCVOptionArchArgType::Full;
2812
2813 if (Parser.getTok().isNot(AsmToken::Identifier))
2814 return Error(Parser.getTok().getLoc(),
2815 "unexpected token, expected identifier");
2816
2817 StringRef Arch = Parser.getTok().getString();
2818 SMLoc Loc = Parser.getTok().getLoc();
2819 Parser.Lex();
2820
2821 if (Type == RISCVOptionArchArgType::Full) {
2822 std::string Result;
2823 if (resetToArch(Arch, Loc, Result, true))
2824 return true;
2825
2826 Args.emplace_back(Type, Result);
2827 break;
2828 }
2829
2830 if (isDigit(Arch.back()))
2831 return Error(
2832 Loc, "Extension version number parsing not currently implemented");
2833
2834 std::string Feature = RISCVISAInfo::getTargetFeatureForExtension(Arch);
2835 if (!enableExperimentalExtension() &&
2836 StringRef(Feature).starts_with("experimental-"))
2837 return Error(Loc, "Unexpected experimental extensions.");
2838 auto Ext = llvm::lower_bound(RISCVFeatureKV, Feature);
2839 if (Ext == std::end(RISCVFeatureKV) || StringRef(Ext->Key) != Feature)
2840 return Error(Loc, "unknown extension feature");
2841
2842 Args.emplace_back(Type, Arch.str());
2843
2844 if (Type == RISCVOptionArchArgType::Plus) {
2845 FeatureBitset OldFeatureBits = STI->getFeatureBits();
2846
2847 setFeatureBits(Ext->Value, Ext->Key);
2848 auto ParseResult = RISCVFeatures::parseFeatureBits(isRV64(), STI->getFeatureBits());
2849 if (!ParseResult) {
2850 copySTI().setFeatureBits(OldFeatureBits);
2851 setAvailableFeatures(ComputeAvailableFeatures(OldFeatureBits));
2852
2853 std::string Buffer;
2854 raw_string_ostream OutputErrMsg(Buffer);
2855 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2856 OutputErrMsg << ErrMsg.getMessage();
2857 });
2858
2859 return Error(Loc, OutputErrMsg.str());
2860 }
2861 } else {
2862 assert(Type == RISCVOptionArchArgType::Minus);
2863 // It is invalid to disable an extension that there are other enabled
2864 // extensions depend on it.
2865 // TODO: Make use of RISCVISAInfo to handle this
2866 for (auto &Feature : RISCVFeatureKV) {
2867 if (getSTI().hasFeature(Feature.Value) &&
2868 Feature.Implies.test(Ext->Value))
2869 return Error(Loc,
2870 Twine("Can't disable ") + Ext->Key + " extension, " +
2871 Feature.Key + " extension requires " + Ext->Key +
2872 " extension be enabled");
2873 }
2874
2875 clearFeatureBits(Ext->Value, Ext->Key);
2876 }
2877 } while (Parser.getTok().isNot(AsmToken::EndOfStatement));
2878
2879 if (Parser.parseEOL())
2880 return true;
2881
2882 getTargetStreamer().emitDirectiveOptionArch(Args);
2883 return false;
2884 }
2885
2886 if (Option == "rvc") {
2887 if (Parser.parseEOL())
2888 return true;
2889
2890 getTargetStreamer().emitDirectiveOptionRVC();
2891 setFeatureBits(RISCV::FeatureStdExtC, "c");
2892 return false;
2893 }
2894
2895 if (Option == "norvc") {
2896 if (Parser.parseEOL())
2897 return true;
2898
2899 getTargetStreamer().emitDirectiveOptionNoRVC();
2900 clearFeatureBits(RISCV::FeatureStdExtC, "c");
2901 clearFeatureBits(RISCV::FeatureStdExtZca, "zca");
2902 return false;
2903 }
2904
2905 if (Option == "pic") {
2906 if (Parser.parseEOL())
2907 return true;
2908
2909 getTargetStreamer().emitDirectiveOptionPIC();
2910 ParserOptions.IsPicEnabled = true;
2911 return false;
2912 }
2913
2914 if (Option == "nopic") {
2915 if (Parser.parseEOL())
2916 return true;
2917
2918 getTargetStreamer().emitDirectiveOptionNoPIC();
2919 ParserOptions.IsPicEnabled = false;
2920 return false;
2921 }
2922
2923 if (Option == "relax") {
2924 if (Parser.parseEOL())
2925 return true;
2926
2927 getTargetStreamer().emitDirectiveOptionRelax();
2928 setFeatureBits(RISCV::FeatureRelax, "relax");
2929 return false;
2930 }
2931
2932 if (Option == "norelax") {
2933 if (Parser.parseEOL())
2934 return true;
2935
2936 getTargetStreamer().emitDirectiveOptionNoRelax();
2937 clearFeatureBits(RISCV::FeatureRelax, "relax");
2938 return false;
2939 }
2940
2941 // Unknown option.
2942 Warning(Parser.getTok().getLoc(), "unknown option, expected 'push', 'pop', "
2943 "'rvc', 'norvc', 'arch', 'relax' or "
2944 "'norelax'");
2945 Parser.eatToEndOfStatement();
2946 return false;
2947}
2948
2949/// parseDirectiveAttribute
2950/// ::= .attribute expression ',' ( expression | "string" )
2951/// ::= .attribute identifier ',' ( expression | "string" )
2952bool RISCVAsmParser::parseDirectiveAttribute() {
2953 MCAsmParser &Parser = getParser();
2954 int64_t Tag;
2955 SMLoc TagLoc;
2956 TagLoc = Parser.getTok().getLoc();
2957 if (Parser.getTok().is(AsmToken::Identifier)) {
2958 StringRef Name = Parser.getTok().getIdentifier();
2959 std::optional<unsigned> Ret =
2961 if (!Ret)
2962 return Error(TagLoc, "attribute name not recognised: " + Name);
2963 Tag = *Ret;
2964 Parser.Lex();
2965 } else {
2966 const MCExpr *AttrExpr;
2967
2968 TagLoc = Parser.getTok().getLoc();
2969 if (Parser.parseExpression(AttrExpr))
2970 return true;
2971
2972 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
2973 if (check(!CE, TagLoc, "expected numeric constant"))
2974 return true;
2975
2976 Tag = CE->getValue();
2977 }
2978
2979 if (Parser.parseComma())
2980 return true;
2981
2982 StringRef StringValue;
2983 int64_t IntegerValue = 0;
2984 bool IsIntegerValue = true;
2985
2986 // RISC-V attributes have a string value if the tag number is odd
2987 // and an integer value if the tag number is even.
2988 if (Tag % 2)
2989 IsIntegerValue = false;
2990
2991 SMLoc ValueExprLoc = Parser.getTok().getLoc();
2992 if (IsIntegerValue) {
2993 const MCExpr *ValueExpr;
2994 if (Parser.parseExpression(ValueExpr))
2995 return true;
2996
2997 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
2998 if (!CE)
2999 return Error(ValueExprLoc, "expected numeric constant");
3000 IntegerValue = CE->getValue();
3001 } else {
3002 if (Parser.getTok().isNot(AsmToken::String))
3003 return Error(Parser.getTok().getLoc(), "expected string constant");
3004
3005 StringValue = Parser.getTok().getStringContents();
3006 Parser.Lex();
3007 }
3008
3009 if (Parser.parseEOL())
3010 return true;
3011
3012 if (IsIntegerValue)
3013 getTargetStreamer().emitAttribute(Tag, IntegerValue);
3014 else if (Tag != RISCVAttrs::ARCH)
3015 getTargetStreamer().emitTextAttribute(Tag, StringValue);
3016 else {
3017 std::string Result;
3018 if (resetToArch(StringValue, ValueExprLoc, Result, false))
3019 return true;
3020
3021 // Then emit the arch string.
3022 getTargetStreamer().emitTextAttribute(Tag, Result);
3023 }
3024
3025 return false;
3026}
3027
3028bool isValidInsnFormat(StringRef Format, bool AllowC) {
3029 return StringSwitch<bool>(Format)
3030 .Cases("r", "r4", "i", "b", "sb", "u", "j", "uj", "s", true)
3031 .Cases("cr", "ci", "ciw", "css", "cl", "cs", "ca", "cb", "cj", AllowC)
3032 .Default(false);
3033}
3034
3035/// parseDirectiveInsn
3036/// ::= .insn [ format encoding, (operands (, operands)*) ]
3037bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
3038 MCAsmParser &Parser = getParser();
3039
3040 // Expect instruction format as identifier.
3042 SMLoc ErrorLoc = Parser.getTok().getLoc();
3043 if (Parser.parseIdentifier(Format))
3044 return Error(ErrorLoc, "expected instruction format");
3045
3046 bool AllowC = getSTI().hasFeature(RISCV::FeatureStdExtC) ||
3047 getSTI().hasFeature(RISCV::FeatureStdExtZca);
3048 if (!isValidInsnFormat(Format, AllowC))
3049 return Error(ErrorLoc, "invalid instruction format");
3050
3051 std::string FormatName = (".insn_" + Format).str();
3052
3055
3056 if (ParseInstruction(Info, FormatName, L, Operands))
3057 return true;
3058
3059 unsigned Opcode;
3061 return MatchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
3062 ErrorInfo,
3063 /*MatchingInlineAsm=*/false);
3064}
3065
3066/// parseDirectiveVariantCC
3067/// ::= .variant_cc symbol
3068bool RISCVAsmParser::parseDirectiveVariantCC() {
3070 if (getParser().parseIdentifier(Name))
3071 return TokError("expected symbol name");
3072 if (parseEOL())
3073 return true;
3074 getTargetStreamer().emitDirectiveVariantCC(
3075 *getContext().getOrCreateSymbol(Name));
3076 return false;
3077}
3078
3079void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
3080 MCInst CInst;
3081 bool Res = RISCVRVC::compress(CInst, Inst, getSTI());
3082 if (Res)
3083 ++RISCVNumInstrsCompressed;
3084 S.emitInstruction((Res ? CInst : Inst), getSTI());
3085}
3086
3087void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
3088 MCStreamer &Out) {
3090 RISCVMatInt::generateMCInstSeq(Value, getSTI(), DestReg, Seq);
3091
3092 for (MCInst &Inst : Seq) {
3093 emitToStreamer(Out, Inst);
3094 }
3095}
3096
3097void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
3098 const MCExpr *Symbol,
3100 unsigned SecondOpcode, SMLoc IDLoc,
3101 MCStreamer &Out) {
3102 // A pair of instructions for PC-relative addressing; expands to
3103 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3104 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3105 MCContext &Ctx = getContext();
3106
3107 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
3108 Out.emitLabel(TmpLabel);
3109
3110 const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
3111 emitToStreamer(
3112 Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
3113
3114 const MCExpr *RefToLinkTmpLabel =
3117
3118 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3119 .addOperand(DestReg)
3120 .addOperand(TmpReg)
3121 .addExpr(RefToLinkTmpLabel));
3122}
3123
3124void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3125 MCStreamer &Out) {
3126 // The load local address pseudo-instruction "lla" is used in PC-relative
3127 // addressing of local symbols:
3128 // lla rdest, symbol
3129 // expands to
3130 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3131 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3132 MCOperand DestReg = Inst.getOperand(0);
3133 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3134 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3135 RISCV::ADDI, IDLoc, Out);
3136}
3137
3138void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3139 MCStreamer &Out) {
3140 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3141 // addressing of global symbols:
3142 // lga rdest, symbol
3143 // expands to
3144 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3145 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3146 MCOperand DestReg = Inst.getOperand(0);
3147 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3148 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3149 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_GOT_HI,
3150 SecondOpcode, IDLoc, Out);
3151}
3152
3153void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3154 MCStreamer &Out) {
3155 // The load address pseudo-instruction "la" is used in PC-relative and
3156 // GOT-indirect addressing of global symbols:
3157 // la rdest, symbol
3158 // is an alias for either (for non-PIC)
3159 // lla rdest, symbol
3160 // or (for PIC)
3161 // lga rdest, symbol
3162 if (ParserOptions.IsPicEnabled)
3163 emitLoadGlobalAddress(Inst, IDLoc, Out);
3164 else
3165 emitLoadLocalAddress(Inst, IDLoc, Out);
3166}
3167
3168void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3169 MCStreamer &Out) {
3170 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3171 // initial-exec TLS model addressing of global symbols:
3172 // la.tls.ie rdest, symbol
3173 // expands to
3174 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3175 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3176 MCOperand DestReg = Inst.getOperand(0);
3177 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3178 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3179 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
3180 SecondOpcode, IDLoc, Out);
3181}
3182
3183void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3184 MCStreamer &Out) {
3185 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3186 // global-dynamic TLS model addressing of global symbols:
3187 // la.tls.gd rdest, symbol
3188 // expands to
3189 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3190 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3191 MCOperand DestReg = Inst.getOperand(0);
3192 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3193 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
3194 RISCV::ADDI, IDLoc, Out);
3195}
3196
3197void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3198 SMLoc IDLoc, MCStreamer &Out,
3199 bool HasTmpReg) {
3200 // The load/store pseudo-instruction does a pc-relative load with
3201 // a symbol.
3202 //
3203 // The expansion looks like this
3204 //
3205 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3206 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3207 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3208 MCOperand DestReg = Inst.getOperand(DestRegOpIdx);
3209 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3210 MCOperand TmpReg = Inst.getOperand(0);
3211 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3212 emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3213 Opcode, IDLoc, Out);
3214}
3215
3216void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3217 int64_t Width, SMLoc IDLoc,
3218 MCStreamer &Out) {
3219 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3220 // amounts dependent on the XLEN.
3221 //
3222 // The expansion looks like this
3223 //
3224 // SLLI rd, rs, XLEN - Width
3225 // SR[A|R]I rd, rd, XLEN - Width
3226 MCOperand DestReg = Inst.getOperand(0);
3227 MCOperand SourceReg = Inst.getOperand(1);
3228
3229 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3230 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3231
3232 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3233
3234 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
3235 .addOperand(DestReg)
3236 .addOperand(SourceReg)
3237 .addImm(ShAmt));
3238
3239 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3240 .addOperand(DestReg)
3241 .addOperand(DestReg)
3242 .addImm(ShAmt));
3243}
3244
3245void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3246 MCStreamer &Out) {
3247 if (Inst.getNumOperands() == 3) {
3248 // unmasked va >= x
3249 //
3250 // pseudoinstruction: vmsge{u}.vx vd, va, x
3251 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3252 emitToStreamer(Out, MCInstBuilder(Opcode)
3253 .addOperand(Inst.getOperand(0))
3254 .addOperand(Inst.getOperand(1))
3255 .addOperand(Inst.getOperand(2))
3256 .addReg(RISCV::NoRegister)
3257 .setLoc(IDLoc));
3258 emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
3259 .addOperand(Inst.getOperand(0))
3260 .addOperand(Inst.getOperand(0))
3261 .addOperand(Inst.getOperand(0))
3262 .setLoc(IDLoc));
3263 } else if (Inst.getNumOperands() == 4) {
3264 // masked va >= x, vd != v0
3265 //
3266 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3267 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3268 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3269 "The destination register should not be V0.");
3270 emitToStreamer(Out, MCInstBuilder(Opcode)
3271 .addOperand(Inst.getOperand(0))
3272 .addOperand(Inst.getOperand(1))
3273 .addOperand(Inst.getOperand(2))
3274 .addOperand(Inst.getOperand(3))
3275 .setLoc(IDLoc));
3276 emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
3277 .addOperand(Inst.getOperand(0))
3278 .addOperand(Inst.getOperand(0))
3279 .addReg(RISCV::V0)
3280 .setLoc(IDLoc));
3281 } else if (Inst.getNumOperands() == 5 &&
3282 Inst.getOperand(0).getReg() == RISCV::V0) {
3283 // masked va >= x, vd == v0
3284 //
3285 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3286 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3287 assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
3288 "The destination register should be V0.");
3289 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3290 "The temporary vector register should not be V0.");
3291 emitToStreamer(Out, MCInstBuilder(Opcode)
3292 .addOperand(Inst.getOperand(1))
3293 .addOperand(Inst.getOperand(2))
3294 .addOperand(Inst.getOperand(3))
3295 .addReg(RISCV::NoRegister)
3296 .setLoc(IDLoc));
3297 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3298 .addOperand(Inst.getOperand(0))
3299 .addOperand(Inst.getOperand(0))
3300 .addOperand(Inst.getOperand(1))
3301 .setLoc(IDLoc));
3302 } else if (Inst.getNumOperands() == 5) {
3303 // masked va >= x, any vd
3304 //
3305 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3306 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3307 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3308 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3309 "The temporary vector register should not be V0.");
3310 emitToStreamer(Out, MCInstBuilder(Opcode)
3311 .addOperand(Inst.getOperand(1))
3312 .addOperand(Inst.getOperand(2))
3313 .addOperand(Inst.getOperand(3))
3314 .addReg(RISCV::NoRegister)
3315 .setLoc(IDLoc));
3316 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3317 .addOperand(Inst.getOperand(1))
3318 .addReg(RISCV::V0)
3319 .addOperand(Inst.getOperand(1))
3320 .setLoc(IDLoc));
3321 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3322 .addOperand(Inst.getOperand(0))
3323 .addOperand(Inst.getOperand(0))
3324 .addReg(RISCV::V0)
3325 .setLoc(IDLoc));
3326 emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
3327 .addOperand(Inst.getOperand(0))
3328 .addOperand(Inst.getOperand(1))
3329 .addOperand(Inst.getOperand(0))
3330 .setLoc(IDLoc));
3331 }
3332}
3333
3334bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3336 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3337 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3338 if (Inst.getOperand(2).getReg() != RISCV::X4) {
3339 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3340 return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
3341 "%tprel_add modifier");
3342 }
3343
3344 return false;
3345}
3346
3347bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3349 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3350 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3351 if (Inst.getOperand(0).getReg() != RISCV::X5) {
3352 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3353 return Error(ErrorLoc, "the output operand must be t0/x5 when using "
3354 "%tlsdesc_call modifier");
3355 }
3356
3357 return false;
3358}
3359
3360std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3361 return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
3362 llvm::SMLoc());
3363}
3364
3365std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3366 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
3367 llvm::SMLoc());
3368}
3369
3370std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3371 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
3372 llvm::SMLoc());
3373}
3374
3375bool RISCVAsmParser::validateInstruction(MCInst &Inst,
3377 unsigned Opcode = Inst.getOpcode();
3378
3379 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
3380 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
3381 unsigned DestReg = Inst.getOperand(0).getReg();
3382 unsigned TempReg = Inst.getOperand(1).getReg();
3383 if (DestReg == TempReg) {
3384 SMLoc Loc = Operands.back()->getStartLoc();
3385 return Error(Loc, "The temporary vector register cannot be the same as "
3386 "the destination register.");
3387 }
3388 }
3389
3390 if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
3391 Opcode == RISCV::TH_LWD) {
3392 unsigned Rd1 = Inst.getOperand(0).getReg();
3393 unsigned Rd2 = Inst.getOperand(1).getReg();
3394 unsigned Rs1 = Inst.getOperand(2).getReg();
3395 // The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
3396 if (Rs1 == Rd1 && Rs1 == Rd2) {
3397 SMLoc Loc = Operands[1]->getStartLoc();
3398 return Error(Loc, "The source register and destination registers "
3399 "cannot be equal.");
3400 }
3401 }
3402
3403 if (Opcode == RISCV::CM_MVSA01) {
3404 unsigned Rd1 = Inst.getOperand(0).getReg();
3405 unsigned Rd2 = Inst.getOperand(1).getReg();
3406 if (Rd1 == Rd2) {
3407 SMLoc Loc = Operands[1]->getStartLoc();
3408 return Error(Loc, "'rs1' and 'rs2' must be different.");
3409 }
3410 }
3411
3412 bool IsTHeadMemPair32 = (Opcode == RISCV::TH_LWD ||
3413 Opcode == RISCV::TH_LWUD || Opcode == RISCV::TH_SWD);
3414 bool IsTHeadMemPair64 = (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_SDD);
3415 // The last operand of XTHeadMemPair instructions must be constant 3 or 4
3416 // depending on the data width.
3417 if (IsTHeadMemPair32 && Inst.getOperand(4).getImm() != 3) {
3418 SMLoc Loc = Operands.back()->getStartLoc();
3419 return Error(Loc, "Operand must be constant 3.");
3420 } else if (IsTHeadMemPair64 && Inst.getOperand(4).getImm() != 4) {
3421 SMLoc Loc = Operands.back()->getStartLoc();
3422 return Error(Loc, "Operand must be constant 4.");
3423 }
3424
3425 const MCInstrDesc &MCID = MII.get(Opcode);
3426 if (!(MCID.TSFlags & RISCVII::ConstraintMask))
3427 return false;
3428
3429 if (Opcode == RISCV::VC_V_XVW || Opcode == RISCV::VC_V_IVW ||
3430 Opcode == RISCV::VC_V_FVW || Opcode == RISCV::VC_V_VVW) {
3431 // Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for VC_V_XVW.
3432 unsigned VCIXDst = Inst.getOperand(0).getReg();
3433 SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
3434 if (MCID.TSFlags & RISCVII::VS1Constraint) {
3435 unsigned VCIXRs1 = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3436 if (VCIXDst == VCIXRs1)
3437 return Error(VCIXDstLoc, "The destination vector register group cannot"
3438 " overlap the source vector register group.");
3439 }
3440 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3441 unsigned VCIXRs2 = Inst.getOperand(Inst.getNumOperands() - 2).getReg();
3442 if (VCIXDst == VCIXRs2)
3443 return Error(VCIXDstLoc, "The destination vector register group cannot"
3444 " overlap the source vector register group.");
3445 }
3446 return false;
3447 }
3448
3449 unsigned DestReg = Inst.getOperand(0).getReg();
3450 unsigned Offset = 0;
3451 int TiedOp = MCID.getOperandConstraint(1, MCOI::TIED_TO);
3452 if (TiedOp == 0)
3453 Offset = 1;
3454
3455 // Operands[1] will be the first operand, DestReg.
3456 SMLoc Loc = Operands[1]->getStartLoc();
3457 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3458 unsigned CheckReg = Inst.getOperand(Offset + 1).getReg();
3459 if (DestReg == CheckReg)
3460 return Error(Loc, "The destination vector register group cannot overlap"
3461 " the source vector register group.");
3462 }
3463 if ((MCID.TSFlags & RISCVII::VS1Constraint) && Inst.getOperand(Offset + 2).isReg()) {
3464 unsigned CheckReg = Inst.getOperand(Offset + 2).getReg();
3465 if (DestReg == CheckReg)
3466 return Error(Loc, "The destination vector register group cannot overlap"
3467 " the source vector register group.");
3468 }
3469 if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
3470 // vadc, vsbc are special cases. These instructions have no mask register.
3471 // The destination register could not be V0.
3472 if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
3473 Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
3474 Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
3475 Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
3476 Opcode == RISCV::VMERGE_VXM)
3477 return Error(Loc, "The destination vector register group cannot be V0.");
3478
3479 // Regardless masked or unmasked version, the number of operands is the
3480 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
3481 // actually. We need to check the last operand to ensure whether it is
3482 // masked or not.
3483 unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3484 assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
3485 "Unexpected register for mask operand");
3486
3487 if (DestReg == CheckReg)
3488 return Error(Loc, "The destination vector register group cannot overlap"
3489 " the mask register.");
3490 }
3491 return false;
3492}
3493
3494bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
3496 MCStreamer &Out) {
3497 Inst.setLoc(IDLoc);
3498
3499 switch (Inst.getOpcode()) {
3500 default:
3501 break;
3502 case RISCV::PseudoLLAImm:
3503 case RISCV::PseudoLAImm:
3504 case RISCV::PseudoLI: {
3505 MCRegister Reg = Inst.getOperand(0).getReg();
3506 const MCOperand &Op1 = Inst.getOperand(1);
3507 if (Op1.isExpr()) {
3508 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
3509 // Just convert to an addi. This allows compatibility with gas.
3510 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
3511 .addReg(Reg)
3512 .addReg(RISCV::X0)
3513 .addExpr(Op1.getExpr()));
3514 return false;
3515 }
3516 int64_t Imm = Inst.getOperand(1).getImm();
3517 // On RV32 the immediate here can either be a signed or an unsigned
3518 // 32-bit number. Sign extension has to be performed to ensure that Imm
3519 // represents the expected signed 64-bit number.
3520 if (!isRV64())
3521 Imm = SignExtend64<32>(Imm);
3522 emitLoadImm(Reg, Imm, Out);
3523 return false;
3524 }
3525 case RISCV::PseudoLLA:
3526 emitLoadLocalAddress(Inst, IDLoc, Out);
3527 return false;
3528 case RISCV::PseudoLGA:
3529 emitLoadGlobalAddress(Inst, IDLoc, Out);
3530 return false;
3531 case RISCV::PseudoLA:
3532 emitLoadAddress(Inst, IDLoc, Out);
3533 return false;
3534 case RISCV::PseudoLA_TLS_IE:
3535 emitLoadTLSIEAddress(Inst, IDLoc, Out);
3536 return false;
3537 case RISCV::PseudoLA_TLS_GD:
3538 emitLoadTLSGDAddress(Inst, IDLoc, Out);
3539 return false;
3540 case RISCV::PseudoLB:
3541 emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
3542 return false;
3543 case RISCV::PseudoLBU:
3544 emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
3545 return false;
3546 case RISCV::PseudoLH:
3547 emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
3548 return false;
3549 case RISCV::PseudoLHU:
3550 emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
3551 return false;
3552 case RISCV::PseudoLW:
3553 emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
3554 return false;
3555 case RISCV::PseudoLWU:
3556 emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
3557 return false;
3558 case RISCV::PseudoLD:
3559 emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
3560 return false;
3561 case RISCV::PseudoFLH:
3562 emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
3563 return false;
3564 case RISCV::PseudoFLW:
3565 emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
3566 return false;
3567 case RISCV::PseudoFLD:
3568 emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
3569 return false;
3570 case RISCV::PseudoSB:
3571 emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
3572 return false;
3573 case RISCV::PseudoSH:
3574 emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
3575 return false;
3576 case RISCV::PseudoSW:
3577 emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
3578 return false;
3579 case RISCV::PseudoSD:
3580 emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
3581 return false;
3582 case RISCV::PseudoFSH:
3583 emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
3584 return false;
3585 case RISCV::PseudoFSW:
3586 emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
3587 return false;
3588 case RISCV::PseudoFSD:
3589 emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
3590 return false;
3591 case RISCV::PseudoAddTPRel:
3592 if (checkPseudoAddTPRel(Inst, Operands))
3593 return true;
3594 break;
3595 case RISCV::PseudoTLSDESCCall:
3596 if (checkPseudoTLSDESCCall(Inst, Operands))
3597 return true;
3598 break;
3599 case RISCV::PseudoSEXT_B:
3600 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
3601 return false;
3602 case RISCV::PseudoSEXT_H:
3603 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
3604 return false;
3605 case RISCV::PseudoZEXT_H:
3606 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
3607 return false;
3608 case RISCV::PseudoZEXT_W:
3609 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
3610 return false;
3611 case RISCV::PseudoVMSGEU_VX:
3612 case RISCV::PseudoVMSGEU_VX_M:
3613 case RISCV::PseudoVMSGEU_VX_M_T:
3614 emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
3615 return false;
3616 case RISCV::PseudoVMSGE_VX:
3617 case RISCV::PseudoVMSGE_VX_M:
3618 case RISCV::PseudoVMSGE_VX_M_T:
3619 emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
3620 return false;
3621 case RISCV::PseudoVMSGE_VI:
3622 case RISCV::PseudoVMSLT_VI: {
3623 // These instructions are signed and so is immediate so we can subtract one
3624 // and change the opcode.
3625 int64_t Imm = Inst.getOperand(2).getImm();
3626 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
3627 : RISCV::VMSLE_VI;
3628 emitToStreamer(Out, MCInstBuilder(Opc)
3629 .addOperand(Inst.getOperand(0))
3630 .addOperand(Inst.getOperand(1))
3631 .addImm(Imm - 1)
3632 .addOperand(Inst.getOperand(3))
3633 .setLoc(IDLoc));
3634 return false;
3635 }
3636 case RISCV::PseudoVMSGEU_VI:
3637 case RISCV::PseudoVMSLTU_VI: {
3638 int64_t Imm = Inst.getOperand(2).getImm();
3639 // Unsigned comparisons are tricky because the immediate is signed. If the
3640 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
3641 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
3642 // vmsne v0, v1, v1 which is always false.
3643 if (Imm == 0) {
3644 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3645 ? RISCV::VMSEQ_VV
3646 : RISCV::VMSNE_VV;
3647 emitToStreamer(Out, MCInstBuilder(Opc)
3648 .addOperand(Inst.getOperand(0))
3649 .addOperand(Inst.getOperand(1))
3650 .addOperand(Inst.getOperand(1))
3651 .addOperand(Inst.getOperand(3))
3652 .setLoc(IDLoc));
3653 } else {
3654 // Other immediate values can subtract one like signed.
3655 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3656 ? RISCV::VMSGTU_VI
3657 : RISCV::VMSLEU_VI;
3658 emitToStreamer(Out, MCInstBuilder(Opc)
3659 .addOperand(Inst.getOperand(0))
3660 .addOperand(Inst.getOperand(1))
3661 .addImm(Imm - 1)
3662 .addOperand(Inst.getOperand(3))
3663 .setLoc(IDLoc));
3664 }
3665
3666 return false;
3667 }
3668 }
3669
3670 emitToStreamer(Out, Inst);
3671 return false;
3672}
3673
3677}
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:76
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:457
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:814
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:304
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:222
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:660
#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:158
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.