[clang] [BPF] Support preserve_access_index attribute for enum (PR #232498)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 8 09:21:52 PST 2026
================
@@ -179,10 +210,199 @@ void SemaBPF::handlePreserveAIRecord(RecordDecl *RD) {
}
void SemaBPF::handlePreserveAccessIndexAttr(Decl *D, const ParsedAttr &AL) {
- auto *Rec = cast<RecordDecl>(D);
- handlePreserveAIRecord(Rec);
- Rec->addAttr(::new (getASTContext())
- BPFPreserveAccessIndexAttr(getASTContext(), AL));
+ if (auto *Rec = dyn_cast<RecordDecl>(D))
+ handlePreserveAIRecord(Rec);
+ auto *A =
+ ::new (getASTContext()) BPFPreserveAccessIndexAttr(getASTContext(), AL);
+ if (auto *ED = dyn_cast<EnumDecl>(D);
+ ED && !ED->getDeclName() && !AL.isPragmaClangAttribute())
+ AnonPreserveAIEnums.insert({ED, A});
+ D->addAttr(A);
+}
+
+void SemaBPF::DiagnoseAnonymousPreserveAIEnums() {
+ for (auto [ED, A] : AnonPreserveAIEnums)
+ if (!ED->getTypedefNameForAnonDecl())
+ Diag(A->getLocation(), diag::warn_preserve_access_index_anon_enum) << A;
+ AnonPreserveAIEnums.clear();
+}
+
+// Return the enum type, or its typedef name, that the enumerator E is relocated
+// against, or a null type if E is not relocated.
+static QualType getPreserveAIEnumType(ASTContext &Context,
+ const DeclRefExpr *E) {
+ const auto *Enumerator = dyn_cast<EnumConstantDecl>(E->getDecl());
+ if (!Enumerator)
+ return QualType();
+
+ // In C, an enumerator usually has type int, not the enum type, so find the
+ // enum from its context. Within the enum's definition, e.g., A in B = A + 1,
+ // the enum is incomplete and A stays a constant.
+ const auto *ED = dyn_cast<EnumDecl>(Enumerator->getDeclContext());
+ if (!ED || !ED->isCompleteDefinition() ||
+ !ED->hasAttr<BPFPreserveAccessIndexAttr>())
+ return QualType();
+
+ // libbpf matches relocations by type name, so an anonymous enum needs a
+ // typedef name.
+ if (ED->getDeclName())
+ return Context.getCanonicalTagType(ED);
+ if (const TypedefNameDecl *TD = ED->getTypedefNameForAnonDecl())
+ return Context.getTypeDeclType(TD);
+ return QualType();
+}
+
+// Return the enumerator reference E, or, if it is relocated, a pseudo-object
+// whose semantic form is a __builtin_preserve_enum_value() call.
+Expr *SemaBPF::BuildPreserveAIEnumeratorRef(DeclRefExpr *E) {
+ if (SemaRef.isUnevaluatedContext())
+ return E;
+
+ ASTContext &Context = getASTContext();
+ QualType EnumTy = getPreserveAIEnumType(Context, E);
+ if (EnumTy.isNull())
+ return E;
+
+ // The value cannot be relocated where a constant is required: in a constant
+ // evaluated context, e.g., an array bound or a case label, or outside of a
+ // function, e.g., a global initializer. Warn, and use the enumerator's value.
+ if (SemaRef.isConstantEvaluatedContext() ||
+ SemaRef.CurContext->getRedeclContext()->isFileContext()) {
+ Diag(E->getExprLoc(),
+ diag::warn_preserve_access_index_enumerator_not_relocated)
+ << E->getDecl() << EnumTy << E->getSourceRange();
+ return E;
+ }
+
+ // Keep it a constant anywhere in an unevaluated operand, e.g., in a block
+ // literal in sizeof. TransformToPotentiallyEvaluated() relocates it when it
+ // rebuilds a variably modified operand.
+ if (llvm::any_of(SemaRef.ExprEvalContexts,
+ [](const Sema::ExpressionEvaluationContextRecord &Rec) {
+ return Rec.isUnevaluated();
+ }))
+ return E;
+
+ // Build *(enum_type *)E in the form required by
+ // __builtin_preserve_enum_value().
+ SourceLocation Loc = E->getExprLoc();
+ auto *Ref = DeclRefExpr::Create(Context, E->getQualifierLoc(),
+ SourceLocation(), E->getDecl(),
+ /*RefersToEnclosingVariableOrCapture=*/false,
+ E->getNameInfo(), E->getType(), VK_PRValue);
+ QualType PtrTy = Context.getPointerType(EnumTy);
+ Expr *Cast = CStyleCastExpr::Create(
+ Context, PtrTy, VK_PRValue, getEnumeratorToPointerCastKind(Context, Ref),
+ Ref,
+ /*BasePath=*/nullptr, FPOptionsOverride(),
+ Context.getTrivialTypeSourceInfo(PtrTy, Loc), Loc, Loc);
+ Expr *Deref = UnaryOperator::Create(
+ Context, Cast, UO_Deref, EnumTy, VK_LValue, OK_Ordinary, Loc,
+ /*CanOverflow=*/false, FPOptionsOverride());
+
+ // Flag 1 is BPF_ENUMVAL_VALUE.
+ Expr *Flag =
+ IntegerLiteral::Create(Context, llvm::APInt(32, 1), Context.IntTy, Loc);
+ Expr *Args[] = {Deref, Flag};
+
+ // Build the call as the parser builds an explicit one, so that both are
+ // handled the same.
+ LookupResult R(SemaRef,
+ &Context.Idents.get(Context.BuiltinInfo.getName(
+ BPF::BI__builtin_preserve_enum_value)),
+ Loc, Sema::LookupOrdinaryName);
+ SemaRef.LookupName(R, SemaRef.TUScope, /*AllowBuiltinCreation=*/true);
+ auto *BuiltinDecl = R.getAsSingle<FunctionDecl>();
+ assert(BuiltinDecl && "failed to find builtin declaration");
+ ExprResult Callee = SemaRef.BuildDeclarationNameExpr(
+ CXXScopeSpec(), R.getLookupNameInfo(), BuiltinDecl);
+ assert(Callee.isUsable() && "Builtin reference cannot fail");
+ ExprResult Call =
+ SemaRef.BuildCallExpr(/*Scope=*/nullptr, Callee.get(), Loc, Args, Loc);
+ assert(Call.isUsable() && "Call to builtin cannot fail");
----------------
yonghong-song wrote:
Good point. Will do.
https://github.com/llvm/llvm-project/pull/232498
More information about the cfe-commits
mailing list