1 //===-- BPFAsmParser.cpp - Parse BPF assembly to MCInst instructions --===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "MCTargetDesc/BPFMCTargetDesc.h"
10 #include "TargetInfo/BPFTargetInfo.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCInstrInfo.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/TargetRegistry.h"
22 #include "llvm/Support/Casting.h"
29 class BPFAsmParser
: public MCTargetAsmParser
{
31 SMLoc
getLoc() const { return getParser().getTok().getLoc(); }
33 bool PreMatchCheck(OperandVector
&Operands
);
35 bool matchAndEmitInstruction(SMLoc IDLoc
, unsigned &Opcode
,
36 OperandVector
&Operands
, MCStreamer
&Out
,
38 bool MatchingInlineAsm
) override
;
40 bool parseRegister(MCRegister
&Reo
, SMLoc
&StartLoc
, SMLoc
&EndLoc
) override
;
41 ParseStatus
tryParseRegister(MCRegister
&Reg
, SMLoc
&StartLoc
,
42 SMLoc
&EndLoc
) override
;
44 bool parseInstruction(ParseInstructionInfo
&Info
, StringRef Name
,
45 SMLoc NameLoc
, OperandVector
&Operands
) override
;
47 // "=" is used as assignment operator for assembly statment, so can't be used
48 // for symbol assignment.
49 bool equalIsAsmAssignment() override
{ return false; }
50 // "*" is used for dereferencing memory that it will be the start of
52 bool starIsStartOfStatement() override
{ return true; }
54 #define GET_ASSEMBLER_HEADER
55 #include "BPFGenAsmMatcher.inc"
57 ParseStatus
parseImmediate(OperandVector
&Operands
);
58 ParseStatus
parseRegister(OperandVector
&Operands
);
59 ParseStatus
parseOperandAsOperator(OperandVector
&Operands
);
62 enum BPFMatchResultTy
{
63 Match_Dummy
= FIRST_TARGET_MATCH_RESULT_TY
,
64 #define GET_OPERAND_DIAGNOSTIC_TYPES
65 #include "BPFGenAsmMatcher.inc"
66 #undef GET_OPERAND_DIAGNOSTIC_TYPES
69 BPFAsmParser(const MCSubtargetInfo
&STI
, MCAsmParser
&Parser
,
70 const MCInstrInfo
&MII
, const MCTargetOptions
&Options
)
71 : MCTargetAsmParser(Options
, STI
, MII
) {
72 setAvailableFeatures(ComputeAvailableFeatures(STI
.getFeatureBits()));
76 /// BPFOperand - Instances of this class represent a parsed machine
78 struct BPFOperand
: public MCParsedAsmOperand
{
94 SMLoc StartLoc
, EndLoc
;
101 BPFOperand(KindTy K
) : Kind(K
) {}
104 BPFOperand(const BPFOperand
&o
) : MCParsedAsmOperand() {
106 StartLoc
= o
.StartLoc
;
122 bool isToken() const override
{ return Kind
== Token
; }
123 bool isReg() const override
{ return Kind
== Register
; }
124 bool isImm() const override
{ return Kind
== Immediate
; }
125 bool isMem() const override
{ return false; }
127 bool isConstantImm() const {
128 return isImm() && isa
<MCConstantExpr
>(getImm());
131 int64_t getConstantImm() const {
132 const MCExpr
*Val
= getImm();
133 return static_cast<const MCConstantExpr
*>(Val
)->getValue();
136 bool isSImm16() const {
137 return (isConstantImm() && isInt
<16>(getConstantImm()));
140 bool isSymbolRef() const { return isImm() && isa
<MCSymbolRefExpr
>(getImm()); }
142 bool isBrTarget() const { return isSymbolRef() || isSImm16(); }
144 /// getStartLoc - Gets location of the first token of this operand
145 SMLoc
getStartLoc() const override
{ return StartLoc
; }
146 /// getEndLoc - Gets location of the last token of this operand
147 SMLoc
getEndLoc() const override
{ return EndLoc
; }
149 MCRegister
getReg() const override
{
150 assert(Kind
== Register
&& "Invalid type access!");
154 const MCExpr
*getImm() const {
155 assert(Kind
== Immediate
&& "Invalid type access!");
159 StringRef
getToken() const {
160 assert(Kind
== Token
&& "Invalid type access!");
164 void print(raw_ostream
&OS
) const override
{
171 OS
<< getReg() << ">";
174 OS
<< "'" << getToken() << "'";
179 void addExpr(MCInst
&Inst
, const MCExpr
*Expr
) const {
180 assert(Expr
&& "Expr shouldn't be null!");
182 if (auto *CE
= dyn_cast
<MCConstantExpr
>(Expr
))
183 Inst
.addOperand(MCOperand::createImm(CE
->getValue()));
185 Inst
.addOperand(MCOperand::createExpr(Expr
));
188 // Used by the TableGen Code
189 void addRegOperands(MCInst
&Inst
, unsigned N
) const {
190 assert(N
== 1 && "Invalid number of operands!");
191 Inst
.addOperand(MCOperand::createReg(getReg()));
194 void addImmOperands(MCInst
&Inst
, unsigned N
) const {
195 assert(N
== 1 && "Invalid number of operands!");
196 addExpr(Inst
, getImm());
199 static std::unique_ptr
<BPFOperand
> createToken(StringRef Str
, SMLoc S
) {
200 auto Op
= std::make_unique
<BPFOperand
>(Token
);
207 static std::unique_ptr
<BPFOperand
> createReg(MCRegister Reg
, SMLoc S
,
209 auto Op
= std::make_unique
<BPFOperand
>(Register
);
210 Op
->Reg
.RegNum
= Reg
;
216 static std::unique_ptr
<BPFOperand
> createImm(const MCExpr
*Val
, SMLoc S
,
218 auto Op
= std::make_unique
<BPFOperand
>(Immediate
);
225 // Identifiers that can be used at the start of a statment.
226 static bool isValidIdAtStart(StringRef Name
) {
227 return StringSwitch
<bool>(Name
.lower())
233 .Case("may_goto", true)
237 .Case("ld_pseudo", true)
241 // Identifiers that can be used in the middle of a statment.
242 static bool isValidIdInMiddle(StringRef Name
) {
243 return StringSwitch
<bool>(Name
.lower())
257 .Case("bswap16", true)
258 .Case("bswap32", true)
259 .Case("bswap64", true)
265 .Case("atomic_fetch_add", true)
266 .Case("atomic_fetch_and", true)
267 .Case("atomic_fetch_or", true)
268 .Case("atomic_fetch_xor", true)
269 .Case("xchg_64", true)
270 .Case("xchg32_32", true)
271 .Case("cmpxchg_64", true)
272 .Case("cmpxchg32_32", true)
273 .Case("addr_space_cast", true)
277 } // end anonymous namespace.
279 #define GET_REGISTER_MATCHER
280 #define GET_MATCHER_IMPLEMENTATION
281 #include "BPFGenAsmMatcher.inc"
283 bool BPFAsmParser::PreMatchCheck(OperandVector
&Operands
) {
285 if (Operands
.size() == 4) {
286 // check "reg1 = -reg2" and "reg1 = be16/be32/be64/le16/le32/le64 reg2",
287 // reg1 must be the same as reg2
288 BPFOperand
&Op0
= (BPFOperand
&)*Operands
[0];
289 BPFOperand
&Op1
= (BPFOperand
&)*Operands
[1];
290 BPFOperand
&Op2
= (BPFOperand
&)*Operands
[2];
291 BPFOperand
&Op3
= (BPFOperand
&)*Operands
[3];
292 if (Op0
.isReg() && Op1
.isToken() && Op2
.isToken() && Op3
.isReg()
293 && Op1
.getToken() == "="
294 && (Op2
.getToken() == "-" || Op2
.getToken() == "be16"
295 || Op2
.getToken() == "be32" || Op2
.getToken() == "be64"
296 || Op2
.getToken() == "le16" || Op2
.getToken() == "le32"
297 || Op2
.getToken() == "le64")
298 && Op0
.getReg() != Op3
.getReg())
305 bool BPFAsmParser::matchAndEmitInstruction(SMLoc IDLoc
, unsigned &Opcode
,
306 OperandVector
&Operands
,
307 MCStreamer
&Out
, uint64_t &ErrorInfo
,
308 bool MatchingInlineAsm
) {
312 if (PreMatchCheck(Operands
))
313 return Error(IDLoc
, "additional inst constraint not met");
315 switch (MatchInstructionImpl(Operands
, Inst
, ErrorInfo
, MatchingInlineAsm
)) {
320 Out
.emitInstruction(Inst
, getSTI());
322 case Match_MissingFeature
:
323 return Error(IDLoc
, "instruction use requires an option to be enabled");
324 case Match_MnemonicFail
:
325 return Error(IDLoc
, "unrecognized instruction mnemonic");
326 case Match_InvalidOperand
:
329 if (ErrorInfo
!= ~0U) {
330 if (ErrorInfo
>= Operands
.size())
331 return Error(ErrorLoc
, "too few operands for instruction");
333 ErrorLoc
= ((BPFOperand
&)*Operands
[ErrorInfo
]).getStartLoc();
335 if (ErrorLoc
== SMLoc())
339 return Error(ErrorLoc
, "invalid operand for instruction");
340 case Match_InvalidBrTarget
:
341 return Error(Operands
[ErrorInfo
]->getStartLoc(),
342 "operand is not an identifier or 16-bit signed integer");
343 case Match_InvalidSImm16
:
344 return Error(Operands
[ErrorInfo
]->getStartLoc(),
345 "operand is not a 16-bit signed integer");
348 llvm_unreachable("Unknown match type detected!");
351 bool BPFAsmParser::parseRegister(MCRegister
&Reg
, SMLoc
&StartLoc
,
353 if (!tryParseRegister(Reg
, StartLoc
, EndLoc
).isSuccess())
354 return Error(StartLoc
, "invalid register name");
358 ParseStatus
BPFAsmParser::tryParseRegister(MCRegister
&Reg
, SMLoc
&StartLoc
,
360 const AsmToken
&Tok
= getParser().getTok();
361 StartLoc
= Tok
.getLoc();
362 EndLoc
= Tok
.getEndLoc();
363 Reg
= BPF::NoRegister
;
364 StringRef Name
= getLexer().getTok().getIdentifier();
366 if (!MatchRegisterName(Name
)) {
367 getParser().Lex(); // Eat identifier token.
368 return ParseStatus::Success
;
371 return ParseStatus::NoMatch
;
374 ParseStatus
BPFAsmParser::parseOperandAsOperator(OperandVector
&Operands
) {
377 if (getLexer().getKind() == AsmToken::Identifier
) {
378 StringRef Name
= getLexer().getTok().getIdentifier();
380 if (BPFOperand::isValidIdInMiddle(Name
)) {
382 Operands
.push_back(BPFOperand::createToken(Name
, S
));
383 return ParseStatus::Success
;
386 return ParseStatus::NoMatch
;
389 switch (getLexer().getKind()) {
390 case AsmToken::Minus
:
391 case AsmToken::Plus
: {
392 if (getLexer().peekTok().is(AsmToken::Integer
))
393 return ParseStatus::NoMatch
;
397 case AsmToken::Equal
:
398 case AsmToken::Greater
:
402 case AsmToken::LParen
:
403 case AsmToken::RParen
:
404 case AsmToken::LBrac
:
405 case AsmToken::RBrac
:
406 case AsmToken::Slash
:
408 case AsmToken::Percent
:
409 case AsmToken::Caret
: {
410 StringRef Name
= getLexer().getTok().getString();
412 Operands
.push_back(BPFOperand::createToken(Name
, S
));
414 return ParseStatus::Success
;
417 case AsmToken::EqualEqual
:
418 case AsmToken::ExclaimEqual
:
419 case AsmToken::GreaterEqual
:
420 case AsmToken::GreaterGreater
:
421 case AsmToken::LessEqual
:
422 case AsmToken::LessLess
: {
423 Operands
.push_back(BPFOperand::createToken(
424 getLexer().getTok().getString().substr(0, 1), S
));
425 Operands
.push_back(BPFOperand::createToken(
426 getLexer().getTok().getString().substr(1, 1), S
));
429 return ParseStatus::Success
;
436 return ParseStatus::NoMatch
;
439 ParseStatus
BPFAsmParser::parseRegister(OperandVector
&Operands
) {
441 SMLoc E
= SMLoc::getFromPointer(S
.getPointer() - 1);
443 switch (getLexer().getKind()) {
445 return ParseStatus::NoMatch
;
446 case AsmToken::Identifier
:
447 StringRef Name
= getLexer().getTok().getIdentifier();
448 MCRegister Reg
= MatchRegisterName(Name
);
451 return ParseStatus::NoMatch
;
454 Operands
.push_back(BPFOperand::createReg(Reg
, S
, E
));
456 return ParseStatus::Success
;
459 ParseStatus
BPFAsmParser::parseImmediate(OperandVector
&Operands
) {
460 switch (getLexer().getKind()) {
462 return ParseStatus::NoMatch
;
463 case AsmToken::LParen
:
464 case AsmToken::Minus
:
466 case AsmToken::Integer
:
467 case AsmToken::String
:
468 case AsmToken::Identifier
:
475 if (getParser().parseExpression(IdVal
))
476 return ParseStatus::Failure
;
478 SMLoc E
= SMLoc::getFromPointer(S
.getPointer() - 1);
479 Operands
.push_back(BPFOperand::createImm(IdVal
, S
, E
));
481 return ParseStatus::Success
;
484 /// Parse an BPF instruction which is in BPF verifier format.
485 bool BPFAsmParser::parseInstruction(ParseInstructionInfo
&Info
, StringRef Name
,
486 SMLoc NameLoc
, OperandVector
&Operands
) {
487 // The first operand could be either register or actually an operator.
488 MCRegister Reg
= MatchRegisterName(Name
);
491 SMLoc E
= SMLoc::getFromPointer(NameLoc
.getPointer() - 1);
492 Operands
.push_back(BPFOperand::createReg(Reg
, NameLoc
, E
));
493 } else if (BPFOperand::isValidIdAtStart(Name
))
494 Operands
.push_back(BPFOperand::createToken(Name
, NameLoc
));
496 return Error(NameLoc
, "invalid register/token name");
498 while (!getLexer().is(AsmToken::EndOfStatement
)) {
499 // Attempt to parse token as operator
500 if (parseOperandAsOperator(Operands
).isSuccess())
503 // Attempt to parse token as register
504 if (parseRegister(Operands
).isSuccess())
507 if (getLexer().is(AsmToken::Comma
)) {
512 // Attempt to parse token as an immediate
513 if (!parseImmediate(Operands
).isSuccess()) {
514 SMLoc Loc
= getLexer().getLoc();
515 return Error(Loc
, "unexpected token");
519 if (getLexer().isNot(AsmToken::EndOfStatement
)) {
520 SMLoc Loc
= getLexer().getLoc();
522 getParser().eatToEndOfStatement();
524 return Error(Loc
, "unexpected token");
527 // Consume the EndOfStatement.
532 extern "C" LLVM_EXTERNAL_VISIBILITY
void LLVMInitializeBPFAsmParser() {
533 RegisterMCAsmParser
<BPFAsmParser
> X(getTheBPFTarget());
534 RegisterMCAsmParser
<BPFAsmParser
> Y(getTheBPFleTarget());
535 RegisterMCAsmParser
<BPFAsmParser
> Z(getTheBPFbeTarget());