blob: 7b010f54b0ba93be9ada91141cc62c8cd9aabcb3 [file] [log] [blame]
Alex Bradbury04f06d92017-08-08 14:43:36 +00001//===-- RISCVAsmParser.cpp - Parse RISCV assembly to MCInst instructions --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Alex Bradbury6758ecb2017-09-17 14:27:35 +000010#include "MCTargetDesc/RISCVBaseInfo.h"
Alex Bradbury9d3f1252017-09-28 08:26:24 +000011#include "MCTargetDesc/RISCVMCExpr.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000012#include "MCTargetDesc/RISCVMCTargetDesc.h"
Alex Bradburybca0c3c2018-05-11 17:30:28 +000013#include "MCTargetDesc/RISCVTargetStreamer.h"
Alex Bradbury4f7f0da2017-09-06 09:21:21 +000014#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/MC/MCContext.h"
17#include "llvm/MC/MCExpr.h"
18#include "llvm/MC/MCInst.h"
Alex Bradbury6a4b5442018-06-07 15:35:47 +000019#include "llvm/MC/MCInstBuilder.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000020#include "llvm/MC/MCParser/MCAsmLexer.h"
21#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000023#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000026#include "llvm/Support/Casting.h"
Alex Bradbury6a4b5442018-06-07 15:35:47 +000027#include "llvm/Support/MathExtras.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000028#include "llvm/Support/TargetRegistry.h"
29
Alex Bradbury6a4b5442018-06-07 15:35:47 +000030#include <limits>
31
Alex Bradbury04f06d92017-08-08 14:43:36 +000032using namespace llvm;
33
Sameer AbuAsalc1b0e662018-04-06 21:07:05 +000034// Include the auto-generated portion of the compress emitter.
35#define GEN_COMPRESS_INSTR
36#include "RISCVGenCompressInstEmitter.inc"
37
Alex Bradbury04f06d92017-08-08 14:43:36 +000038namespace {
39struct RISCVOperand;
40
41class RISCVAsmParser : public MCTargetAsmParser {
42 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
Alex Bradburya6e62482017-12-07 10:53:48 +000043 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
Alex Bradbury04f06d92017-08-08 14:43:36 +000044
Alex Bradburybca0c3c2018-05-11 17:30:28 +000045 RISCVTargetStreamer &getTargetStreamer() {
46 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
47 return static_cast<RISCVTargetStreamer &>(TS);
48 }
49
Alex Bradbury7bc2a952017-12-07 10:46:23 +000050 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
51 unsigned Kind) override;
52
Alex Bradbury6758ecb2017-09-17 14:27:35 +000053 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
Alex Bradbury6a4b5442018-06-07 15:35:47 +000054 int64_t Lower, int64_t Upper, Twine Msg);
Alex Bradbury6758ecb2017-09-17 14:27:35 +000055
Alex Bradbury04f06d92017-08-08 14:43:36 +000056 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
57 OperandVector &Operands, MCStreamer &Out,
58 uint64_t &ErrorInfo,
59 bool MatchingInlineAsm) override;
60
61 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
62
63 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
64 SMLoc NameLoc, OperandVector &Operands) override;
65
66 bool ParseDirective(AsmToken DirectiveID) override;
67
Alex Bradbury6a4b5442018-06-07 15:35:47 +000068 // Helper to actually emit an instruction to the MCStreamer. Also, when
69 // possible, compression of the instruction is performed.
70 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
71
72 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
73 // synthesize the desired immedate value into the destination register.
74 void emitLoadImm(unsigned DestReg, int64_t Value, MCStreamer &Out);
75
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +000076 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
77 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
78
Alex Bradbury6a4b5442018-06-07 15:35:47 +000079 /// Helper for processing MC instructions that have been successfully matched
80 /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
81 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
82 /// in this method.
83 bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
84
Alex Bradbury04f06d92017-08-08 14:43:36 +000085// Auto-generated instruction matching functions
86#define GET_ASSEMBLER_HEADER
87#include "RISCVGenAsmMatcher.inc"
88
89 OperandMatchResultTy parseImmediate(OperandVector &Operands);
Alex Bradbury8c345c52017-11-09 15:00:03 +000090 OperandMatchResultTy parseRegister(OperandVector &Operands,
91 bool AllowParens = false);
Alex Bradbury6758ecb2017-09-17 14:27:35 +000092 OperandMatchResultTy parseMemOpBaseReg(OperandVector &Operands);
Alex Bradbury9d3f1252017-09-28 08:26:24 +000093 OperandMatchResultTy parseOperandWithModifier(OperandVector &Operands);
Alex Bradbury04f06d92017-08-08 14:43:36 +000094
Alex Bradburycd8688a2018-04-25 17:25:29 +000095 bool parseOperand(OperandVector &Operands, bool ForceImmediate);
Alex Bradbury04f06d92017-08-08 14:43:36 +000096
Alex Bradburybca0c3c2018-05-11 17:30:28 +000097 bool parseDirectiveOption();
98
99 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
100 if (!(getSTI().getFeatureBits()[Feature])) {
101 MCSubtargetInfo &STI = copySTI();
102 setAvailableFeatures(
103 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
104 }
105 }
106
107 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
108 if (getSTI().getFeatureBits()[Feature]) {
109 MCSubtargetInfo &STI = copySTI();
110 setAvailableFeatures(
111 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
112 }
113 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000114public:
115 enum RISCVMatchResultTy {
116 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
117#define GET_OPERAND_DIAGNOSTIC_TYPES
118#include "RISCVGenAsmMatcher.inc"
119#undef GET_OPERAND_DIAGNOSTIC_TYPES
120 };
121
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000122 static bool classifySymbolRef(const MCExpr *Expr,
123 RISCVMCExpr::VariantKind &Kind,
124 int64_t &Addend);
125
Alex Bradbury04f06d92017-08-08 14:43:36 +0000126 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
127 const MCInstrInfo &MII, const MCTargetOptions &Options)
Oliver Stannard4191b9e2017-10-11 09:17:43 +0000128 : MCTargetAsmParser(Options, STI, MII) {
Alex Bradburycea6db02018-05-17 05:58:08 +0000129 Parser.addAliasForDirective(".half", ".2byte");
130 Parser.addAliasForDirective(".hword", ".2byte");
131 Parser.addAliasForDirective(".word", ".4byte");
132 Parser.addAliasForDirective(".dword", ".8byte");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000133 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
134 }
135};
136
137/// RISCVOperand - Instances of this class represent a parsed machine
138/// instruction
139struct RISCVOperand : public MCParsedAsmOperand {
140
141 enum KindTy {
142 Token,
143 Register,
144 Immediate,
145 } Kind;
146
Alex Bradburya6e62482017-12-07 10:53:48 +0000147 bool IsRV64;
148
Alex Bradbury04f06d92017-08-08 14:43:36 +0000149 struct RegOp {
150 unsigned RegNum;
151 };
152
153 struct ImmOp {
154 const MCExpr *Val;
155 };
156
157 SMLoc StartLoc, EndLoc;
158 union {
159 StringRef Tok;
160 RegOp Reg;
161 ImmOp Imm;
162 };
163
164 RISCVOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
165
166public:
167 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
168 Kind = o.Kind;
Alex Bradburya6e62482017-12-07 10:53:48 +0000169 IsRV64 = o.IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000170 StartLoc = o.StartLoc;
171 EndLoc = o.EndLoc;
172 switch (Kind) {
173 case Register:
174 Reg = o.Reg;
175 break;
176 case Immediate:
177 Imm = o.Imm;
178 break;
179 case Token:
180 Tok = o.Tok;
181 break;
182 }
183 }
184
185 bool isToken() const override { return Kind == Token; }
186 bool isReg() const override { return Kind == Register; }
187 bool isImm() const override { return Kind == Immediate; }
188 bool isMem() const override { return false; }
189
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000190 bool evaluateConstantImm(int64_t &Imm, RISCVMCExpr::VariantKind &VK) const {
191 const MCExpr *Val = getImm();
192 bool Ret = false;
193 if (auto *RE = dyn_cast<RISCVMCExpr>(Val)) {
194 Ret = RE->evaluateAsConstant(Imm);
195 VK = RE->getKind();
196 } else if (auto CE = dyn_cast<MCConstantExpr>(Val)) {
197 Ret = true;
198 VK = RISCVMCExpr::VK_RISCV_None;
199 Imm = CE->getValue();
200 }
201 return Ret;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000202 }
203
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000204 // True if operand is a symbol with no modifiers, or a constant with no
205 // modifiers and isShiftedInt<N-1, 1>(Op).
206 template <int N> bool isBareSimmNLsb0() const {
207 int64_t Imm;
208 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000209 if (!isImm())
210 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000211 bool IsConstantImm = evaluateConstantImm(Imm, VK);
212 bool IsValid;
213 if (!IsConstantImm)
214 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
215 else
216 IsValid = isShiftedInt<N - 1, 1>(Imm);
217 return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000218 }
219
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000220 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
221
Shiva Chen98f93892018-04-25 14:18:55 +0000222 bool isBareSymbol() const {
223 int64_t Imm;
224 RISCVMCExpr::VariantKind VK;
225 // Must be of 'immediate' type but not a constant.
226 if (!isImm() || evaluateConstantImm(Imm, VK))
227 return false;
228 return RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm) &&
229 VK == RISCVMCExpr::VK_RISCV_None;
230 }
231
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000232 /// Return true if the operand is a valid for the fence instruction e.g.
233 /// ('iorw').
234 bool isFenceArg() const {
235 if (!isImm())
236 return false;
237 const MCExpr *Val = getImm();
238 auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
239 if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
240 return false;
241
242 StringRef Str = SVal->getSymbol().getName();
243 // Letters must be unique, taken from 'iorw', and in ascending order. This
244 // holds as long as each individual character is one of 'iorw' and is
245 // greater than the previous character.
246 char Prev = '\0';
247 for (char c : Str) {
248 if (c != 'i' && c != 'o' && c != 'r' && c != 'w')
249 return false;
250 if (c <= Prev)
251 return false;
252 Prev = c;
253 }
254 return true;
255 }
256
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000257 /// Return true if the operand is a valid floating point rounding mode.
258 bool isFRMArg() const {
259 if (!isImm())
260 return false;
261 const MCExpr *Val = getImm();
262 auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
263 if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
264 return false;
265
266 StringRef Str = SVal->getSymbol().getName();
267
268 return RISCVFPRndMode::stringToRoundingMode(Str) != RISCVFPRndMode::Invalid;
269 }
270
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000271 bool isImmXLen() const {
272 int64_t Imm;
273 RISCVMCExpr::VariantKind VK;
274 if (!isImm())
275 return false;
276 bool IsConstantImm = evaluateConstantImm(Imm, VK);
277 // Given only Imm, ensuring that the actually specified constant is either
278 // a signed or unsigned 64-bit number is unfortunately impossible.
279 bool IsInRange = isRV64() ? true : isInt<32>(Imm) || isUInt<32>(Imm);
280 return IsConstantImm && IsInRange && VK == RISCVMCExpr::VK_RISCV_None;
281 }
282
Alex Bradburya6e62482017-12-07 10:53:48 +0000283 bool isUImmLog2XLen() const {
284 int64_t Imm;
285 RISCVMCExpr::VariantKind VK;
286 if (!isImm())
287 return false;
288 if (!evaluateConstantImm(Imm, VK) || VK != RISCVMCExpr::VK_RISCV_None)
289 return false;
290 return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
291 }
292
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000293 bool isUImmLog2XLenNonZero() const {
294 int64_t Imm;
295 RISCVMCExpr::VariantKind VK;
296 if (!isImm())
297 return false;
298 if (!evaluateConstantImm(Imm, VK) || VK != RISCVMCExpr::VK_RISCV_None)
299 return false;
300 if (Imm == 0)
301 return false;
302 return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
303 }
304
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000305 bool isUImm5() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000306 int64_t Imm;
307 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000308 if (!isImm())
309 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000310 bool IsConstantImm = evaluateConstantImm(Imm, VK);
311 return IsConstantImm && isUInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000312 }
313
Alex Bradbury60714f92017-12-13 09:32:55 +0000314 bool isUImm5NonZero() const {
315 int64_t Imm;
316 RISCVMCExpr::VariantKind VK;
317 if (!isImm())
318 return false;
319 bool IsConstantImm = evaluateConstantImm(Imm, VK);
320 return IsConstantImm && isUInt<5>(Imm) && (Imm != 0) &&
321 VK == RISCVMCExpr::VK_RISCV_None;
322 }
323
Alex Bradbury581d6b02017-12-13 09:41:21 +0000324 bool isSImm6() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000325 if (!isImm())
326 return false;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000327 RISCVMCExpr::VariantKind VK;
328 int64_t Imm;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000329 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Ana Pazos065b0882018-09-13 18:37:23 +0000330 return IsConstantImm && isInt<6>(Imm) &&
331 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000332 }
333
Shiva Chenb22c1d22018-02-02 02:43:23 +0000334 bool isSImm6NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000335 if (!isImm())
336 return false;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000337 RISCVMCExpr::VariantKind VK;
338 int64_t Imm;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000339 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Ana Pazos065b0882018-09-13 18:37:23 +0000340 return IsConstantImm && isInt<6>(Imm) && (Imm != 0) &&
341 VK == RISCVMCExpr::VK_RISCV_None;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000342 }
343
Shiva Chen7c172422018-02-22 15:02:28 +0000344 bool isCLUIImm() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000345 if (!isImm())
346 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000347 int64_t Imm;
348 RISCVMCExpr::VariantKind VK;
349 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chen7c172422018-02-22 15:02:28 +0000350 return IsConstantImm && (Imm != 0) &&
351 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
352 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury60714f92017-12-13 09:32:55 +0000353 }
354
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000355 bool isUImm7Lsb00() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000356 if (!isImm())
357 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000358 int64_t Imm;
359 RISCVMCExpr::VariantKind VK;
360 bool IsConstantImm = evaluateConstantImm(Imm, VK);
361 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
362 VK == RISCVMCExpr::VK_RISCV_None;
363 }
364
365 bool isUImm8Lsb00() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000366 if (!isImm())
367 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000368 int64_t Imm;
369 RISCVMCExpr::VariantKind VK;
370 bool IsConstantImm = evaluateConstantImm(Imm, VK);
371 return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
372 VK == RISCVMCExpr::VK_RISCV_None;
373 }
374
375 bool isUImm8Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000376 if (!isImm())
377 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000378 int64_t Imm;
379 RISCVMCExpr::VariantKind VK;
380 bool IsConstantImm = evaluateConstantImm(Imm, VK);
381 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
382 VK == RISCVMCExpr::VK_RISCV_None;
383 }
384
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000385 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
386
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000387 bool isUImm9Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000388 if (!isImm())
389 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000390 int64_t Imm;
391 RISCVMCExpr::VariantKind VK;
392 bool IsConstantImm = evaluateConstantImm(Imm, VK);
393 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
394 VK == RISCVMCExpr::VK_RISCV_None;
395 }
396
Alex Bradbury60714f92017-12-13 09:32:55 +0000397 bool isUImm10Lsb00NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000398 if (!isImm())
399 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000400 int64_t Imm;
401 RISCVMCExpr::VariantKind VK;
402 bool IsConstantImm = evaluateConstantImm(Imm, VK);
403 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
404 VK == RISCVMCExpr::VK_RISCV_None;
405 }
406
Alex Bradbury04f06d92017-08-08 14:43:36 +0000407 bool isSImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000408 RISCVMCExpr::VariantKind VK;
409 int64_t Imm;
410 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000411 if (!isImm())
412 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000413 bool IsConstantImm = evaluateConstantImm(Imm, VK);
414 if (!IsConstantImm)
415 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
416 else
417 IsValid = isInt<12>(Imm);
Ahmed Charles646ab872018-02-06 00:55:23 +0000418 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
419 VK == RISCVMCExpr::VK_RISCV_LO ||
420 VK == RISCVMCExpr::VK_RISCV_PCREL_LO);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000421 }
422
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000423 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
424
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000425 bool isUImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000426 int64_t Imm;
427 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000428 if (!isImm())
429 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000430 bool IsConstantImm = evaluateConstantImm(Imm, VK);
431 return IsConstantImm && isUInt<12>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000432 }
433
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000434 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000435
Shiva Chenb22c1d22018-02-02 02:43:23 +0000436 bool isSImm10Lsb0000NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000437 if (!isImm())
438 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000439 int64_t Imm;
440 RISCVMCExpr::VariantKind VK;
441 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000442 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
Alex Bradbury60714f92017-12-13 09:32:55 +0000443 VK == RISCVMCExpr::VK_RISCV_None;
444 }
445
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000446 bool isUImm20() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000447 RISCVMCExpr::VariantKind VK;
448 int64_t Imm;
449 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000450 if (!isImm())
451 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000452 bool IsConstantImm = evaluateConstantImm(Imm, VK);
453 if (!IsConstantImm)
454 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
455 else
456 IsValid = isUInt<20>(Imm);
457 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
458 VK == RISCVMCExpr::VK_RISCV_HI ||
459 VK == RISCVMCExpr::VK_RISCV_PCREL_HI);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000460 }
461
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000462 bool isSImm21Lsb0() const { return isBareSimmNLsb0<21>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000463
Alex Bradbury04f06d92017-08-08 14:43:36 +0000464 /// getStartLoc - Gets location of the first token of this operand
465 SMLoc getStartLoc() const override { return StartLoc; }
466 /// getEndLoc - Gets location of the last token of this operand
467 SMLoc getEndLoc() const override { return EndLoc; }
Alex Bradburya6e62482017-12-07 10:53:48 +0000468 /// True if this operand is for an RV64 instruction
469 bool isRV64() const { return IsRV64; }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000470
471 unsigned getReg() const override {
472 assert(Kind == Register && "Invalid type access!");
473 return Reg.RegNum;
474 }
475
476 const MCExpr *getImm() const {
477 assert(Kind == Immediate && "Invalid type access!");
478 return Imm.Val;
479 }
480
481 StringRef getToken() const {
482 assert(Kind == Token && "Invalid type access!");
483 return Tok;
484 }
485
486 void print(raw_ostream &OS) const override {
487 switch (Kind) {
488 case Immediate:
489 OS << *getImm();
490 break;
491 case Register:
492 OS << "<register x";
493 OS << getReg() << ">";
494 break;
495 case Token:
496 OS << "'" << getToken() << "'";
497 break;
498 }
499 }
500
Alex Bradburya6e62482017-12-07 10:53:48 +0000501 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
502 bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000503 auto Op = make_unique<RISCVOperand>(Token);
504 Op->Tok = Str;
505 Op->StartLoc = S;
506 Op->EndLoc = S;
Alex Bradburya6e62482017-12-07 10:53:48 +0000507 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000508 return Op;
509 }
510
511 static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000512 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000513 auto Op = make_unique<RISCVOperand>(Register);
514 Op->Reg.RegNum = RegNo;
515 Op->StartLoc = S;
516 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000517 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000518 return Op;
519 }
520
521 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000522 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000523 auto Op = make_unique<RISCVOperand>(Immediate);
524 Op->Imm.Val = Val;
525 Op->StartLoc = S;
526 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000527 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000528 return Op;
529 }
530
531 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
532 assert(Expr && "Expr shouldn't be null!");
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000533 int64_t Imm = 0;
534 bool IsConstant = false;
535 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
536 IsConstant = RE->evaluateAsConstant(Imm);
537 } else if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
538 IsConstant = true;
539 Imm = CE->getValue();
540 }
541
542 if (IsConstant)
543 Inst.addOperand(MCOperand::createImm(Imm));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000544 else
545 Inst.addOperand(MCOperand::createExpr(Expr));
546 }
547
548 // Used by the TableGen Code
549 void addRegOperands(MCInst &Inst, unsigned N) const {
550 assert(N == 1 && "Invalid number of operands!");
551 Inst.addOperand(MCOperand::createReg(getReg()));
552 }
553
554 void addImmOperands(MCInst &Inst, unsigned N) const {
555 assert(N == 1 && "Invalid number of operands!");
556 addExpr(Inst, getImm());
557 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000558
559 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
560 assert(N == 1 && "Invalid number of operands!");
561 // isFenceArg has validated the operand, meaning this cast is safe
562 auto SE = cast<MCSymbolRefExpr>(getImm());
563
564 unsigned Imm = 0;
565 for (char c : SE->getSymbol().getName()) {
566 switch (c) {
567 default: llvm_unreachable("FenceArg must contain only [iorw]");
568 case 'i': Imm |= RISCVFenceField::I; break;
569 case 'o': Imm |= RISCVFenceField::O; break;
570 case 'r': Imm |= RISCVFenceField::R; break;
571 case 'w': Imm |= RISCVFenceField::W; break;
572 }
573 }
574 Inst.addOperand(MCOperand::createImm(Imm));
575 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000576
577 // Returns the rounding mode represented by this RISCVOperand. Should only
578 // be called after checking isFRMArg.
579 RISCVFPRndMode::RoundingMode getRoundingMode() const {
580 // isFRMArg has validated the operand, meaning this cast is safe.
581 auto SE = cast<MCSymbolRefExpr>(getImm());
582 RISCVFPRndMode::RoundingMode FRM =
583 RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
584 assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
585 return FRM;
586 }
587
588 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
589 assert(N == 1 && "Invalid number of operands!");
590 Inst.addOperand(MCOperand::createImm(getRoundingMode()));
591 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000592};
593} // end anonymous namespace.
594
595#define GET_REGISTER_MATCHER
596#define GET_MATCHER_IMPLEMENTATION
Alex Bradbury04f06d92017-08-08 14:43:36 +0000597#include "RISCVGenAsmMatcher.inc"
598
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000599// Return the matching FPR64 register for the given FPR32.
600// FIXME: Ideally this function could be removed in favour of using
601// information from TableGen.
602unsigned convertFPR32ToFPR64(unsigned Reg) {
603 switch (Reg) {
604 default:
605 llvm_unreachable("Not a recognised FPR32 register");
606 case RISCV::F0_32: return RISCV::F0_64;
607 case RISCV::F1_32: return RISCV::F1_64;
608 case RISCV::F2_32: return RISCV::F2_64;
609 case RISCV::F3_32: return RISCV::F3_64;
610 case RISCV::F4_32: return RISCV::F4_64;
611 case RISCV::F5_32: return RISCV::F5_64;
612 case RISCV::F6_32: return RISCV::F6_64;
613 case RISCV::F7_32: return RISCV::F7_64;
614 case RISCV::F8_32: return RISCV::F8_64;
615 case RISCV::F9_32: return RISCV::F9_64;
616 case RISCV::F10_32: return RISCV::F10_64;
617 case RISCV::F11_32: return RISCV::F11_64;
618 case RISCV::F12_32: return RISCV::F12_64;
619 case RISCV::F13_32: return RISCV::F13_64;
620 case RISCV::F14_32: return RISCV::F14_64;
621 case RISCV::F15_32: return RISCV::F15_64;
622 case RISCV::F16_32: return RISCV::F16_64;
623 case RISCV::F17_32: return RISCV::F17_64;
624 case RISCV::F18_32: return RISCV::F18_64;
625 case RISCV::F19_32: return RISCV::F19_64;
626 case RISCV::F20_32: return RISCV::F20_64;
627 case RISCV::F21_32: return RISCV::F21_64;
628 case RISCV::F22_32: return RISCV::F22_64;
629 case RISCV::F23_32: return RISCV::F23_64;
630 case RISCV::F24_32: return RISCV::F24_64;
631 case RISCV::F25_32: return RISCV::F25_64;
632 case RISCV::F26_32: return RISCV::F26_64;
633 case RISCV::F27_32: return RISCV::F27_64;
634 case RISCV::F28_32: return RISCV::F28_64;
635 case RISCV::F29_32: return RISCV::F29_64;
636 case RISCV::F30_32: return RISCV::F30_64;
637 case RISCV::F31_32: return RISCV::F31_64;
638 }
639}
640
641unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
642 unsigned Kind) {
643 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
644 if (!Op.isReg())
645 return Match_InvalidOperand;
646
647 unsigned Reg = Op.getReg();
648 bool IsRegFPR32 =
649 RISCVMCRegisterClasses[RISCV::FPR32RegClassID].contains(Reg);
Alex Bradbury60714f92017-12-13 09:32:55 +0000650 bool IsRegFPR32C =
651 RISCVMCRegisterClasses[RISCV::FPR32CRegClassID].contains(Reg);
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000652
653 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
Alex Bradbury60714f92017-12-13 09:32:55 +0000654 // register from FPR32 to FPR64 or FPR32C to FPR64C if necessary.
655 if ((IsRegFPR32 && Kind == MCK_FPR64) ||
656 (IsRegFPR32C && Kind == MCK_FPR64C)) {
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000657 Op.Reg.RegNum = convertFPR32ToFPR64(Reg);
658 return Match_Success;
659 }
660 return Match_InvalidOperand;
661}
662
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000663bool RISCVAsmParser::generateImmOutOfRangeError(
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000664 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000665 Twine Msg = "immediate must be an integer in the range") {
666 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
667 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
668}
669
Alex Bradbury04f06d92017-08-08 14:43:36 +0000670bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
671 OperandVector &Operands,
672 MCStreamer &Out,
673 uint64_t &ErrorInfo,
674 bool MatchingInlineAsm) {
675 MCInst Inst;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000676
Ana Pazos6b34051b2018-08-30 19:43:19 +0000677 auto Result =
678 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
679 switch (Result) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000680 default:
681 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000682 case Match_Success:
683 return processInstruction(Inst, IDLoc, Out);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000684 case Match_MissingFeature:
685 return Error(IDLoc, "instruction use requires an option to be enabled");
686 case Match_MnemonicFail:
687 return Error(IDLoc, "unrecognized instruction mnemonic");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000688 case Match_InvalidOperand: {
689 SMLoc ErrorLoc = IDLoc;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000690 if (ErrorInfo != ~0U) {
691 if (ErrorInfo >= Operands.size())
692 return Error(ErrorLoc, "too few operands for instruction");
693
694 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
695 if (ErrorLoc == SMLoc())
696 ErrorLoc = IDLoc;
697 }
698 return Error(ErrorLoc, "invalid operand for instruction");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000699 }
Ana Pazos6b34051b2018-08-30 19:43:19 +0000700 }
701
702 // Handle the case when the error message is of specific type
703 // other than the generic Match_InvalidOperand, and the
704 // corresponding operand is missing.
705 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
706 SMLoc ErrorLoc = IDLoc;
707 if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
708 return Error(ErrorLoc, "too few operands for instruction");
709 }
710
711 switch(Result) {
712 default:
713 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000714 case Match_InvalidImmXLen:
715 if (isRV64()) {
716 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
717 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
718 }
719 return generateImmOutOfRangeError(Operands, ErrorInfo,
720 std::numeric_limits<int32_t>::min(),
721 std::numeric_limits<uint32_t>::max());
Alex Bradburya6e62482017-12-07 10:53:48 +0000722 case Match_InvalidUImmLog2XLen:
723 if (isRV64())
724 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
725 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000726 case Match_InvalidUImmLog2XLenNonZero:
727 if (isRV64())
728 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
729 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000730 case Match_InvalidUImm5:
731 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury581d6b02017-12-13 09:41:21 +0000732 case Match_InvalidSImm6:
733 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
734 (1 << 5) - 1);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000735 case Match_InvalidSImm6NonZero:
736 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
737 (1 << 5) - 1,
738 "immediate must be non-zero in the range");
Shiva Chen7c172422018-02-22 15:02:28 +0000739 case Match_InvalidCLUIImm:
740 return generateImmOutOfRangeError(
741 Operands, ErrorInfo, 1, (1 << 5) - 1,
742 "immediate must be in [0xfffe0, 0xfffff] or");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000743 case Match_InvalidUImm7Lsb00:
744 return generateImmOutOfRangeError(
745 Operands, ErrorInfo, 0, (1 << 7) - 4,
746 "immediate must be a multiple of 4 bytes in the range");
747 case Match_InvalidUImm8Lsb00:
748 return generateImmOutOfRangeError(
749 Operands, ErrorInfo, 0, (1 << 8) - 4,
750 "immediate must be a multiple of 4 bytes in the range");
751 case Match_InvalidUImm8Lsb000:
752 return generateImmOutOfRangeError(
753 Operands, ErrorInfo, 0, (1 << 8) - 8,
754 "immediate must be a multiple of 8 bytes in the range");
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000755 case Match_InvalidSImm9Lsb0:
756 return generateImmOutOfRangeError(
757 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
758 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000759 case Match_InvalidUImm9Lsb000:
760 return generateImmOutOfRangeError(
761 Operands, ErrorInfo, 0, (1 << 9) - 8,
762 "immediate must be a multiple of 8 bytes in the range");
Alex Bradbury60714f92017-12-13 09:32:55 +0000763 case Match_InvalidUImm10Lsb00NonZero:
764 return generateImmOutOfRangeError(
765 Operands, ErrorInfo, 4, (1 << 10) - 4,
766 "immediate must be a multiple of 4 bytes in the range");
Shiva Chenb22c1d22018-02-02 02:43:23 +0000767 case Match_InvalidSImm10Lsb0000NonZero:
Alex Bradbury60714f92017-12-13 09:32:55 +0000768 return generateImmOutOfRangeError(
769 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
Shiva Chenb22c1d22018-02-02 02:43:23 +0000770 "immediate must be a multiple of 16 bytes and non-zero in the range");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000771 case Match_InvalidSImm12:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000772 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 11),
773 (1 << 11) - 1);
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000774 case Match_InvalidSImm12Lsb0:
775 return generateImmOutOfRangeError(
776 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
777 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000778 case Match_InvalidUImm12:
779 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1);
780 case Match_InvalidSImm13Lsb0:
781 return generateImmOutOfRangeError(
782 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
783 "immediate must be a multiple of 2 bytes in the range");
784 case Match_InvalidUImm20:
785 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
786 case Match_InvalidSImm21Lsb0:
787 return generateImmOutOfRangeError(
788 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
789 "immediate must be a multiple of 2 bytes in the range");
790 case Match_InvalidFenceArg: {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000791 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000792 return Error(
793 ErrorLoc,
794 "operand must be formed of letters selected in-order from 'iorw'");
795 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000796 case Match_InvalidFRMArg: {
797 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
798 return Error(
799 ErrorLoc,
800 "operand must be a valid floating point rounding mode mnemonic");
801 }
Shiva Chen98f93892018-04-25 14:18:55 +0000802 case Match_InvalidBareSymbol: {
803 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
804 return Error(ErrorLoc, "operand must be a bare symbol name");
805 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000806 }
807
808 llvm_unreachable("Unknown match type detected!");
809}
810
811bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
812 SMLoc &EndLoc) {
813 const AsmToken &Tok = getParser().getTok();
814 StartLoc = Tok.getLoc();
815 EndLoc = Tok.getEndLoc();
816 RegNo = 0;
817 StringRef Name = getLexer().getTok().getIdentifier();
818
819 if (!MatchRegisterName(Name) || !MatchRegisterAltName(Name)) {
820 getParser().Lex(); // Eat identifier token.
821 return false;
822 }
823
824 return Error(StartLoc, "invalid register name");
825}
826
Alex Bradbury8c345c52017-11-09 15:00:03 +0000827OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
828 bool AllowParens) {
829 SMLoc FirstS = getLoc();
830 bool HadParens = false;
831 AsmToken Buf[2];
832
833 // If this a parenthesised register name is allowed, parse it atomically
834 if (AllowParens && getLexer().is(AsmToken::LParen)) {
835 size_t ReadCount = getLexer().peekTokens(Buf);
836 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
837 HadParens = true;
838 getParser().Lex(); // Eat '('
839 }
840 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000841
842 switch (getLexer().getKind()) {
843 default:
844 return MatchOperand_NoMatch;
845 case AsmToken::Identifier:
846 StringRef Name = getLexer().getTok().getIdentifier();
847 unsigned RegNo = MatchRegisterName(Name);
848 if (RegNo == 0) {
849 RegNo = MatchRegisterAltName(Name);
Alex Bradbury8c345c52017-11-09 15:00:03 +0000850 if (RegNo == 0) {
851 if (HadParens)
852 getLexer().UnLex(Buf[0]);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000853 return MatchOperand_NoMatch;
Alex Bradbury8c345c52017-11-09 15:00:03 +0000854 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000855 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000856 if (HadParens)
Alex Bradburya6e62482017-12-07 10:53:48 +0000857 Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000858 SMLoc S = getLoc();
859 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000860 getLexer().Lex();
Alex Bradburya6e62482017-12-07 10:53:48 +0000861 Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000862 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000863
864 if (HadParens) {
865 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000866 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000867 }
868
Alex Bradbury04f06d92017-08-08 14:43:36 +0000869 return MatchOperand_Success;
870}
871
872OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000873 SMLoc S = getLoc();
874 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
875 const MCExpr *Res;
876
Alex Bradbury04f06d92017-08-08 14:43:36 +0000877 switch (getLexer().getKind()) {
878 default:
879 return MatchOperand_NoMatch;
880 case AsmToken::LParen:
881 case AsmToken::Minus:
882 case AsmToken::Plus:
883 case AsmToken::Integer:
884 case AsmToken::String:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000885 if (getParser().parseExpression(Res))
886 return MatchOperand_ParseFail;
887 break;
888 case AsmToken::Identifier: {
889 StringRef Identifier;
890 if (getParser().parseIdentifier(Identifier))
891 return MatchOperand_ParseFail;
892 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
893 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Alex Bradbury04f06d92017-08-08 14:43:36 +0000894 break;
895 }
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000896 case AsmToken::Percent:
897 return parseOperandWithModifier(Operands);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000898 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000899
Alex Bradburya6e62482017-12-07 10:53:48 +0000900 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000901 return MatchOperand_Success;
902}
903
904OperandMatchResultTy
905RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
906 SMLoc S = getLoc();
907 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
908
909 if (getLexer().getKind() != AsmToken::Percent) {
910 Error(getLoc(), "expected '%' for operand modifier");
911 return MatchOperand_ParseFail;
912 }
913
914 getParser().Lex(); // Eat '%'
915
916 if (getLexer().getKind() != AsmToken::Identifier) {
917 Error(getLoc(), "expected valid identifier for operand modifier");
918 return MatchOperand_ParseFail;
919 }
920 StringRef Identifier = getParser().getTok().getIdentifier();
921 RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
922 if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
923 Error(getLoc(), "unrecognized operand modifier");
924 return MatchOperand_ParseFail;
925 }
926
927 getParser().Lex(); // Eat the identifier
928 if (getLexer().getKind() != AsmToken::LParen) {
929 Error(getLoc(), "expected '('");
930 return MatchOperand_ParseFail;
931 }
932 getParser().Lex(); // Eat '('
933
934 const MCExpr *SubExpr;
935 if (getParser().parseParenExpression(SubExpr, E)) {
936 return MatchOperand_ParseFail;
937 }
938
939 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
Alex Bradburya6e62482017-12-07 10:53:48 +0000940 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000941 return MatchOperand_Success;
942}
943
944OperandMatchResultTy
945RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
946 if (getLexer().isNot(AsmToken::LParen)) {
947 Error(getLoc(), "expected '('");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000948 return MatchOperand_ParseFail;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000949 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000950
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000951 getParser().Lex(); // Eat '('
Alex Bradburya6e62482017-12-07 10:53:48 +0000952 Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000953
954 if (parseRegister(Operands) != MatchOperand_Success) {
955 Error(getLoc(), "expected register");
956 return MatchOperand_ParseFail;
957 }
958
959 if (getLexer().isNot(AsmToken::RParen)) {
960 Error(getLoc(), "expected ')'");
961 return MatchOperand_ParseFail;
962 }
963
964 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000965 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000966
Alex Bradbury04f06d92017-08-08 14:43:36 +0000967 return MatchOperand_Success;
968}
969
Alex Bradburycd8688a2018-04-25 17:25:29 +0000970/// Looks at a token type and creates the relevant operand from this
971/// information, adding to Operands. If operand was parsed, returns false, else
972/// true. If ForceImmediate is true, no attempt will be made to parse the
973/// operand as a register, which is needed for pseudoinstructions such as
974/// call.
975bool RISCVAsmParser::parseOperand(OperandVector &Operands,
976 bool ForceImmediate) {
977 // Attempt to parse token as register, unless ForceImmediate.
978 if (!ForceImmediate && parseRegister(Operands, true) == MatchOperand_Success)
Alex Bradbury04f06d92017-08-08 14:43:36 +0000979 return false;
980
981 // Attempt to parse token as an immediate
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000982 if (parseImmediate(Operands) == MatchOperand_Success) {
983 // Parse memory base register if present
984 if (getLexer().is(AsmToken::LParen))
985 return parseMemOpBaseReg(Operands) != MatchOperand_Success;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000986 return false;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000987 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000988
989 // Finally we have exhausted all options and must declare defeat.
990 Error(getLoc(), "unknown operand");
991 return true;
992}
993
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +0000994/// Return true if the operand at the OperandIdx for opcode Name should be
995/// 'forced' to be parsed as an immediate. This is required for
996/// pseudoinstructions such as tail or call, which allow bare symbols to be used
997/// that could clash with register names.
998static bool shouldForceImediateOperand(StringRef Name, unsigned OperandIdx) {
999 // FIXME: This may not scale so perhaps we want to use a data-driven approach
1000 // instead.
1001 switch (OperandIdx) {
1002 case 0:
1003 // call imm
1004 // tail imm
1005 return Name == "tail" || Name == "call";
1006 case 1:
1007 // lla rdest, imm
1008 return Name == "lla";
1009 default:
1010 return false;
1011 }
1012}
1013
Alex Bradbury04f06d92017-08-08 14:43:36 +00001014bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1015 StringRef Name, SMLoc NameLoc,
1016 OperandVector &Operands) {
1017 // First operand is token for instruction
Alex Bradburya6e62482017-12-07 10:53:48 +00001018 Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +00001019
1020 // If there are no more operands, then finish
1021 if (getLexer().is(AsmToken::EndOfStatement))
1022 return false;
1023
1024 // Parse first operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001025 if (parseOperand(Operands, shouldForceImediateOperand(Name, 0)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001026 return true;
1027
1028 // Parse until end of statement, consuming commas between operands
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001029 unsigned OperandIdx = 1;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001030 while (getLexer().is(AsmToken::Comma)) {
1031 // Consume comma token
1032 getLexer().Lex();
1033
1034 // Parse next operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001035 if (parseOperand(Operands, shouldForceImediateOperand(Name, OperandIdx)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001036 return true;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001037
1038 ++OperandIdx;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001039 }
1040
1041 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1042 SMLoc Loc = getLexer().getLoc();
1043 getParser().eatToEndOfStatement();
1044 return Error(Loc, "unexpected token");
1045 }
1046
1047 getParser().Lex(); // Consume the EndOfStatement.
1048 return false;
1049}
1050
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001051bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1052 RISCVMCExpr::VariantKind &Kind,
1053 int64_t &Addend) {
1054 Kind = RISCVMCExpr::VK_RISCV_None;
1055 Addend = 0;
1056
1057 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1058 Kind = RE->getKind();
1059 Expr = RE->getSubExpr();
1060 }
1061
1062 // It's a simple symbol reference or constant with no addend.
1063 if (isa<MCConstantExpr>(Expr) || isa<MCSymbolRefExpr>(Expr))
1064 return true;
1065
1066 const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
1067 if (!BE)
1068 return false;
1069
1070 if (!isa<MCSymbolRefExpr>(BE->getLHS()))
1071 return false;
1072
1073 if (BE->getOpcode() != MCBinaryExpr::Add &&
1074 BE->getOpcode() != MCBinaryExpr::Sub)
1075 return false;
1076
1077 // We are able to support the subtraction of two symbol references
1078 if (BE->getOpcode() == MCBinaryExpr::Sub &&
1079 isa<MCSymbolRefExpr>(BE->getRHS()))
1080 return true;
1081
Hiroshi Inoue9ff23802018-04-09 04:37:53 +00001082 // See if the addend is a constant, otherwise there's more going
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001083 // on here than we can deal with.
1084 auto AddendExpr = dyn_cast<MCConstantExpr>(BE->getRHS());
1085 if (!AddendExpr)
1086 return false;
1087
1088 Addend = AddendExpr->getValue();
1089 if (BE->getOpcode() == MCBinaryExpr::Sub)
1090 Addend = -Addend;
1091
1092 // It's some symbol reference + a constant addend
1093 return Kind != RISCVMCExpr::VK_RISCV_Invalid;
1094}
1095
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001096bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1097 // This returns false if this function recognizes the directive
1098 // regardless of whether it is successfully handles or reports an
1099 // error. Otherwise it returns true to give the generic parser a
1100 // chance at recognizing it.
1101 StringRef IDVal = DirectiveID.getString();
1102
1103 if (IDVal == ".option")
1104 return parseDirectiveOption();
1105
1106 return true;
1107}
1108
1109bool RISCVAsmParser::parseDirectiveOption() {
1110 MCAsmParser &Parser = getParser();
1111 // Get the option token.
1112 AsmToken Tok = Parser.getTok();
1113 // At the moment only identifiers are supported.
1114 if (Tok.isNot(AsmToken::Identifier))
1115 return Error(Parser.getTok().getLoc(),
1116 "unexpected token, expected identifier");
1117
1118 StringRef Option = Tok.getIdentifier();
1119
1120 if (Option == "rvc") {
1121 getTargetStreamer().emitDirectiveOptionRVC();
1122
1123 Parser.Lex();
1124 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1125 return Error(Parser.getTok().getLoc(),
1126 "unexpected token, expected end of statement");
1127
1128 setFeatureBits(RISCV::FeatureStdExtC, "c");
1129 return false;
1130 }
1131
1132 if (Option == "norvc") {
1133 getTargetStreamer().emitDirectiveOptionNoRVC();
1134
1135 Parser.Lex();
1136 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1137 return Error(Parser.getTok().getLoc(),
1138 "unexpected token, expected end of statement");
1139
1140 clearFeatureBits(RISCV::FeatureStdExtC, "c");
1141 return false;
1142 }
1143
1144 // Unknown option.
1145 Warning(Parser.getTok().getLoc(),
1146 "unknown option, expected 'rvc' or 'norvc'");
1147 Parser.eatToEndOfStatement();
1148 return false;
1149}
Alex Bradbury04f06d92017-08-08 14:43:36 +00001150
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001151void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
1152 MCInst CInst;
1153 bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
1154 CInst.setLoc(Inst.getLoc());
1155 S.EmitInstruction((Res ? CInst : Inst), getSTI());
1156}
1157
1158void RISCVAsmParser::emitLoadImm(unsigned DestReg, int64_t Value,
1159 MCStreamer &Out) {
1160 if (isInt<32>(Value)) {
1161 // Emits the MC instructions for loading a 32-bit constant into a register.
1162 //
1163 // Depending on the active bits in the immediate Value v, the following
1164 // instruction sequences are emitted:
1165 //
1166 // v == 0 : ADDI(W)
1167 // v[0,12) != 0 && v[12,32) == 0 : ADDI(W)
1168 // v[0,12) == 0 && v[12,32) != 0 : LUI
1169 // v[0,32) != 0 : LUI+ADDI(W)
1170 //
1171 int64_t Hi20 = ((Value + 0x800) >> 12) & 0xFFFFF;
1172 int64_t Lo12 = SignExtend64<12>(Value);
1173 unsigned SrcReg = RISCV::X0;
1174
1175 if (Hi20) {
1176 emitToStreamer(Out,
1177 MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Hi20));
1178 SrcReg = DestReg;
1179 }
1180
1181 if (Lo12 || Hi20 == 0) {
1182 unsigned AddiOpcode =
1183 STI->hasFeature(RISCV::Feature64Bit) ? RISCV::ADDIW : RISCV::ADDI;
1184 emitToStreamer(Out, MCInstBuilder(AddiOpcode)
1185 .addReg(DestReg)
1186 .addReg(SrcReg)
1187 .addImm(Lo12));
1188 }
1189 return;
1190 }
1191 assert(STI->hasFeature(RISCV::Feature64Bit) &&
1192 "Target must be 64-bit to support a >32-bit constant");
1193
1194 // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
1195 // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emmitted. Note
1196 // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
1197 // while the following ADDI instructions contribute up to 12 bits each.
1198 //
1199 // On the first glance, implementing this seems to be possible by simply
1200 // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
1201 // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
1202 // fact that ADDI performs a sign extended addition, doing it like that would
1203 // only be possible when at most 11 bits of the ADDI instructions are used.
1204 // Using all 12 bits of the ADDI instructions, like done by GAS, actually
1205 // requires that the constant is processed starting with the least significant
1206 // bit.
1207 //
1208 // In the following, constants are processed from LSB to MSB but instruction
1209 // emission is performed from MSB to LSB by recursively calling
1210 // emitLoadImm. In each recursion, first the lowest 12 bits are removed
1211 // from the constant and the optimal shift amount, which can be greater than
1212 // 12 bits if the constant is sparse, is determined. Then, the shifted
1213 // remaining constant is processed recursively and gets emitted as soon as it
1214 // fits into 32 bits. The emission of the shifts and additions is subsequently
1215 // performed when the recursion returns.
1216 //
1217 int64_t Lo12 = SignExtend64<12>(Value);
1218 int64_t Hi52 = (Value + 0x800) >> 12;
1219 int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
1220 Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
1221
1222 emitLoadImm(DestReg, Hi52, Out);
1223
1224 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
1225 .addReg(DestReg)
1226 .addReg(DestReg)
1227 .addImm(ShiftAmount));
1228
1229 if (Lo12)
1230 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1231 .addReg(DestReg)
1232 .addReg(DestReg)
1233 .addImm(Lo12));
1234}
1235
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001236void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
1237 MCStreamer &Out) {
1238 // The local load address pseudo-instruction "lla" is used in PC-relative
1239 // addressing of symbols:
1240 // lla rdest, symbol
1241 // expands to
1242 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1243 // ADDI rdest, %pcrel_lo(TmpLabel)
1244 MCContext &Ctx = getContext();
1245
1246 MCSymbol *TmpLabel = Ctx.createTempSymbol(
1247 "pcrel_hi", /* AlwaysAddSuffix */ true, /* CanBeUnnamed */ false);
1248 Out.EmitLabel(TmpLabel);
1249
1250 MCOperand DestReg = Inst.getOperand(0);
1251 const RISCVMCExpr *Symbol = RISCVMCExpr::create(
1252 Inst.getOperand(1).getExpr(), RISCVMCExpr::VK_RISCV_PCREL_HI, Ctx);
1253
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001254 emitToStreamer(
1255 Out, MCInstBuilder(RISCV::AUIPC).addOperand(DestReg).addExpr(Symbol));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001256
1257 const MCExpr *RefToLinkTmpLabel =
1258 RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
1259 RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
1260
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001261 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1262 .addOperand(DestReg)
1263 .addOperand(DestReg)
1264 .addExpr(RefToLinkTmpLabel));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001265}
1266
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001267bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1268 MCStreamer &Out) {
1269 Inst.setLoc(IDLoc);
1270
1271 if (Inst.getOpcode() == RISCV::PseudoLI) {
1272 auto Reg = Inst.getOperand(0).getReg();
1273 int64_t Imm = Inst.getOperand(1).getImm();
1274 // On RV32 the immediate here can either be a signed or an unsigned
1275 // 32-bit number. Sign extension has to be performed to ensure that Imm
1276 // represents the expected signed 64-bit number.
1277 if (!isRV64())
1278 Imm = SignExtend64<32>(Imm);
1279 emitLoadImm(Reg, Imm, Out);
1280 return false;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001281 } else if (Inst.getOpcode() == RISCV::PseudoLLA) {
1282 emitLoadLocalAddress(Inst, IDLoc, Out);
1283 return false;
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001284 }
1285
1286 emitToStreamer(Out, Inst);
1287 return false;
1288}
1289
Alex Bradbury04f06d92017-08-08 14:43:36 +00001290extern "C" void LLVMInitializeRISCVAsmParser() {
1291 RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
1292 RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
1293}