[clang] [BPF] Support preserve_access_index attribute for enum (PR #232498)

via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 4 21:47:54 PST 2026


================
@@ -179,10 +210,161 @@ 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();
+}
+
+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 rather than the enum type, so
+  // find its enum through the declaration context. Within the definition of
+  // the enum, e.g., A in B = A + 1, the enum is not complete yet and A must
+  // stay a constant, so it is not relocated.
+  const auto *ED = dyn_cast<EnumDecl>(Enumerator->getDeclContext());
+  if (!ED || !ED->isCompleteDefinition() ||
+      !ED->hasAttr<BPFPreserveAccessIndexAttr>())
+    return QualType();
+
+  // The relocation is matched by type name, so an anonymous enum is only
+  // supported through its typedef name.
+  if (ED->getDeclName())
+    return Context.getCanonicalTagType(ED);
+  if (const TypedefNameDecl *TD = ED->getTypedefNameForAnonDecl())
+    return Context.getTypeDeclType(TD);
+  return QualType();
+}
+
+Expr *SemaBPF::BuildPreserveAIEnumeratorRef(DeclRefExpr *E) {
+  if (SemaRef.isUnevaluatedContext())
+    return E;
+
+  ASTContext &Context = getASTContext();
+  QualType EnumTy = getPreserveAIEnumType(Context, E);
+  if (EnumTy.isNull())
+    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 the same way as the parser builds an explicit
+  // __builtin_preserve_enum_value() call, so that the two have the same AST and
+  // are handled the same, e.g., with the same diagnostics where a constant
+  // expression is required.
+  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");
+
+  // Cast the unsigned long result to long if the type of the enumerator is
+  // signed, so that, e.g., a negative value stays negative in a comparison. Do
+  // not cast it to a narrower type of the enumerator, e.g., int or char. The
+  // narrowing would be done by extra instructions after the relocated ld_imm64,
+  // e.g., r0 <<= 56; r0 s>>= 56 for char. libbpf only patches the ld_imm64, so
+  // these instructions would truncate a relocated value too big for the
+  // narrower type, e.g., if the enum is enum E : char {...} in the BPF program
+  // but enum E : long {...} in the kernel.
+  QualType ResultTy = E->getType();
+  if (Context.getTypeSize(ResultTy) < Context.getTypeSize(Context.LongTy))
+    ResultTy = ResultTy->isSignedIntegerOrEnumerationType()
+                   ? Context.LongTy
+                   : Context.UnsignedLongTy;
+  Expr *Conv = Call.get();
+  if (!Context.hasSameType(Conv->getType(), ResultTy))
+    Conv = CStyleCastExpr::Create(
+        Context, ResultTy, VK_PRValue, CK_IntegralCast, Conv,
+        /*BasePath=*/nullptr, FPOptionsOverride(),
+        Context.getTrivialTypeSourceInfo(ResultTy, Loc), Loc, Loc);
+
+  // E is the syntactic form, so the AST is printed as written. The result of
+  // the cast call is not a constant expression.
+  return PseudoObjectExpr::Create(Context, E, {Conv}, /*resultIndex=*/0);
----------------
yonghong-song wrote:

Okay, I see that. Once the previous comment is applied:
```
The parser reads every C array bound in a ConstantEvaluated context (ParseBracketDeclarator()). Same for case, bit-field widths, _Static_assert and attribute arguments. So BuildPreserveAIEnumeratorRef() knows that it is in such a context. ...
```
I cannot reproduce assertion any more. So yes, this one can be ditched.

https://github.com/llvm/llvm-project/pull/232498


More information about the cfe-commits mailing list