blob: 3e469c89369ab2969ce02506152058e17dc41aa3 [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;
329 bool IsValid;
330 bool IsConstantImm = evaluateConstantImm(Imm, VK);
331 if (!IsConstantImm)
332 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
333 else
334 IsValid = isInt<6>(Imm);
335 return IsValid &&
336 (VK == RISCVMCExpr::VK_RISCV_None || VK == RISCVMCExpr::VK_RISCV_LO);
337 }
338
Shiva Chenb22c1d22018-02-02 02:43:23 +0000339 bool isSImm6NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000340 if (!isImm())
341 return false;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000342 RISCVMCExpr::VariantKind VK;
343 int64_t Imm;
344 bool IsValid;
345 bool IsConstantImm = evaluateConstantImm(Imm, VK);
346 if (!IsConstantImm)
347 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
348 else
349 IsValid = ((Imm != 0) && isInt<6>(Imm));
350 return IsValid &&
351 (VK == RISCVMCExpr::VK_RISCV_None || VK == RISCVMCExpr::VK_RISCV_LO);
352 }
353
Shiva Chen7c172422018-02-22 15:02:28 +0000354 bool isCLUIImm() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000355 if (!isImm())
356 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000357 int64_t Imm;
358 RISCVMCExpr::VariantKind VK;
359 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chen7c172422018-02-22 15:02:28 +0000360 return IsConstantImm && (Imm != 0) &&
361 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
362 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury60714f92017-12-13 09:32:55 +0000363 }
364
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000365 bool isUImm7Lsb00() 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<5, 2>(Imm) &&
372 VK == RISCVMCExpr::VK_RISCV_None;
373 }
374
375 bool isUImm8Lsb00() 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<6, 2>(Imm) &&
382 VK == RISCVMCExpr::VK_RISCV_None;
383 }
384
385 bool isUImm8Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000386 if (!isImm())
387 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000388 int64_t Imm;
389 RISCVMCExpr::VariantKind VK;
390 bool IsConstantImm = evaluateConstantImm(Imm, VK);
391 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
392 VK == RISCVMCExpr::VK_RISCV_None;
393 }
394
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000395 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
396
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000397 bool isUImm9Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000398 if (!isImm())
399 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000400 int64_t Imm;
401 RISCVMCExpr::VariantKind VK;
402 bool IsConstantImm = evaluateConstantImm(Imm, VK);
403 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
404 VK == RISCVMCExpr::VK_RISCV_None;
405 }
406
Alex Bradbury60714f92017-12-13 09:32:55 +0000407 bool isUImm10Lsb00NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000408 if (!isImm())
409 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000410 int64_t Imm;
411 RISCVMCExpr::VariantKind VK;
412 bool IsConstantImm = evaluateConstantImm(Imm, VK);
413 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
414 VK == RISCVMCExpr::VK_RISCV_None;
415 }
416
Alex Bradbury04f06d92017-08-08 14:43:36 +0000417 bool isSImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000418 RISCVMCExpr::VariantKind VK;
419 int64_t Imm;
420 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000421 if (!isImm())
422 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000423 bool IsConstantImm = evaluateConstantImm(Imm, VK);
424 if (!IsConstantImm)
425 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
426 else
427 IsValid = isInt<12>(Imm);
Ahmed Charles646ab872018-02-06 00:55:23 +0000428 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
429 VK == RISCVMCExpr::VK_RISCV_LO ||
430 VK == RISCVMCExpr::VK_RISCV_PCREL_LO);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000431 }
432
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000433 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
434
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000435 bool isUImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000436 int64_t Imm;
437 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000438 if (!isImm())
439 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000440 bool IsConstantImm = evaluateConstantImm(Imm, VK);
441 return IsConstantImm && isUInt<12>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000442 }
443
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000444 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000445
Shiva Chenb22c1d22018-02-02 02:43:23 +0000446 bool isSImm10Lsb0000NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000447 if (!isImm())
448 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000449 int64_t Imm;
450 RISCVMCExpr::VariantKind VK;
451 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000452 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
Alex Bradbury60714f92017-12-13 09:32:55 +0000453 VK == RISCVMCExpr::VK_RISCV_None;
454 }
455
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000456 bool isUImm20() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000457 RISCVMCExpr::VariantKind VK;
458 int64_t Imm;
459 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000460 if (!isImm())
461 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000462 bool IsConstantImm = evaluateConstantImm(Imm, VK);
463 if (!IsConstantImm)
464 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
465 else
466 IsValid = isUInt<20>(Imm);
467 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
468 VK == RISCVMCExpr::VK_RISCV_HI ||
469 VK == RISCVMCExpr::VK_RISCV_PCREL_HI);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000470 }
471
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000472 bool isSImm21Lsb0() const { return isBareSimmNLsb0<21>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000473
Alex Bradbury04f06d92017-08-08 14:43:36 +0000474 /// getStartLoc - Gets location of the first token of this operand
475 SMLoc getStartLoc() const override { return StartLoc; }
476 /// getEndLoc - Gets location of the last token of this operand
477 SMLoc getEndLoc() const override { return EndLoc; }
Alex Bradburya6e62482017-12-07 10:53:48 +0000478 /// True if this operand is for an RV64 instruction
479 bool isRV64() const { return IsRV64; }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000480
481 unsigned getReg() const override {
482 assert(Kind == Register && "Invalid type access!");
483 return Reg.RegNum;
484 }
485
486 const MCExpr *getImm() const {
487 assert(Kind == Immediate && "Invalid type access!");
488 return Imm.Val;
489 }
490
491 StringRef getToken() const {
492 assert(Kind == Token && "Invalid type access!");
493 return Tok;
494 }
495
496 void print(raw_ostream &OS) const override {
497 switch (Kind) {
498 case Immediate:
499 OS << *getImm();
500 break;
501 case Register:
502 OS << "<register x";
503 OS << getReg() << ">";
504 break;
505 case Token:
506 OS << "'" << getToken() << "'";
507 break;
508 }
509 }
510
Alex Bradburya6e62482017-12-07 10:53:48 +0000511 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
512 bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000513 auto Op = make_unique<RISCVOperand>(Token);
514 Op->Tok = Str;
515 Op->StartLoc = S;
516 Op->EndLoc = S;
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> createReg(unsigned RegNo, 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>(Register);
524 Op->Reg.RegNum = RegNo;
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 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000532 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000533 auto Op = make_unique<RISCVOperand>(Immediate);
534 Op->Imm.Val = Val;
535 Op->StartLoc = S;
536 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000537 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000538 return Op;
539 }
540
541 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
542 assert(Expr && "Expr shouldn't be null!");
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000543 int64_t Imm = 0;
544 bool IsConstant = false;
545 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
546 IsConstant = RE->evaluateAsConstant(Imm);
547 } else if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
548 IsConstant = true;
549 Imm = CE->getValue();
550 }
551
552 if (IsConstant)
553 Inst.addOperand(MCOperand::createImm(Imm));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000554 else
555 Inst.addOperand(MCOperand::createExpr(Expr));
556 }
557
558 // Used by the TableGen Code
559 void addRegOperands(MCInst &Inst, unsigned N) const {
560 assert(N == 1 && "Invalid number of operands!");
561 Inst.addOperand(MCOperand::createReg(getReg()));
562 }
563
564 void addImmOperands(MCInst &Inst, unsigned N) const {
565 assert(N == 1 && "Invalid number of operands!");
566 addExpr(Inst, getImm());
567 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000568
569 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
570 assert(N == 1 && "Invalid number of operands!");
571 // isFenceArg has validated the operand, meaning this cast is safe
572 auto SE = cast<MCSymbolRefExpr>(getImm());
573
574 unsigned Imm = 0;
575 for (char c : SE->getSymbol().getName()) {
576 switch (c) {
577 default: llvm_unreachable("FenceArg must contain only [iorw]");
578 case 'i': Imm |= RISCVFenceField::I; break;
579 case 'o': Imm |= RISCVFenceField::O; break;
580 case 'r': Imm |= RISCVFenceField::R; break;
581 case 'w': Imm |= RISCVFenceField::W; break;
582 }
583 }
584 Inst.addOperand(MCOperand::createImm(Imm));
585 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000586
587 // Returns the rounding mode represented by this RISCVOperand. Should only
588 // be called after checking isFRMArg.
589 RISCVFPRndMode::RoundingMode getRoundingMode() const {
590 // isFRMArg has validated the operand, meaning this cast is safe.
591 auto SE = cast<MCSymbolRefExpr>(getImm());
592 RISCVFPRndMode::RoundingMode FRM =
593 RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
594 assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
595 return FRM;
596 }
597
598 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
599 assert(N == 1 && "Invalid number of operands!");
600 Inst.addOperand(MCOperand::createImm(getRoundingMode()));
601 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000602};
603} // end anonymous namespace.
604
605#define GET_REGISTER_MATCHER
606#define GET_MATCHER_IMPLEMENTATION
Alex Bradbury04f06d92017-08-08 14:43:36 +0000607#include "RISCVGenAsmMatcher.inc"
608
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000609// Return the matching FPR64 register for the given FPR32.
610// FIXME: Ideally this function could be removed in favour of using
611// information from TableGen.
612unsigned convertFPR32ToFPR64(unsigned Reg) {
613 switch (Reg) {
614 default:
615 llvm_unreachable("Not a recognised FPR32 register");
616 case RISCV::F0_32: return RISCV::F0_64;
617 case RISCV::F1_32: return RISCV::F1_64;
618 case RISCV::F2_32: return RISCV::F2_64;
619 case RISCV::F3_32: return RISCV::F3_64;
620 case RISCV::F4_32: return RISCV::F4_64;
621 case RISCV::F5_32: return RISCV::F5_64;
622 case RISCV::F6_32: return RISCV::F6_64;
623 case RISCV::F7_32: return RISCV::F7_64;
624 case RISCV::F8_32: return RISCV::F8_64;
625 case RISCV::F9_32: return RISCV::F9_64;
626 case RISCV::F10_32: return RISCV::F10_64;
627 case RISCV::F11_32: return RISCV::F11_64;
628 case RISCV::F12_32: return RISCV::F12_64;
629 case RISCV::F13_32: return RISCV::F13_64;
630 case RISCV::F14_32: return RISCV::F14_64;
631 case RISCV::F15_32: return RISCV::F15_64;
632 case RISCV::F16_32: return RISCV::F16_64;
633 case RISCV::F17_32: return RISCV::F17_64;
634 case RISCV::F18_32: return RISCV::F18_64;
635 case RISCV::F19_32: return RISCV::F19_64;
636 case RISCV::F20_32: return RISCV::F20_64;
637 case RISCV::F21_32: return RISCV::F21_64;
638 case RISCV::F22_32: return RISCV::F22_64;
639 case RISCV::F23_32: return RISCV::F23_64;
640 case RISCV::F24_32: return RISCV::F24_64;
641 case RISCV::F25_32: return RISCV::F25_64;
642 case RISCV::F26_32: return RISCV::F26_64;
643 case RISCV::F27_32: return RISCV::F27_64;
644 case RISCV::F28_32: return RISCV::F28_64;
645 case RISCV::F29_32: return RISCV::F29_64;
646 case RISCV::F30_32: return RISCV::F30_64;
647 case RISCV::F31_32: return RISCV::F31_64;
648 }
649}
650
651unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
652 unsigned Kind) {
653 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
654 if (!Op.isReg())
655 return Match_InvalidOperand;
656
657 unsigned Reg = Op.getReg();
658 bool IsRegFPR32 =
659 RISCVMCRegisterClasses[RISCV::FPR32RegClassID].contains(Reg);
Alex Bradbury60714f92017-12-13 09:32:55 +0000660 bool IsRegFPR32C =
661 RISCVMCRegisterClasses[RISCV::FPR32CRegClassID].contains(Reg);
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000662
663 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
Alex Bradbury60714f92017-12-13 09:32:55 +0000664 // register from FPR32 to FPR64 or FPR32C to FPR64C if necessary.
665 if ((IsRegFPR32 && Kind == MCK_FPR64) ||
666 (IsRegFPR32C && Kind == MCK_FPR64C)) {
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000667 Op.Reg.RegNum = convertFPR32ToFPR64(Reg);
668 return Match_Success;
669 }
670 return Match_InvalidOperand;
671}
672
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000673bool RISCVAsmParser::generateImmOutOfRangeError(
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000674 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000675 Twine Msg = "immediate must be an integer in the range") {
676 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
677 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
678}
679
Alex Bradbury04f06d92017-08-08 14:43:36 +0000680bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
681 OperandVector &Operands,
682 MCStreamer &Out,
683 uint64_t &ErrorInfo,
684 bool MatchingInlineAsm) {
685 MCInst Inst;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000686
Ana Pazos6b34051b2018-08-30 19:43:19 +0000687 auto Result =
688 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
689 switch (Result) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000690 default:
691 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000692 case Match_Success:
693 return processInstruction(Inst, IDLoc, Out);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000694 case Match_MissingFeature:
695 return Error(IDLoc, "instruction use requires an option to be enabled");
696 case Match_MnemonicFail:
697 return Error(IDLoc, "unrecognized instruction mnemonic");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000698 case Match_InvalidOperand: {
699 SMLoc ErrorLoc = IDLoc;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000700 if (ErrorInfo != ~0U) {
701 if (ErrorInfo >= Operands.size())
702 return Error(ErrorLoc, "too few operands for instruction");
703
704 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
705 if (ErrorLoc == SMLoc())
706 ErrorLoc = IDLoc;
707 }
708 return Error(ErrorLoc, "invalid operand for instruction");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000709 }
Ana Pazos6b34051b2018-08-30 19:43:19 +0000710 }
711
712 // Handle the case when the error message is of specific type
713 // other than the generic Match_InvalidOperand, and the
714 // corresponding operand is missing.
715 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
716 SMLoc ErrorLoc = IDLoc;
717 if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
718 return Error(ErrorLoc, "too few operands for instruction");
719 }
720
721 switch(Result) {
722 default:
723 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000724 case Match_InvalidImmXLen:
725 if (isRV64()) {
726 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
727 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
728 }
729 return generateImmOutOfRangeError(Operands, ErrorInfo,
730 std::numeric_limits<int32_t>::min(),
731 std::numeric_limits<uint32_t>::max());
Alex Bradburya6e62482017-12-07 10:53:48 +0000732 case Match_InvalidUImmLog2XLen:
733 if (isRV64())
734 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
735 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000736 case Match_InvalidUImmLog2XLenNonZero:
737 if (isRV64())
738 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
739 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000740 case Match_InvalidUImm5:
741 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury581d6b02017-12-13 09:41:21 +0000742 case Match_InvalidSImm6:
743 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
744 (1 << 5) - 1);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000745 case Match_InvalidSImm6NonZero:
746 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
747 (1 << 5) - 1,
748 "immediate must be non-zero in the range");
Shiva Chen7c172422018-02-22 15:02:28 +0000749 case Match_InvalidCLUIImm:
750 return generateImmOutOfRangeError(
751 Operands, ErrorInfo, 1, (1 << 5) - 1,
752 "immediate must be in [0xfffe0, 0xfffff] or");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000753 case Match_InvalidUImm7Lsb00:
754 return generateImmOutOfRangeError(
755 Operands, ErrorInfo, 0, (1 << 7) - 4,
756 "immediate must be a multiple of 4 bytes in the range");
757 case Match_InvalidUImm8Lsb00:
758 return generateImmOutOfRangeError(
759 Operands, ErrorInfo, 0, (1 << 8) - 4,
760 "immediate must be a multiple of 4 bytes in the range");
761 case Match_InvalidUImm8Lsb000:
762 return generateImmOutOfRangeError(
763 Operands, ErrorInfo, 0, (1 << 8) - 8,
764 "immediate must be a multiple of 8 bytes in the range");
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000765 case Match_InvalidSImm9Lsb0:
766 return generateImmOutOfRangeError(
767 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
768 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000769 case Match_InvalidUImm9Lsb000:
770 return generateImmOutOfRangeError(
771 Operands, ErrorInfo, 0, (1 << 9) - 8,
772 "immediate must be a multiple of 8 bytes in the range");
Alex Bradbury60714f92017-12-13 09:32:55 +0000773 case Match_InvalidUImm10Lsb00NonZero:
774 return generateImmOutOfRangeError(
775 Operands, ErrorInfo, 4, (1 << 10) - 4,
776 "immediate must be a multiple of 4 bytes in the range");
Shiva Chenb22c1d22018-02-02 02:43:23 +0000777 case Match_InvalidSImm10Lsb0000NonZero:
Alex Bradbury60714f92017-12-13 09:32:55 +0000778 return generateImmOutOfRangeError(
779 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
Shiva Chenb22c1d22018-02-02 02:43:23 +0000780 "immediate must be a multiple of 16 bytes and non-zero in the range");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000781 case Match_InvalidSImm12:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000782 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 11),
783 (1 << 11) - 1);
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000784 case Match_InvalidSImm12Lsb0:
785 return generateImmOutOfRangeError(
786 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
787 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000788 case Match_InvalidUImm12:
789 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1);
790 case Match_InvalidSImm13Lsb0:
791 return generateImmOutOfRangeError(
792 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
793 "immediate must be a multiple of 2 bytes in the range");
794 case Match_InvalidUImm20:
795 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
796 case Match_InvalidSImm21Lsb0:
797 return generateImmOutOfRangeError(
798 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
799 "immediate must be a multiple of 2 bytes in the range");
800 case Match_InvalidFenceArg: {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000801 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000802 return Error(
803 ErrorLoc,
804 "operand must be formed of letters selected in-order from 'iorw'");
805 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000806 case Match_InvalidFRMArg: {
807 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
808 return Error(
809 ErrorLoc,
810 "operand must be a valid floating point rounding mode mnemonic");
811 }
Shiva Chen98f93892018-04-25 14:18:55 +0000812 case Match_InvalidBareSymbol: {
813 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
814 return Error(ErrorLoc, "operand must be a bare symbol name");
815 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000816 }
817
818 llvm_unreachable("Unknown match type detected!");
819}
820
821bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
822 SMLoc &EndLoc) {
823 const AsmToken &Tok = getParser().getTok();
824 StartLoc = Tok.getLoc();
825 EndLoc = Tok.getEndLoc();
826 RegNo = 0;
827 StringRef Name = getLexer().getTok().getIdentifier();
828
829 if (!MatchRegisterName(Name) || !MatchRegisterAltName(Name)) {
830 getParser().Lex(); // Eat identifier token.
831 return false;
832 }
833
834 return Error(StartLoc, "invalid register name");
835}
836
Alex Bradbury8c345c52017-11-09 15:00:03 +0000837OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
838 bool AllowParens) {
839 SMLoc FirstS = getLoc();
840 bool HadParens = false;
841 AsmToken Buf[2];
842
843 // If this a parenthesised register name is allowed, parse it atomically
844 if (AllowParens && getLexer().is(AsmToken::LParen)) {
845 size_t ReadCount = getLexer().peekTokens(Buf);
846 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
847 HadParens = true;
848 getParser().Lex(); // Eat '('
849 }
850 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000851
852 switch (getLexer().getKind()) {
853 default:
854 return MatchOperand_NoMatch;
855 case AsmToken::Identifier:
856 StringRef Name = getLexer().getTok().getIdentifier();
857 unsigned RegNo = MatchRegisterName(Name);
858 if (RegNo == 0) {
859 RegNo = MatchRegisterAltName(Name);
Alex Bradbury8c345c52017-11-09 15:00:03 +0000860 if (RegNo == 0) {
861 if (HadParens)
862 getLexer().UnLex(Buf[0]);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000863 return MatchOperand_NoMatch;
Alex Bradbury8c345c52017-11-09 15:00:03 +0000864 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000865 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000866 if (HadParens)
Alex Bradburya6e62482017-12-07 10:53:48 +0000867 Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000868 SMLoc S = getLoc();
869 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000870 getLexer().Lex();
Alex Bradburya6e62482017-12-07 10:53:48 +0000871 Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000872 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000873
874 if (HadParens) {
875 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000876 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000877 }
878
Alex Bradbury04f06d92017-08-08 14:43:36 +0000879 return MatchOperand_Success;
880}
881
882OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000883 SMLoc S = getLoc();
884 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
885 const MCExpr *Res;
886
Alex Bradbury04f06d92017-08-08 14:43:36 +0000887 switch (getLexer().getKind()) {
888 default:
889 return MatchOperand_NoMatch;
890 case AsmToken::LParen:
891 case AsmToken::Minus:
892 case AsmToken::Plus:
893 case AsmToken::Integer:
894 case AsmToken::String:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000895 if (getParser().parseExpression(Res))
896 return MatchOperand_ParseFail;
897 break;
898 case AsmToken::Identifier: {
899 StringRef Identifier;
900 if (getParser().parseIdentifier(Identifier))
901 return MatchOperand_ParseFail;
902 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
903 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Alex Bradbury04f06d92017-08-08 14:43:36 +0000904 break;
905 }
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000906 case AsmToken::Percent:
907 return parseOperandWithModifier(Operands);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000908 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000909
Alex Bradburya6e62482017-12-07 10:53:48 +0000910 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000911 return MatchOperand_Success;
912}
913
914OperandMatchResultTy
915RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
916 SMLoc S = getLoc();
917 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
918
919 if (getLexer().getKind() != AsmToken::Percent) {
920 Error(getLoc(), "expected '%' for operand modifier");
921 return MatchOperand_ParseFail;
922 }
923
924 getParser().Lex(); // Eat '%'
925
926 if (getLexer().getKind() != AsmToken::Identifier) {
927 Error(getLoc(), "expected valid identifier for operand modifier");
928 return MatchOperand_ParseFail;
929 }
930 StringRef Identifier = getParser().getTok().getIdentifier();
931 RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
932 if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
933 Error(getLoc(), "unrecognized operand modifier");
934 return MatchOperand_ParseFail;
935 }
936
937 getParser().Lex(); // Eat the identifier
938 if (getLexer().getKind() != AsmToken::LParen) {
939 Error(getLoc(), "expected '('");
940 return MatchOperand_ParseFail;
941 }
942 getParser().Lex(); // Eat '('
943
944 const MCExpr *SubExpr;
945 if (getParser().parseParenExpression(SubExpr, E)) {
946 return MatchOperand_ParseFail;
947 }
948
949 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
Alex Bradburya6e62482017-12-07 10:53:48 +0000950 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000951 return MatchOperand_Success;
952}
953
954OperandMatchResultTy
955RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
956 if (getLexer().isNot(AsmToken::LParen)) {
957 Error(getLoc(), "expected '('");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000958 return MatchOperand_ParseFail;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000959 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000960
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000961 getParser().Lex(); // Eat '('
Alex Bradburya6e62482017-12-07 10:53:48 +0000962 Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000963
964 if (parseRegister(Operands) != MatchOperand_Success) {
965 Error(getLoc(), "expected register");
966 return MatchOperand_ParseFail;
967 }
968
969 if (getLexer().isNot(AsmToken::RParen)) {
970 Error(getLoc(), "expected ')'");
971 return MatchOperand_ParseFail;
972 }
973
974 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000975 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000976
Alex Bradbury04f06d92017-08-08 14:43:36 +0000977 return MatchOperand_Success;
978}
979
Alex Bradburycd8688a2018-04-25 17:25:29 +0000980/// Looks at a token type and creates the relevant operand from this
981/// information, adding to Operands. If operand was parsed, returns false, else
982/// true. If ForceImmediate is true, no attempt will be made to parse the
983/// operand as a register, which is needed for pseudoinstructions such as
984/// call.
985bool RISCVAsmParser::parseOperand(OperandVector &Operands,
986 bool ForceImmediate) {
987 // Attempt to parse token as register, unless ForceImmediate.
988 if (!ForceImmediate && parseRegister(Operands, true) == MatchOperand_Success)
Alex Bradbury04f06d92017-08-08 14:43:36 +0000989 return false;
990
991 // Attempt to parse token as an immediate
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000992 if (parseImmediate(Operands) == MatchOperand_Success) {
993 // Parse memory base register if present
994 if (getLexer().is(AsmToken::LParen))
995 return parseMemOpBaseReg(Operands) != MatchOperand_Success;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000996 return false;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000997 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000998
999 // Finally we have exhausted all options and must declare defeat.
1000 Error(getLoc(), "unknown operand");
1001 return true;
1002}
1003
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001004/// Return true if the operand at the OperandIdx for opcode Name should be
1005/// 'forced' to be parsed as an immediate. This is required for
1006/// pseudoinstructions such as tail or call, which allow bare symbols to be used
1007/// that could clash with register names.
1008static bool shouldForceImediateOperand(StringRef Name, unsigned OperandIdx) {
1009 // FIXME: This may not scale so perhaps we want to use a data-driven approach
1010 // instead.
1011 switch (OperandIdx) {
1012 case 0:
1013 // call imm
1014 // tail imm
1015 return Name == "tail" || Name == "call";
1016 case 1:
1017 // lla rdest, imm
1018 return Name == "lla";
1019 default:
1020 return false;
1021 }
1022}
1023
Alex Bradbury04f06d92017-08-08 14:43:36 +00001024bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1025 StringRef Name, SMLoc NameLoc,
1026 OperandVector &Operands) {
1027 // First operand is token for instruction
Alex Bradburya6e62482017-12-07 10:53:48 +00001028 Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +00001029
1030 // If there are no more operands, then finish
1031 if (getLexer().is(AsmToken::EndOfStatement))
1032 return false;
1033
1034 // Parse first operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001035 if (parseOperand(Operands, shouldForceImediateOperand(Name, 0)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001036 return true;
1037
1038 // Parse until end of statement, consuming commas between operands
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001039 unsigned OperandIdx = 1;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001040 while (getLexer().is(AsmToken::Comma)) {
1041 // Consume comma token
1042 getLexer().Lex();
1043
1044 // Parse next operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001045 if (parseOperand(Operands, shouldForceImediateOperand(Name, OperandIdx)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001046 return true;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001047
1048 ++OperandIdx;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001049 }
1050
1051 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1052 SMLoc Loc = getLexer().getLoc();
1053 getParser().eatToEndOfStatement();
1054 return Error(Loc, "unexpected token");
1055 }
1056
1057 getParser().Lex(); // Consume the EndOfStatement.
1058 return false;
1059}
1060
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001061bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1062 RISCVMCExpr::VariantKind &Kind,
1063 int64_t &Addend) {
1064 Kind = RISCVMCExpr::VK_RISCV_None;
1065 Addend = 0;
1066
1067 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1068 Kind = RE->getKind();
1069 Expr = RE->getSubExpr();
1070 }
1071
1072 // It's a simple symbol reference or constant with no addend.
1073 if (isa<MCConstantExpr>(Expr) || isa<MCSymbolRefExpr>(Expr))
1074 return true;
1075
1076 const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
1077 if (!BE)
1078 return false;
1079
1080 if (!isa<MCSymbolRefExpr>(BE->getLHS()))
1081 return false;
1082
1083 if (BE->getOpcode() != MCBinaryExpr::Add &&
1084 BE->getOpcode() != MCBinaryExpr::Sub)
1085 return false;
1086
1087 // We are able to support the subtraction of two symbol references
1088 if (BE->getOpcode() == MCBinaryExpr::Sub &&
1089 isa<MCSymbolRefExpr>(BE->getRHS()))
1090 return true;
1091
Hiroshi Inoue9ff23802018-04-09 04:37:53 +00001092 // See if the addend is a constant, otherwise there's more going
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001093 // on here than we can deal with.
1094 auto AddendExpr = dyn_cast<MCConstantExpr>(BE->getRHS());
1095 if (!AddendExpr)
1096 return false;
1097
1098 Addend = AddendExpr->getValue();
1099 if (BE->getOpcode() == MCBinaryExpr::Sub)
1100 Addend = -Addend;
1101
1102 // It's some symbol reference + a constant addend
1103 return Kind != RISCVMCExpr::VK_RISCV_Invalid;
1104}
1105
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001106bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1107 // This returns false if this function recognizes the directive
1108 // regardless of whether it is successfully handles or reports an
1109 // error. Otherwise it returns true to give the generic parser a
1110 // chance at recognizing it.
1111 StringRef IDVal = DirectiveID.getString();
1112
1113 if (IDVal == ".option")
1114 return parseDirectiveOption();
1115
1116 return true;
1117}
1118
1119bool RISCVAsmParser::parseDirectiveOption() {
1120 MCAsmParser &Parser = getParser();
1121 // Get the option token.
1122 AsmToken Tok = Parser.getTok();
1123 // At the moment only identifiers are supported.
1124 if (Tok.isNot(AsmToken::Identifier))
1125 return Error(Parser.getTok().getLoc(),
1126 "unexpected token, expected identifier");
1127
1128 StringRef Option = Tok.getIdentifier();
1129
1130 if (Option == "rvc") {
1131 getTargetStreamer().emitDirectiveOptionRVC();
1132
1133 Parser.Lex();
1134 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1135 return Error(Parser.getTok().getLoc(),
1136 "unexpected token, expected end of statement");
1137
1138 setFeatureBits(RISCV::FeatureStdExtC, "c");
1139 return false;
1140 }
1141
1142 if (Option == "norvc") {
1143 getTargetStreamer().emitDirectiveOptionNoRVC();
1144
1145 Parser.Lex();
1146 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1147 return Error(Parser.getTok().getLoc(),
1148 "unexpected token, expected end of statement");
1149
1150 clearFeatureBits(RISCV::FeatureStdExtC, "c");
1151 return false;
1152 }
1153
1154 // Unknown option.
1155 Warning(Parser.getTok().getLoc(),
1156 "unknown option, expected 'rvc' or 'norvc'");
1157 Parser.eatToEndOfStatement();
1158 return false;
1159}
Alex Bradbury04f06d92017-08-08 14:43:36 +00001160
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001161void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
1162 MCInst CInst;
1163 bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
1164 CInst.setLoc(Inst.getLoc());
1165 S.EmitInstruction((Res ? CInst : Inst), getSTI());
1166}
1167
1168void RISCVAsmParser::emitLoadImm(unsigned DestReg, int64_t Value,
1169 MCStreamer &Out) {
1170 if (isInt<32>(Value)) {
1171 // Emits the MC instructions for loading a 32-bit constant into a register.
1172 //
1173 // Depending on the active bits in the immediate Value v, the following
1174 // instruction sequences are emitted:
1175 //
1176 // v == 0 : ADDI(W)
1177 // v[0,12) != 0 && v[12,32) == 0 : ADDI(W)
1178 // v[0,12) == 0 && v[12,32) != 0 : LUI
1179 // v[0,32) != 0 : LUI+ADDI(W)
1180 //
1181 int64_t Hi20 = ((Value + 0x800) >> 12) & 0xFFFFF;
1182 int64_t Lo12 = SignExtend64<12>(Value);
1183 unsigned SrcReg = RISCV::X0;
1184
1185 if (Hi20) {
1186 emitToStreamer(Out,
1187 MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Hi20));
1188 SrcReg = DestReg;
1189 }
1190
1191 if (Lo12 || Hi20 == 0) {
1192 unsigned AddiOpcode =
1193 STI->hasFeature(RISCV::Feature64Bit) ? RISCV::ADDIW : RISCV::ADDI;
1194 emitToStreamer(Out, MCInstBuilder(AddiOpcode)
1195 .addReg(DestReg)
1196 .addReg(SrcReg)
1197 .addImm(Lo12));
1198 }
1199 return;
1200 }
1201 assert(STI->hasFeature(RISCV::Feature64Bit) &&
1202 "Target must be 64-bit to support a >32-bit constant");
1203
1204 // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
1205 // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emmitted. Note
1206 // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
1207 // while the following ADDI instructions contribute up to 12 bits each.
1208 //
1209 // On the first glance, implementing this seems to be possible by simply
1210 // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
1211 // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
1212 // fact that ADDI performs a sign extended addition, doing it like that would
1213 // only be possible when at most 11 bits of the ADDI instructions are used.
1214 // Using all 12 bits of the ADDI instructions, like done by GAS, actually
1215 // requires that the constant is processed starting with the least significant
1216 // bit.
1217 //
1218 // In the following, constants are processed from LSB to MSB but instruction
1219 // emission is performed from MSB to LSB by recursively calling
1220 // emitLoadImm. In each recursion, first the lowest 12 bits are removed
1221 // from the constant and the optimal shift amount, which can be greater than
1222 // 12 bits if the constant is sparse, is determined. Then, the shifted
1223 // remaining constant is processed recursively and gets emitted as soon as it
1224 // fits into 32 bits. The emission of the shifts and additions is subsequently
1225 // performed when the recursion returns.
1226 //
1227 int64_t Lo12 = SignExtend64<12>(Value);
1228 int64_t Hi52 = (Value + 0x800) >> 12;
1229 int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
1230 Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
1231
1232 emitLoadImm(DestReg, Hi52, Out);
1233
1234 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
1235 .addReg(DestReg)
1236 .addReg(DestReg)
1237 .addImm(ShiftAmount));
1238
1239 if (Lo12)
1240 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1241 .addReg(DestReg)
1242 .addReg(DestReg)
1243 .addImm(Lo12));
1244}
1245
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001246void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
1247 MCStreamer &Out) {
1248 // The local load address pseudo-instruction "lla" is used in PC-relative
1249 // addressing of symbols:
1250 // lla rdest, symbol
1251 // expands to
1252 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1253 // ADDI rdest, %pcrel_lo(TmpLabel)
1254 MCContext &Ctx = getContext();
1255
1256 MCSymbol *TmpLabel = Ctx.createTempSymbol(
1257 "pcrel_hi", /* AlwaysAddSuffix */ true, /* CanBeUnnamed */ false);
1258 Out.EmitLabel(TmpLabel);
1259
1260 MCOperand DestReg = Inst.getOperand(0);
1261 const RISCVMCExpr *Symbol = RISCVMCExpr::create(
1262 Inst.getOperand(1).getExpr(), RISCVMCExpr::VK_RISCV_PCREL_HI, Ctx);
1263
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001264 emitToStreamer(
1265 Out, MCInstBuilder(RISCV::AUIPC).addOperand(DestReg).addExpr(Symbol));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001266
1267 const MCExpr *RefToLinkTmpLabel =
1268 RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
1269 RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
1270
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001271 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1272 .addOperand(DestReg)
1273 .addOperand(DestReg)
1274 .addExpr(RefToLinkTmpLabel));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001275}
1276
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001277bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1278 MCStreamer &Out) {
1279 Inst.setLoc(IDLoc);
1280
1281 if (Inst.getOpcode() == RISCV::PseudoLI) {
1282 auto Reg = Inst.getOperand(0).getReg();
1283 int64_t Imm = Inst.getOperand(1).getImm();
1284 // On RV32 the immediate here can either be a signed or an unsigned
1285 // 32-bit number. Sign extension has to be performed to ensure that Imm
1286 // represents the expected signed 64-bit number.
1287 if (!isRV64())
1288 Imm = SignExtend64<32>(Imm);
1289 emitLoadImm(Reg, Imm, Out);
1290 return false;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001291 } else if (Inst.getOpcode() == RISCV::PseudoLLA) {
1292 emitLoadLocalAddress(Inst, IDLoc, Out);
1293 return false;
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001294 }
1295
1296 emitToStreamer(Out, Inst);
1297 return false;
1298}
1299
Alex Bradbury04f06d92017-08-08 14:43:36 +00001300extern "C" void LLVMInitializeRISCVAsmParser() {
1301 RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
1302 RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
1303}