blob: 3a5257206bf9a401ef75b79fbac0adea6ff71658 [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 {
325 RISCVMCExpr::VariantKind VK;
326 int64_t Imm;
327 bool IsValid;
328 bool IsConstantImm = evaluateConstantImm(Imm, VK);
329 if (!IsConstantImm)
330 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
331 else
332 IsValid = isInt<6>(Imm);
333 return IsValid &&
334 (VK == RISCVMCExpr::VK_RISCV_None || VK == RISCVMCExpr::VK_RISCV_LO);
335 }
336
Shiva Chenb22c1d22018-02-02 02:43:23 +0000337 bool isSImm6NonZero() const {
338 RISCVMCExpr::VariantKind VK;
339 int64_t Imm;
340 bool IsValid;
341 bool IsConstantImm = evaluateConstantImm(Imm, VK);
342 if (!IsConstantImm)
343 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
344 else
345 IsValid = ((Imm != 0) && isInt<6>(Imm));
346 return IsValid &&
347 (VK == RISCVMCExpr::VK_RISCV_None || VK == RISCVMCExpr::VK_RISCV_LO);
348 }
349
Shiva Chen7c172422018-02-22 15:02:28 +0000350 bool isCLUIImm() const {
Alex Bradbury60714f92017-12-13 09:32:55 +0000351 int64_t Imm;
352 RISCVMCExpr::VariantKind VK;
353 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chen7c172422018-02-22 15:02:28 +0000354 return IsConstantImm && (Imm != 0) &&
355 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
356 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury60714f92017-12-13 09:32:55 +0000357 }
358
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000359 bool isUImm7Lsb00() const {
360 int64_t Imm;
361 RISCVMCExpr::VariantKind VK;
362 bool IsConstantImm = evaluateConstantImm(Imm, VK);
363 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
364 VK == RISCVMCExpr::VK_RISCV_None;
365 }
366
367 bool isUImm8Lsb00() const {
368 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 {
376 int64_t Imm;
377 RISCVMCExpr::VariantKind VK;
378 bool IsConstantImm = evaluateConstantImm(Imm, VK);
379 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
380 VK == RISCVMCExpr::VK_RISCV_None;
381 }
382
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000383 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
384
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000385 bool isUImm9Lsb000() const {
386 int64_t Imm;
387 RISCVMCExpr::VariantKind VK;
388 bool IsConstantImm = evaluateConstantImm(Imm, VK);
389 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
390 VK == RISCVMCExpr::VK_RISCV_None;
391 }
392
Alex Bradbury60714f92017-12-13 09:32:55 +0000393 bool isUImm10Lsb00NonZero() const {
394 int64_t Imm;
395 RISCVMCExpr::VariantKind VK;
396 bool IsConstantImm = evaluateConstantImm(Imm, VK);
397 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
398 VK == RISCVMCExpr::VK_RISCV_None;
399 }
400
Alex Bradbury04f06d92017-08-08 14:43:36 +0000401 bool isSImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000402 RISCVMCExpr::VariantKind VK;
403 int64_t Imm;
404 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000405 if (!isImm())
406 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000407 bool IsConstantImm = evaluateConstantImm(Imm, VK);
408 if (!IsConstantImm)
409 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
410 else
411 IsValid = isInt<12>(Imm);
Ahmed Charles646ab872018-02-06 00:55:23 +0000412 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
413 VK == RISCVMCExpr::VK_RISCV_LO ||
414 VK == RISCVMCExpr::VK_RISCV_PCREL_LO);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000415 }
416
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000417 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
418
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000419 bool isUImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000420 int64_t Imm;
421 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000422 if (!isImm())
423 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000424 bool IsConstantImm = evaluateConstantImm(Imm, VK);
425 return IsConstantImm && isUInt<12>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000426 }
427
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000428 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000429
Shiva Chenb22c1d22018-02-02 02:43:23 +0000430 bool isSImm10Lsb0000NonZero() const {
Alex Bradbury60714f92017-12-13 09:32:55 +0000431 int64_t Imm;
432 RISCVMCExpr::VariantKind VK;
433 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000434 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
Alex Bradbury60714f92017-12-13 09:32:55 +0000435 VK == RISCVMCExpr::VK_RISCV_None;
436 }
437
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000438 bool isUImm20() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000439 RISCVMCExpr::VariantKind VK;
440 int64_t Imm;
441 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000442 if (!isImm())
443 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000444 bool IsConstantImm = evaluateConstantImm(Imm, VK);
445 if (!IsConstantImm)
446 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
447 else
448 IsValid = isUInt<20>(Imm);
449 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
450 VK == RISCVMCExpr::VK_RISCV_HI ||
451 VK == RISCVMCExpr::VK_RISCV_PCREL_HI);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000452 }
453
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000454 bool isSImm21Lsb0() const { return isBareSimmNLsb0<21>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000455
Alex Bradbury04f06d92017-08-08 14:43:36 +0000456 /// getStartLoc - Gets location of the first token of this operand
457 SMLoc getStartLoc() const override { return StartLoc; }
458 /// getEndLoc - Gets location of the last token of this operand
459 SMLoc getEndLoc() const override { return EndLoc; }
Alex Bradburya6e62482017-12-07 10:53:48 +0000460 /// True if this operand is for an RV64 instruction
461 bool isRV64() const { return IsRV64; }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000462
463 unsigned getReg() const override {
464 assert(Kind == Register && "Invalid type access!");
465 return Reg.RegNum;
466 }
467
468 const MCExpr *getImm() const {
469 assert(Kind == Immediate && "Invalid type access!");
470 return Imm.Val;
471 }
472
473 StringRef getToken() const {
474 assert(Kind == Token && "Invalid type access!");
475 return Tok;
476 }
477
478 void print(raw_ostream &OS) const override {
479 switch (Kind) {
480 case Immediate:
481 OS << *getImm();
482 break;
483 case Register:
484 OS << "<register x";
485 OS << getReg() << ">";
486 break;
487 case Token:
488 OS << "'" << getToken() << "'";
489 break;
490 }
491 }
492
Alex Bradburya6e62482017-12-07 10:53:48 +0000493 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
494 bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000495 auto Op = make_unique<RISCVOperand>(Token);
496 Op->Tok = Str;
497 Op->StartLoc = S;
498 Op->EndLoc = S;
Alex Bradburya6e62482017-12-07 10:53:48 +0000499 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000500 return Op;
501 }
502
503 static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000504 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000505 auto Op = make_unique<RISCVOperand>(Register);
506 Op->Reg.RegNum = RegNo;
507 Op->StartLoc = S;
508 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000509 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000510 return Op;
511 }
512
513 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000514 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000515 auto Op = make_unique<RISCVOperand>(Immediate);
516 Op->Imm.Val = Val;
517 Op->StartLoc = S;
518 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000519 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000520 return Op;
521 }
522
523 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
524 assert(Expr && "Expr shouldn't be null!");
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000525 int64_t Imm = 0;
526 bool IsConstant = false;
527 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
528 IsConstant = RE->evaluateAsConstant(Imm);
529 } else if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
530 IsConstant = true;
531 Imm = CE->getValue();
532 }
533
534 if (IsConstant)
535 Inst.addOperand(MCOperand::createImm(Imm));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000536 else
537 Inst.addOperand(MCOperand::createExpr(Expr));
538 }
539
540 // Used by the TableGen Code
541 void addRegOperands(MCInst &Inst, unsigned N) const {
542 assert(N == 1 && "Invalid number of operands!");
543 Inst.addOperand(MCOperand::createReg(getReg()));
544 }
545
546 void addImmOperands(MCInst &Inst, unsigned N) const {
547 assert(N == 1 && "Invalid number of operands!");
548 addExpr(Inst, getImm());
549 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000550
551 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
552 assert(N == 1 && "Invalid number of operands!");
553 // isFenceArg has validated the operand, meaning this cast is safe
554 auto SE = cast<MCSymbolRefExpr>(getImm());
555
556 unsigned Imm = 0;
557 for (char c : SE->getSymbol().getName()) {
558 switch (c) {
559 default: llvm_unreachable("FenceArg must contain only [iorw]");
560 case 'i': Imm |= RISCVFenceField::I; break;
561 case 'o': Imm |= RISCVFenceField::O; break;
562 case 'r': Imm |= RISCVFenceField::R; break;
563 case 'w': Imm |= RISCVFenceField::W; break;
564 }
565 }
566 Inst.addOperand(MCOperand::createImm(Imm));
567 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000568
569 // Returns the rounding mode represented by this RISCVOperand. Should only
570 // be called after checking isFRMArg.
571 RISCVFPRndMode::RoundingMode getRoundingMode() const {
572 // isFRMArg has validated the operand, meaning this cast is safe.
573 auto SE = cast<MCSymbolRefExpr>(getImm());
574 RISCVFPRndMode::RoundingMode FRM =
575 RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
576 assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
577 return FRM;
578 }
579
580 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
581 assert(N == 1 && "Invalid number of operands!");
582 Inst.addOperand(MCOperand::createImm(getRoundingMode()));
583 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000584};
585} // end anonymous namespace.
586
587#define GET_REGISTER_MATCHER
588#define GET_MATCHER_IMPLEMENTATION
Alex Bradbury04f06d92017-08-08 14:43:36 +0000589#include "RISCVGenAsmMatcher.inc"
590
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000591// Return the matching FPR64 register for the given FPR32.
592// FIXME: Ideally this function could be removed in favour of using
593// information from TableGen.
594unsigned convertFPR32ToFPR64(unsigned Reg) {
595 switch (Reg) {
596 default:
597 llvm_unreachable("Not a recognised FPR32 register");
598 case RISCV::F0_32: return RISCV::F0_64;
599 case RISCV::F1_32: return RISCV::F1_64;
600 case RISCV::F2_32: return RISCV::F2_64;
601 case RISCV::F3_32: return RISCV::F3_64;
602 case RISCV::F4_32: return RISCV::F4_64;
603 case RISCV::F5_32: return RISCV::F5_64;
604 case RISCV::F6_32: return RISCV::F6_64;
605 case RISCV::F7_32: return RISCV::F7_64;
606 case RISCV::F8_32: return RISCV::F8_64;
607 case RISCV::F9_32: return RISCV::F9_64;
608 case RISCV::F10_32: return RISCV::F10_64;
609 case RISCV::F11_32: return RISCV::F11_64;
610 case RISCV::F12_32: return RISCV::F12_64;
611 case RISCV::F13_32: return RISCV::F13_64;
612 case RISCV::F14_32: return RISCV::F14_64;
613 case RISCV::F15_32: return RISCV::F15_64;
614 case RISCV::F16_32: return RISCV::F16_64;
615 case RISCV::F17_32: return RISCV::F17_64;
616 case RISCV::F18_32: return RISCV::F18_64;
617 case RISCV::F19_32: return RISCV::F19_64;
618 case RISCV::F20_32: return RISCV::F20_64;
619 case RISCV::F21_32: return RISCV::F21_64;
620 case RISCV::F22_32: return RISCV::F22_64;
621 case RISCV::F23_32: return RISCV::F23_64;
622 case RISCV::F24_32: return RISCV::F24_64;
623 case RISCV::F25_32: return RISCV::F25_64;
624 case RISCV::F26_32: return RISCV::F26_64;
625 case RISCV::F27_32: return RISCV::F27_64;
626 case RISCV::F28_32: return RISCV::F28_64;
627 case RISCV::F29_32: return RISCV::F29_64;
628 case RISCV::F30_32: return RISCV::F30_64;
629 case RISCV::F31_32: return RISCV::F31_64;
630 }
631}
632
633unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
634 unsigned Kind) {
635 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
636 if (!Op.isReg())
637 return Match_InvalidOperand;
638
639 unsigned Reg = Op.getReg();
640 bool IsRegFPR32 =
641 RISCVMCRegisterClasses[RISCV::FPR32RegClassID].contains(Reg);
Alex Bradbury60714f92017-12-13 09:32:55 +0000642 bool IsRegFPR32C =
643 RISCVMCRegisterClasses[RISCV::FPR32CRegClassID].contains(Reg);
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000644
645 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
Alex Bradbury60714f92017-12-13 09:32:55 +0000646 // register from FPR32 to FPR64 or FPR32C to FPR64C if necessary.
647 if ((IsRegFPR32 && Kind == MCK_FPR64) ||
648 (IsRegFPR32C && Kind == MCK_FPR64C)) {
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000649 Op.Reg.RegNum = convertFPR32ToFPR64(Reg);
650 return Match_Success;
651 }
652 return Match_InvalidOperand;
653}
654
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000655bool RISCVAsmParser::generateImmOutOfRangeError(
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000656 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000657 Twine Msg = "immediate must be an integer in the range") {
658 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
659 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
660}
661
Alex Bradbury04f06d92017-08-08 14:43:36 +0000662bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
663 OperandVector &Operands,
664 MCStreamer &Out,
665 uint64_t &ErrorInfo,
666 bool MatchingInlineAsm) {
667 MCInst Inst;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000668
669 switch (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm)) {
670 default:
671 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000672 case Match_Success:
673 return processInstruction(Inst, IDLoc, Out);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000674 case Match_MissingFeature:
675 return Error(IDLoc, "instruction use requires an option to be enabled");
676 case Match_MnemonicFail:
677 return Error(IDLoc, "unrecognized instruction mnemonic");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000678 case Match_InvalidOperand: {
679 SMLoc ErrorLoc = IDLoc;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000680 if (ErrorInfo != ~0U) {
681 if (ErrorInfo >= Operands.size())
682 return Error(ErrorLoc, "too few operands for instruction");
683
684 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
685 if (ErrorLoc == SMLoc())
686 ErrorLoc = IDLoc;
687 }
688 return Error(ErrorLoc, "invalid operand for instruction");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000689 }
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000690 case Match_InvalidImmXLen:
691 if (isRV64()) {
692 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
693 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
694 }
695 return generateImmOutOfRangeError(Operands, ErrorInfo,
696 std::numeric_limits<int32_t>::min(),
697 std::numeric_limits<uint32_t>::max());
Alex Bradburya6e62482017-12-07 10:53:48 +0000698 case Match_InvalidUImmLog2XLen:
699 if (isRV64())
700 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
701 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000702 case Match_InvalidUImmLog2XLenNonZero:
703 if (isRV64())
704 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
705 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000706 case Match_InvalidUImm5:
707 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury581d6b02017-12-13 09:41:21 +0000708 case Match_InvalidSImm6:
709 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
710 (1 << 5) - 1);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000711 case Match_InvalidSImm6NonZero:
712 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
713 (1 << 5) - 1,
714 "immediate must be non-zero in the range");
Shiva Chen7c172422018-02-22 15:02:28 +0000715 case Match_InvalidCLUIImm:
716 return generateImmOutOfRangeError(
717 Operands, ErrorInfo, 1, (1 << 5) - 1,
718 "immediate must be in [0xfffe0, 0xfffff] or");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000719 case Match_InvalidUImm7Lsb00:
720 return generateImmOutOfRangeError(
721 Operands, ErrorInfo, 0, (1 << 7) - 4,
722 "immediate must be a multiple of 4 bytes in the range");
723 case Match_InvalidUImm8Lsb00:
724 return generateImmOutOfRangeError(
725 Operands, ErrorInfo, 0, (1 << 8) - 4,
726 "immediate must be a multiple of 4 bytes in the range");
727 case Match_InvalidUImm8Lsb000:
728 return generateImmOutOfRangeError(
729 Operands, ErrorInfo, 0, (1 << 8) - 8,
730 "immediate must be a multiple of 8 bytes in the range");
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000731 case Match_InvalidSImm9Lsb0:
732 return generateImmOutOfRangeError(
733 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
734 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000735 case Match_InvalidUImm9Lsb000:
736 return generateImmOutOfRangeError(
737 Operands, ErrorInfo, 0, (1 << 9) - 8,
738 "immediate must be a multiple of 8 bytes in the range");
Alex Bradbury60714f92017-12-13 09:32:55 +0000739 case Match_InvalidUImm10Lsb00NonZero:
740 return generateImmOutOfRangeError(
741 Operands, ErrorInfo, 4, (1 << 10) - 4,
742 "immediate must be a multiple of 4 bytes in the range");
Shiva Chenb22c1d22018-02-02 02:43:23 +0000743 case Match_InvalidSImm10Lsb0000NonZero:
Alex Bradbury60714f92017-12-13 09:32:55 +0000744 return generateImmOutOfRangeError(
745 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
Shiva Chenb22c1d22018-02-02 02:43:23 +0000746 "immediate must be a multiple of 16 bytes and non-zero in the range");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000747 case Match_InvalidSImm12:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000748 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 11),
749 (1 << 11) - 1);
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000750 case Match_InvalidSImm12Lsb0:
751 return generateImmOutOfRangeError(
752 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
753 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000754 case Match_InvalidUImm12:
755 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1);
756 case Match_InvalidSImm13Lsb0:
757 return generateImmOutOfRangeError(
758 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
759 "immediate must be a multiple of 2 bytes in the range");
760 case Match_InvalidUImm20:
761 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
762 case Match_InvalidSImm21Lsb0:
763 return generateImmOutOfRangeError(
764 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
765 "immediate must be a multiple of 2 bytes in the range");
766 case Match_InvalidFenceArg: {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000767 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000768 return Error(
769 ErrorLoc,
770 "operand must be formed of letters selected in-order from 'iorw'");
771 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000772 case Match_InvalidFRMArg: {
773 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
774 return Error(
775 ErrorLoc,
776 "operand must be a valid floating point rounding mode mnemonic");
777 }
Shiva Chen98f93892018-04-25 14:18:55 +0000778 case Match_InvalidBareSymbol: {
779 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
780 return Error(ErrorLoc, "operand must be a bare symbol name");
781 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000782 }
783
784 llvm_unreachable("Unknown match type detected!");
785}
786
787bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
788 SMLoc &EndLoc) {
789 const AsmToken &Tok = getParser().getTok();
790 StartLoc = Tok.getLoc();
791 EndLoc = Tok.getEndLoc();
792 RegNo = 0;
793 StringRef Name = getLexer().getTok().getIdentifier();
794
795 if (!MatchRegisterName(Name) || !MatchRegisterAltName(Name)) {
796 getParser().Lex(); // Eat identifier token.
797 return false;
798 }
799
800 return Error(StartLoc, "invalid register name");
801}
802
Alex Bradbury8c345c52017-11-09 15:00:03 +0000803OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
804 bool AllowParens) {
805 SMLoc FirstS = getLoc();
806 bool HadParens = false;
807 AsmToken Buf[2];
808
809 // If this a parenthesised register name is allowed, parse it atomically
810 if (AllowParens && getLexer().is(AsmToken::LParen)) {
811 size_t ReadCount = getLexer().peekTokens(Buf);
812 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
813 HadParens = true;
814 getParser().Lex(); // Eat '('
815 }
816 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000817
818 switch (getLexer().getKind()) {
819 default:
820 return MatchOperand_NoMatch;
821 case AsmToken::Identifier:
822 StringRef Name = getLexer().getTok().getIdentifier();
823 unsigned RegNo = MatchRegisterName(Name);
824 if (RegNo == 0) {
825 RegNo = MatchRegisterAltName(Name);
Alex Bradbury8c345c52017-11-09 15:00:03 +0000826 if (RegNo == 0) {
827 if (HadParens)
828 getLexer().UnLex(Buf[0]);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000829 return MatchOperand_NoMatch;
Alex Bradbury8c345c52017-11-09 15:00:03 +0000830 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000831 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000832 if (HadParens)
Alex Bradburya6e62482017-12-07 10:53:48 +0000833 Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000834 SMLoc S = getLoc();
835 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000836 getLexer().Lex();
Alex Bradburya6e62482017-12-07 10:53:48 +0000837 Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000838 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000839
840 if (HadParens) {
841 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000842 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000843 }
844
Alex Bradbury04f06d92017-08-08 14:43:36 +0000845 return MatchOperand_Success;
846}
847
848OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000849 SMLoc S = getLoc();
850 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
851 const MCExpr *Res;
852
Alex Bradbury04f06d92017-08-08 14:43:36 +0000853 switch (getLexer().getKind()) {
854 default:
855 return MatchOperand_NoMatch;
856 case AsmToken::LParen:
857 case AsmToken::Minus:
858 case AsmToken::Plus:
859 case AsmToken::Integer:
860 case AsmToken::String:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000861 if (getParser().parseExpression(Res))
862 return MatchOperand_ParseFail;
863 break;
864 case AsmToken::Identifier: {
865 StringRef Identifier;
866 if (getParser().parseIdentifier(Identifier))
867 return MatchOperand_ParseFail;
868 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
869 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Alex Bradbury04f06d92017-08-08 14:43:36 +0000870 break;
871 }
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000872 case AsmToken::Percent:
873 return parseOperandWithModifier(Operands);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000874 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000875
Alex Bradburya6e62482017-12-07 10:53:48 +0000876 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000877 return MatchOperand_Success;
878}
879
880OperandMatchResultTy
881RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
882 SMLoc S = getLoc();
883 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
884
885 if (getLexer().getKind() != AsmToken::Percent) {
886 Error(getLoc(), "expected '%' for operand modifier");
887 return MatchOperand_ParseFail;
888 }
889
890 getParser().Lex(); // Eat '%'
891
892 if (getLexer().getKind() != AsmToken::Identifier) {
893 Error(getLoc(), "expected valid identifier for operand modifier");
894 return MatchOperand_ParseFail;
895 }
896 StringRef Identifier = getParser().getTok().getIdentifier();
897 RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
898 if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
899 Error(getLoc(), "unrecognized operand modifier");
900 return MatchOperand_ParseFail;
901 }
902
903 getParser().Lex(); // Eat the identifier
904 if (getLexer().getKind() != AsmToken::LParen) {
905 Error(getLoc(), "expected '('");
906 return MatchOperand_ParseFail;
907 }
908 getParser().Lex(); // Eat '('
909
910 const MCExpr *SubExpr;
911 if (getParser().parseParenExpression(SubExpr, E)) {
912 return MatchOperand_ParseFail;
913 }
914
915 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
Alex Bradburya6e62482017-12-07 10:53:48 +0000916 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000917 return MatchOperand_Success;
918}
919
920OperandMatchResultTy
921RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
922 if (getLexer().isNot(AsmToken::LParen)) {
923 Error(getLoc(), "expected '('");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000924 return MatchOperand_ParseFail;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000925 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000926
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000927 getParser().Lex(); // Eat '('
Alex Bradburya6e62482017-12-07 10:53:48 +0000928 Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000929
930 if (parseRegister(Operands) != MatchOperand_Success) {
931 Error(getLoc(), "expected register");
932 return MatchOperand_ParseFail;
933 }
934
935 if (getLexer().isNot(AsmToken::RParen)) {
936 Error(getLoc(), "expected ')'");
937 return MatchOperand_ParseFail;
938 }
939
940 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000941 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000942
Alex Bradbury04f06d92017-08-08 14:43:36 +0000943 return MatchOperand_Success;
944}
945
Alex Bradburycd8688a2018-04-25 17:25:29 +0000946/// Looks at a token type and creates the relevant operand from this
947/// information, adding to Operands. If operand was parsed, returns false, else
948/// true. If ForceImmediate is true, no attempt will be made to parse the
949/// operand as a register, which is needed for pseudoinstructions such as
950/// call.
951bool RISCVAsmParser::parseOperand(OperandVector &Operands,
952 bool ForceImmediate) {
953 // Attempt to parse token as register, unless ForceImmediate.
954 if (!ForceImmediate && parseRegister(Operands, true) == MatchOperand_Success)
Alex Bradbury04f06d92017-08-08 14:43:36 +0000955 return false;
956
957 // Attempt to parse token as an immediate
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000958 if (parseImmediate(Operands) == MatchOperand_Success) {
959 // Parse memory base register if present
960 if (getLexer().is(AsmToken::LParen))
961 return parseMemOpBaseReg(Operands) != MatchOperand_Success;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000962 return false;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000963 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000964
965 // Finally we have exhausted all options and must declare defeat.
966 Error(getLoc(), "unknown operand");
967 return true;
968}
969
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +0000970/// Return true if the operand at the OperandIdx for opcode Name should be
971/// 'forced' to be parsed as an immediate. This is required for
972/// pseudoinstructions such as tail or call, which allow bare symbols to be used
973/// that could clash with register names.
974static bool shouldForceImediateOperand(StringRef Name, unsigned OperandIdx) {
975 // FIXME: This may not scale so perhaps we want to use a data-driven approach
976 // instead.
977 switch (OperandIdx) {
978 case 0:
979 // call imm
980 // tail imm
981 return Name == "tail" || Name == "call";
982 case 1:
983 // lla rdest, imm
984 return Name == "lla";
985 default:
986 return false;
987 }
988}
989
Alex Bradbury04f06d92017-08-08 14:43:36 +0000990bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
991 StringRef Name, SMLoc NameLoc,
992 OperandVector &Operands) {
993 // First operand is token for instruction
Alex Bradburya6e62482017-12-07 10:53:48 +0000994 Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000995
996 // If there are no more operands, then finish
997 if (getLexer().is(AsmToken::EndOfStatement))
998 return false;
999
1000 // Parse first operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001001 if (parseOperand(Operands, shouldForceImediateOperand(Name, 0)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001002 return true;
1003
1004 // Parse until end of statement, consuming commas between operands
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001005 unsigned OperandIdx = 1;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001006 while (getLexer().is(AsmToken::Comma)) {
1007 // Consume comma token
1008 getLexer().Lex();
1009
1010 // Parse next operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001011 if (parseOperand(Operands, shouldForceImediateOperand(Name, OperandIdx)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001012 return true;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001013
1014 ++OperandIdx;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001015 }
1016
1017 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1018 SMLoc Loc = getLexer().getLoc();
1019 getParser().eatToEndOfStatement();
1020 return Error(Loc, "unexpected token");
1021 }
1022
1023 getParser().Lex(); // Consume the EndOfStatement.
1024 return false;
1025}
1026
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001027bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1028 RISCVMCExpr::VariantKind &Kind,
1029 int64_t &Addend) {
1030 Kind = RISCVMCExpr::VK_RISCV_None;
1031 Addend = 0;
1032
1033 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1034 Kind = RE->getKind();
1035 Expr = RE->getSubExpr();
1036 }
1037
1038 // It's a simple symbol reference or constant with no addend.
1039 if (isa<MCConstantExpr>(Expr) || isa<MCSymbolRefExpr>(Expr))
1040 return true;
1041
1042 const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
1043 if (!BE)
1044 return false;
1045
1046 if (!isa<MCSymbolRefExpr>(BE->getLHS()))
1047 return false;
1048
1049 if (BE->getOpcode() != MCBinaryExpr::Add &&
1050 BE->getOpcode() != MCBinaryExpr::Sub)
1051 return false;
1052
1053 // We are able to support the subtraction of two symbol references
1054 if (BE->getOpcode() == MCBinaryExpr::Sub &&
1055 isa<MCSymbolRefExpr>(BE->getRHS()))
1056 return true;
1057
Hiroshi Inoue9ff23802018-04-09 04:37:53 +00001058 // See if the addend is a constant, otherwise there's more going
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001059 // on here than we can deal with.
1060 auto AddendExpr = dyn_cast<MCConstantExpr>(BE->getRHS());
1061 if (!AddendExpr)
1062 return false;
1063
1064 Addend = AddendExpr->getValue();
1065 if (BE->getOpcode() == MCBinaryExpr::Sub)
1066 Addend = -Addend;
1067
1068 // It's some symbol reference + a constant addend
1069 return Kind != RISCVMCExpr::VK_RISCV_Invalid;
1070}
1071
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001072bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1073 // This returns false if this function recognizes the directive
1074 // regardless of whether it is successfully handles or reports an
1075 // error. Otherwise it returns true to give the generic parser a
1076 // chance at recognizing it.
1077 StringRef IDVal = DirectiveID.getString();
1078
1079 if (IDVal == ".option")
1080 return parseDirectiveOption();
1081
1082 return true;
1083}
1084
1085bool RISCVAsmParser::parseDirectiveOption() {
1086 MCAsmParser &Parser = getParser();
1087 // Get the option token.
1088 AsmToken Tok = Parser.getTok();
1089 // At the moment only identifiers are supported.
1090 if (Tok.isNot(AsmToken::Identifier))
1091 return Error(Parser.getTok().getLoc(),
1092 "unexpected token, expected identifier");
1093
1094 StringRef Option = Tok.getIdentifier();
1095
1096 if (Option == "rvc") {
1097 getTargetStreamer().emitDirectiveOptionRVC();
1098
1099 Parser.Lex();
1100 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1101 return Error(Parser.getTok().getLoc(),
1102 "unexpected token, expected end of statement");
1103
1104 setFeatureBits(RISCV::FeatureStdExtC, "c");
1105 return false;
1106 }
1107
1108 if (Option == "norvc") {
1109 getTargetStreamer().emitDirectiveOptionNoRVC();
1110
1111 Parser.Lex();
1112 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1113 return Error(Parser.getTok().getLoc(),
1114 "unexpected token, expected end of statement");
1115
1116 clearFeatureBits(RISCV::FeatureStdExtC, "c");
1117 return false;
1118 }
1119
1120 // Unknown option.
1121 Warning(Parser.getTok().getLoc(),
1122 "unknown option, expected 'rvc' or 'norvc'");
1123 Parser.eatToEndOfStatement();
1124 return false;
1125}
Alex Bradbury04f06d92017-08-08 14:43:36 +00001126
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001127void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
1128 MCInst CInst;
1129 bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
1130 CInst.setLoc(Inst.getLoc());
1131 S.EmitInstruction((Res ? CInst : Inst), getSTI());
1132}
1133
1134void RISCVAsmParser::emitLoadImm(unsigned DestReg, int64_t Value,
1135 MCStreamer &Out) {
1136 if (isInt<32>(Value)) {
1137 // Emits the MC instructions for loading a 32-bit constant into a register.
1138 //
1139 // Depending on the active bits in the immediate Value v, the following
1140 // instruction sequences are emitted:
1141 //
1142 // v == 0 : ADDI(W)
1143 // v[0,12) != 0 && v[12,32) == 0 : ADDI(W)
1144 // v[0,12) == 0 && v[12,32) != 0 : LUI
1145 // v[0,32) != 0 : LUI+ADDI(W)
1146 //
1147 int64_t Hi20 = ((Value + 0x800) >> 12) & 0xFFFFF;
1148 int64_t Lo12 = SignExtend64<12>(Value);
1149 unsigned SrcReg = RISCV::X0;
1150
1151 if (Hi20) {
1152 emitToStreamer(Out,
1153 MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Hi20));
1154 SrcReg = DestReg;
1155 }
1156
1157 if (Lo12 || Hi20 == 0) {
1158 unsigned AddiOpcode =
1159 STI->hasFeature(RISCV::Feature64Bit) ? RISCV::ADDIW : RISCV::ADDI;
1160 emitToStreamer(Out, MCInstBuilder(AddiOpcode)
1161 .addReg(DestReg)
1162 .addReg(SrcReg)
1163 .addImm(Lo12));
1164 }
1165 return;
1166 }
1167 assert(STI->hasFeature(RISCV::Feature64Bit) &&
1168 "Target must be 64-bit to support a >32-bit constant");
1169
1170 // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
1171 // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emmitted. Note
1172 // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
1173 // while the following ADDI instructions contribute up to 12 bits each.
1174 //
1175 // On the first glance, implementing this seems to be possible by simply
1176 // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
1177 // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
1178 // fact that ADDI performs a sign extended addition, doing it like that would
1179 // only be possible when at most 11 bits of the ADDI instructions are used.
1180 // Using all 12 bits of the ADDI instructions, like done by GAS, actually
1181 // requires that the constant is processed starting with the least significant
1182 // bit.
1183 //
1184 // In the following, constants are processed from LSB to MSB but instruction
1185 // emission is performed from MSB to LSB by recursively calling
1186 // emitLoadImm. In each recursion, first the lowest 12 bits are removed
1187 // from the constant and the optimal shift amount, which can be greater than
1188 // 12 bits if the constant is sparse, is determined. Then, the shifted
1189 // remaining constant is processed recursively and gets emitted as soon as it
1190 // fits into 32 bits. The emission of the shifts and additions is subsequently
1191 // performed when the recursion returns.
1192 //
1193 int64_t Lo12 = SignExtend64<12>(Value);
1194 int64_t Hi52 = (Value + 0x800) >> 12;
1195 int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
1196 Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
1197
1198 emitLoadImm(DestReg, Hi52, Out);
1199
1200 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
1201 .addReg(DestReg)
1202 .addReg(DestReg)
1203 .addImm(ShiftAmount));
1204
1205 if (Lo12)
1206 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1207 .addReg(DestReg)
1208 .addReg(DestReg)
1209 .addImm(Lo12));
1210}
1211
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001212void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
1213 MCStreamer &Out) {
1214 // The local load address pseudo-instruction "lla" is used in PC-relative
1215 // addressing of symbols:
1216 // lla rdest, symbol
1217 // expands to
1218 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1219 // ADDI rdest, %pcrel_lo(TmpLabel)
1220 MCContext &Ctx = getContext();
1221
1222 MCSymbol *TmpLabel = Ctx.createTempSymbol(
1223 "pcrel_hi", /* AlwaysAddSuffix */ true, /* CanBeUnnamed */ false);
1224 Out.EmitLabel(TmpLabel);
1225
1226 MCOperand DestReg = Inst.getOperand(0);
1227 const RISCVMCExpr *Symbol = RISCVMCExpr::create(
1228 Inst.getOperand(1).getExpr(), RISCVMCExpr::VK_RISCV_PCREL_HI, Ctx);
1229
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001230 emitToStreamer(
1231 Out, MCInstBuilder(RISCV::AUIPC).addOperand(DestReg).addExpr(Symbol));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001232
1233 const MCExpr *RefToLinkTmpLabel =
1234 RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
1235 RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
1236
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001237 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1238 .addOperand(DestReg)
1239 .addOperand(DestReg)
1240 .addExpr(RefToLinkTmpLabel));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001241}
1242
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001243bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1244 MCStreamer &Out) {
1245 Inst.setLoc(IDLoc);
1246
1247 if (Inst.getOpcode() == RISCV::PseudoLI) {
1248 auto Reg = Inst.getOperand(0).getReg();
1249 int64_t Imm = Inst.getOperand(1).getImm();
1250 // On RV32 the immediate here can either be a signed or an unsigned
1251 // 32-bit number. Sign extension has to be performed to ensure that Imm
1252 // represents the expected signed 64-bit number.
1253 if (!isRV64())
1254 Imm = SignExtend64<32>(Imm);
1255 emitLoadImm(Reg, Imm, Out);
1256 return false;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001257 } else if (Inst.getOpcode() == RISCV::PseudoLLA) {
1258 emitLoadLocalAddress(Inst, IDLoc, Out);
1259 return false;
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001260 }
1261
1262 emitToStreamer(Out, Inst);
1263 return false;
1264}
1265
Alex Bradbury04f06d92017-08-08 14:43:36 +00001266extern "C" void LLVMInitializeRISCVAsmParser() {
1267 RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
1268 RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
1269}