24#include "llvm/ADT/APSInt.h"
46 if (ArgType->getAsPlaceholderType())
63 if (
const auto *RT = ArgType->getAsCanonical<TagType>())
64 if (!RT->getDecl()->getDeclName().isEmpty())
72 if (ArgType->getAsPlaceholderType())
79 const auto *UO = dyn_cast<UnaryOperator>(Arg->
IgnoreParens());
83 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
86 if (CE->getCastKind() != CK_IntegralToPointer &&
87 CE->getCastKind() != CK_NullToPointer)
91 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
96 dyn_cast<EnumConstantDecl>(DR->getDecl());
101 const auto *ED = ArgType->getAsEnumDecl();
106 return llvm::is_contained(ED->enumerators(),
Enumerator);
115 : CK_IntegralToPointer;
122 auto *UO = dyn_cast<UnaryOperator>(Arg->
IgnoreParens());
123 if (!UO || UO->getOpcode() != UO_Deref)
125 auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
136 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
137 BuiltinID == BPF::BI__builtin_btf_type_id ||
138 BuiltinID == BPF::BI__builtin_preserve_type_info ||
139 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
140 "unexpected BPF builtin");
142 if (
SemaRef.checkArgCount(TheCall, 2))
150 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
151 kind = diag::err_preserve_field_info_not_const;
152 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
153 kind = diag::err_btf_type_id_not_const;
154 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
155 kind = diag::err_preserve_type_info_not_const;
157 kind = diag::err_preserve_enum_value_not_const;
164 bool InvalidArg =
false;
165 bool ReturnUnsignedInt =
true;
166 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
169 kind = diag::err_preserve_field_info_not_field;
171 }
else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
174 kind = diag::err_preserve_type_info_invalid;
176 }
else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
180 kind = diag::err_preserve_enum_value_invalid;
182 ReturnUnsignedInt =
false;
183 }
else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
184 ReturnUnsignedInt =
false;
192 if (ReturnUnsignedInt)
193 TheCall->
setType(Context.UnsignedIntTy);
195 TheCall->
setType(Context.UnsignedLongTy);
202 for (
auto *D : RD->
decls()) {
203 if (
isa<EnumDecl>(D) || D->hasAttr<BPFPreserveAccessIndexAttr>())
206 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(
getASTContext()));
207 if (
auto *Rec = dyn_cast<RecordDecl>(D))
213 if (
auto *Rec = dyn_cast<RecordDecl>(D))
217 if (
auto *ED = dyn_cast<EnumDecl>(D);
219 AnonPreserveAIEnums.insert({ED, A});
224 for (
auto [ED, A] : AnonPreserveAIEnums)
225 if (!ED->getTypedefNameForAnonDecl())
226 Diag(A->getLocation(), diag::warn_preserve_access_index_anon_enum) << A;
227 AnonPreserveAIEnums.clear();
241 const auto *ED = dyn_cast<EnumDecl>(
Enumerator->getDeclContext());
242 if (!ED || !ED->isCompleteDefinition() ||
243 !ED->hasAttr<BPFPreserveAccessIndexAttr>())
249 if (!ED->getDeclName()) {
250 TD = ED->getTypedefNameForAnonDecl();
254 StringRef Name = TD ? TD->
getName() : ED->getName();
255 if (llvm::is_contained(Context.getLangOpts().BPFNoEnumRelocs, Name))
257 return TD ? Context.getTypeDeclType(TD) : Context.getCanonicalTagType(ED);
269 if (
SemaRef.isUnevaluatedContext())
282 SemaRef.CurContext->getRedeclContext()->isFileContext()) {
284 diag::warn_preserve_access_index_enumerator_not_relocated)
292 if (llvm::any_of(
SemaRef.ExprEvalContexts,
294 return Rec.isUnevaluated();
305 QualType PtrTy = Context.getPointerType(EnumTy);
310 Context.getTrivialTypeSourceInfo(PtrTy, Loc), Loc, Loc);
318 Expr *Args[] = {Deref, Flag};
320 Loc, BPF::BI__builtin_preserve_enum_value, Args);
325 if (!Context.hasSameType(Conv->
getType(), ResultTy))
327 Context, ResultTy,
VK_PRValue, CK_IntegralCast, Conv,
329 Context.getTrivialTypeSourceInfo(ResultTy, Loc), Loc, Loc);
339 const auto *POE = dyn_cast<PseudoObjectExpr>(E);
342 const auto *DRE = dyn_cast<DeclRefExpr>(POE->getSyntacticForm());
345 const auto *
Call = dyn_cast<CallExpr>(POE->getResultExpr()->IgnoreCasts());
347 Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value;
363static std::optional<PartialDiagnosticAt>
369 EvalResult.
Diag = &Notes;
373 if (
Note.second.getDiagID() ==
374 diag::note_constexpr_bpf_preserve_ai_enumerator)
375 return std::move(
Note);
382 if (std::optional<PartialDiagnosticAt>
Note =
389 diag::warn_preserve_access_index_enumerator_not_relocated)
399 if (
auto *E = dyn_cast<Expr>(St);
440 if (
auto *E = dyn_cast<Expr>(Slot);
442 Replaced.push_back({&Slot, Slot});
455 if (
const auto *
Call = dyn_cast<CallExpr>(S);
456 Call &&
Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value)
481 Diag(
Call->getBeginLoc(), diag::note_preserve_enum_value_not_const)
482 <<
Call->getSourceRange();
483 Diag(
Call->getBeginLoc(), diag::note_preserve_enum_value_case_attr);
487 if (Replaced.empty())
492 if (ConstE->isGLValue() ||
498 for (
const auto &R : Replaced)
507 for (
auto [Slot, Ref] : Replaced)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
This file declares semantic analysis functions specific to BPF.
Enumerates target-specific builtins in their own namespaces within namespace clang.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
DeclarationNameInfo getNameInfo() const
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Decl - This represents one declaration (or definition), e.g.
An instance of this object exists for each enum constant that is defined.
This represents one expression.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Represents difference between two FPOptions values.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
ParsedAttr - Represents a syntactic attribute.
bool isPragmaClangAttribute() const
True if the attribute is specified using 'pragma clang attribute'.
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Represents a struct/union/class.
Expr * checkLocalConstantInitializer(const VarDecl *VD, Expr *Init)
void notePreserveAIEnumerator(const Expr *E)
void handlePreserveAIRecord(RecordDecl *RD)
void DiagnoseAnonymousPreserveAIEnums()
Expr * keepPreserveAIEnumeratorsConstant(Expr *E)
static bool isPreserveAIEnumeratorRef(const Expr *E)
Expr * checkAsmImmediateOperand(Expr *E)
ExprResult verifyCaseExpr(Expr *E)
Expr * BuildPreserveAIEnumeratorRef(DeclRefExpr *E)
void handlePreserveAccessIndexAttr(Decl *D, const ParsedAttr &AL)
static bool hasPreserveAIEnumeratorRef(const Stmt *S)
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
ASTContext & getASTContext() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Sema - This implements semantic analysis and AST building for C.
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
sema::FunctionScopeInfo * getCurFunction() const
Encodes a location in the source.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
const BuiltinType * getAsPlaceholderType() const
Base class for declarations which introduce a typedef-name.
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Retains information about a function, method, or block that is currently being parsed.
SmallVector< SwitchInfo, 8 > SwitchStack
SwitchStack - This is the current set of active switch statements in the block.
Defines the clang::TargetInfo interface.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
static bool isValidPreserveFieldInfoArg(Expr *Arg)
@ OK_Ordinary
An ordinary object is located at an address in memory.
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
static CastKind getEnumeratorToPointerCastKind(ASTContext &Context, const Expr *E)
static Stmt * keepEnumeratorsConstant(SemaBPF &S, Stmt *St)
static void unwrapPreserveEnumValueArg(ASTContext &Context, Expr *Arg)
@ Result
The result type of a method or function.
static bool isValidPreserveEnumValueArg(Expr *Arg)
static const CallExpr * findPreserveEnumValueCall(const Stmt *S)
static void warnEnumeratorNotRelocated(SemaBPF &S, const DeclRefExpr *DRE)
static QualType getPreserveAIEnumType(ASTContext &Context, const DeclRefExpr *E)
static bool isInSwitchCaseLabel(Sema &S)
CastKind
CastKind - The kind of operation required for a conversion.
static std::optional< PartialDiagnosticAt > getPreserveAIEnumeratorNote(ASTContext &Context, const Expr *E)
static void replaceEnumeratorRefs(Stmt *&Slot, SmallVectorImpl< std::pair< Stmt **, Stmt * > > &Replaced)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
static bool isValidPreserveTypeInfoArg(Expr *Arg)
U cast(CodeGen::Address addr)
@ Enumerator
Enumerator value with fixed underlying type.
ActionResult< Expr * > ExprResult
EvalResult is a struct with detailed info about an evaluated expression.
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Data structure used to record current or nested expression evaluation contexts.
bool IsCaseExpr
Whether evaluating an expression for a switch case label.