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

via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 8 13:12:05 PST 2026


https://github.com/yonghong-song updated https://github.com/llvm/llvm-project/pull/232498

>From 4a2b287d690d4ce608de7d190b9831553763f136 Mon Sep 17 00:00:00 2001
From: Yonghong Song <yonghong.song at linux.dev>
Date: Thu, 5 Nov 2026 08:40:23 -0800
Subject: [PATCH] [BPF] Support preserve_access_index attribute for enum

An enum value can only be relocated with __builtin_preserve_enum_value()
or bpf_core_enum_value(), which is easy to forget. Allow the
preserve_access_index attribute on an enum, so that with -g each use of
its enumerators becomes an ENUM_VALUE relocation:

  enum cgroup_subsys_id {
    cpuset_cgrp_id = 0,
    memory_cgrp_id = 4,
  } __attribute__((preserve_access_index));

  struct css_set {
    void *subsys[10];
  } __attribute__((preserve_access_index));

  void *get_mem_css(struct css_set *cset) {
    return cset->subsys[memory_cgrp_id];
  }

  $ clang --target=bpf -O2 -g -c t.c && llvm-objdump -dr t.o
  ...
  r1 = 0x4 ll
    CO-RE <enumval_value> [8] enum cgroup_subsys_id::memory_cgrp_id = 4

This works for a named enum and for an anonymous enum with a typedef
name, with the attribute written on it or applied by #pragma clang
attribute, as in vmlinux.h. An enum defined in a struct with the
attribute does not get it from the struct. Since libbpf matches
relocations by type name, writing the attribute on an anonymous enum
without a typedef name is an error by default (-Wignored-attributes).

Sema turns such a reference into a PseudoObjectExpr whose semantic form
is a __builtin_preserve_enum_value() call cast to the type of the
enumerator, so the type of an expression does not change, and there is
no new -Wconversion or -Wint-to-pointer-cast warning. This does not
depend on -g, so a program is accepted or rejected the same with and
without -g. An enumerator in an unevaluated operand, e.g., of sizeof, or
in the argument of an explicit __builtin_preserve_enum_value() call is
not changed, so existing bpf_core_enum_value() uses keep working.
Without -g, or in a nodebug function, codegen uses the value of the
enumerator.

The relocated value is not a constant, so a condition such as
memory_cgrp_id == 4 is not folded. Where a constant is required, e.g.,
an array bound, a case label, an array designator, the initializer of a
global, static local or constexpr variable, or an "i" asm operand, the
enumerator is not relocated and its value is used. This is diagnosed by
-Wbpf-enum-not-relocated, an error by default. -Wno-error= or
#pragma clang diagnostic is the opt-out, e.g., for
__uint(type, BPF_MAP_TYPE_HASH) in a map definition with vmlinux.h.
Uses elsewhere, e.g., in a function body, are still relocated. Where a
builtin argument must be a constant, e.g., of __builtin_prefetch(), the
error has a note naming the attribute.

Sema::BuildBuiltinCallExpr() now takes an unsigned builtin ID instead of
Builtin::ID, which only has target-independent builtins, so that it can
build the call to the BPF builtin.

__BPF_FEATURE_ENUM_PRESERVE_ACCESS_INDEX is defined for any -mcpu, so
vmlinux.h can apply the attribute to enums when it is supported.
---
 clang/include/clang/Basic/Attr.td             |   2 +-
 clang/include/clang/Basic/AttrDocs.td         |  16 ++
 .../include/clang/Basic/DiagnosticASTKinds.td |   3 +
 clang/include/clang/Basic/DiagnosticGroups.td |   2 +
 .../clang/Basic/DiagnosticSemaKinds.td        |   7 +
 clang/include/clang/Sema/Sema.h               |   6 +-
 clang/include/clang/Sema/SemaBPF.h            |  12 +
 clang/lib/AST/ExprConstant.cpp                |  31 ++
 clang/lib/Basic/Targets/BPF.cpp               |   1 +
 clang/lib/CodeGen/CGExpr.cpp                  |  10 +
 clang/lib/Sema/Sema.cpp                       |   1 +
 clang/lib/Sema/SemaBPF.cpp                    | 229 ++++++++++++++-
 clang/lib/Sema/SemaCast.cpp                   |  12 +-
 clang/lib/Sema/SemaChecking.cpp               |   6 +-
 clang/lib/Sema/SemaDecl.cpp                   |   4 +
 clang/lib/Sema/SemaExpr.cpp                   |   5 +-
 clang/lib/Sema/SemaInit.cpp                   |   6 +
 clang/lib/Sema/SemaStmtAsm.cpp                |   4 +
 ...f-attr-preserve-access-index-enum-blocks.c |  26 ++
 ...attr-preserve-access-index-enum-constant.c |  50 ++++
 .../bpf-attr-preserve-access-index-enum.c     | 269 ++++++++++++++++++
 ...a-attribute-supported-attributes-list.test |   2 +-
 .../test/Preprocessor/bpf-predefined-macros.c |  11 +
 ...attr-preserve-access-index-enum-constant.c |  71 +++++
 ...tr-preserve-access-index-enum-conversion.c |  20 ++
 .../Sema/bpf-attr-preserve-access-index.c     |  76 ++++-
 .../Sema/bpf-preserve-enum-value-parity.c     |  86 ++++++
 27 files changed, 944 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/CodeGen/bpf-attr-preserve-access-index-enum-blocks.c
 create mode 100644 clang/test/CodeGen/bpf-attr-preserve-access-index-enum-constant.c
 create mode 100644 clang/test/CodeGen/bpf-attr-preserve-access-index-enum.c
 create mode 100644 clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
 create mode 100644 clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
 create mode 100644 clang/test/Sema/bpf-preserve-enum-value-parity.c

diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 24fd853a2384af..92c9b565e77f12 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2577,7 +2577,7 @@ def AMDGPUAvailableVisible : StmtAttr, TargetSpecificAttr<TargetAMDGPU> {
 def BPFPreserveAccessIndex : InheritableAttr,
                              TargetSpecificAttr<TargetBPF>  {
   let Spellings = [Clang<"preserve_access_index">];
-  let Subjects = SubjectList<[Record], ErrorDiag>;
+  let Subjects = SubjectList<[Record, Enum], ErrorDiag>;
   let Documentation = [BPFPreserveAccessIndexDocs];
   let LangOpts = [COnly];
 }
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 2300c8456ef164..dae55eaf50c1ab 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3079,6 +3079,22 @@ attribute for the BPF target. This attribute may be attached to a
 struct or union declaration, where if -g is specified, it enables
 preserving struct or union member access debuginfo indices of this
 struct or union, similar to clang `__builtin_preserve_access_index()`.
+
+The attribute may also be attached to a named enum, or an anonymous enum with
+a typedef name. A use of its enumerator is then treated like
+`__builtin_preserve_enum_value(*(enum_type *)enumerator, BPF_ENUMVAL_VALUE)`,
+so it is not a constant expression, and if -g is specified, its value is
+relocated. An enum defined in a struct or union with the attribute does not
+get the attribute.
+
+Where a constant is required, e.g., in an array bound, a case label, an array
+designator, the initializer of a global, static local or constexpr variable or
+an `"i"` operand of inline asm, the enumerator is not relocated and its value in
+the local enum is used. This is diagnosed by `-Wbpf-enum-not-relocated`, an
+error by default; `-Wno-error=` or `#pragma clang diagnostic` allows such a use.
+
+The macro `__BPF_FEATURE_ENUM_PRESERVE_ACCESS_INDEX` is defined if the
+attribute is supported on enum declarations.
   }];
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td b/clang/include/clang/Basic/DiagnosticASTKinds.td
index e9834cca42091b..9b130160ef213a 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -41,6 +41,9 @@ def note_constexpr_lshift_discards : Note<"signed left shift discards bits">;
 def note_constexpr_invalid_function : Note<
   "%select{non-constexpr|undefined}0 %select{function|constructor}1 %2 cannot "
   "be used in a constant expression">;
+def note_constexpr_bpf_preserve_ai_enumerator : Note<
+  "enumerator %0 is not a constant expression since %1 has the "
+  "'preserve_access_index' attribute">;
 def note_constexpr_invalid_inhctor : Note<
   "constructor inherited from base class %0 cannot be used in a "
   "constant expression; derived class cannot be implicitly initialized">;
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index eaf87106a2fa31..d7efccf0c87409 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -2067,3 +2067,5 @@ def UnguardedBuiltinUsageAMDGPU : DiagGroup<"amdgpu-unguarded-builtin-usage">;
 def AvailableVisibleAMDGPU : DiagGroup<"amdgpu-av">;
 
 def DynamicDebugging : DiagGroup<"dynamic-debugging">;
+
+def BPFEnumNotRelocated : DiagGroup<"bpf-enum-not-relocated">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 80de4627959c4b..9e43a41c253222 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13631,6 +13631,13 @@ def err_preserve_enum_value_invalid : Error<
   "__builtin_preserve_enum_value argument %0 invalid">;
 def err_preserve_enum_value_not_const: Error<
   "__builtin_preserve_enum_value argument %0 not a constant">;
+def warn_preserve_access_index_anon_enum : Warning<
+  "%0 attribute has no effect on an anonymous enum without a typedef name">,
+  InGroup<IgnoredAttributes>, DefaultError;
+def warn_preserve_access_index_enumerator_not_relocated : Warning<
+  "enumerator %0 is not relocated where a constant is required, although %1 "
+  "has the 'preserve_access_index' attribute">,
+  InGroup<BPFEnumNotRelocated>, DefaultError;
 
 def err_bit_cast_non_trivially_copyable : Error<
   "'__builtin_bit_cast' %select{source|destination}0 type must be trivially copyable">;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 3abbaf6b1941ec..48f98b837d9ad2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7642,8 +7642,10 @@ class Sema final : public SemaBase {
                            bool AllowRecovery = false);
 
   /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
-  //  with the specified CallArgs
-  Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
+  /// with the specified CallArgs. Id is unsigned rather than Builtin::ID, so
+  /// that it can also be a target-specific builtin ID, which is not in
+  /// Builtin::ID, e.g., BPF::BI__builtin_preserve_enum_value.
+  Expr *BuildBuiltinCallExpr(SourceLocation Loc, unsigned Id,
                              MultiExprArg CallArgs);
 
   using ADLCallKind = CallExpr::ADLCallKind;
diff --git a/clang/include/clang/Sema/SemaBPF.h b/clang/include/clang/Sema/SemaBPF.h
index d7577aea701227..16d12e21e88ef0 100644
--- a/clang/include/clang/Sema/SemaBPF.h
+++ b/clang/include/clang/Sema/SemaBPF.h
@@ -15,6 +15,7 @@
 
 #include "clang/AST/ASTFwd.h"
 #include "clang/Sema/SemaBase.h"
+#include "llvm/ADT/MapVector.h"
 
 namespace clang {
 class ParsedAttr;
@@ -27,6 +28,17 @@ class SemaBPF : public SemaBase {
 
   void handlePreserveAIRecord(RecordDecl *RD);
   void handlePreserveAccessIndexAttr(Decl *D, const ParsedAttr &AL);
+  void DiagnoseAnonymousPreserveAIEnums();
+  Expr *BuildPreserveAIEnumeratorRef(DeclRefExpr *E);
+  static bool isPreserveAIEnumeratorRef(const Expr *E);
+  void notePreserveAIEnumerator(const Expr *E);
+  Expr *checkAsmImmediateOperand(Expr *E);
+  Expr *keepPreserveAIEnumeratorsConstant(Expr *E);
+  Expr *checkLocalConstantInitializer(const VarDecl *VD, Expr *Init);
+
+private:
+  llvm::MapVector<EnumDecl *, const BPFPreserveAccessIndexAttr *>
+      AnonPreserveAIEnums;
 };
 } // namespace clang
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 57d5bb475d0f9b..647bb9c45f871a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8722,6 +8722,35 @@ static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
   return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
 }
 
+/// Diagnose a relocated BPF enumerator, i.e., of an enum with the
+/// preserve_access_index attribute, which is not a constant expression. Return
+/// true if diagnosed.
+static bool diagnoseBPFPreserveAIEnumerator(EvalInfo &Info,
+                                            const PseudoObjectExpr *E) {
+  const auto *DRE = dyn_cast<DeclRefExpr>(E->getSyntacticForm());
+  if (!DRE)
+    return false;
+  const auto *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl());
+  if (!ECD)
+    return false;
+  const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext());
+  if (!ED || !ED->hasAttr<BPFPreserveAccessIndexAttr>())
+    return false;
+
+  // An anonymous enum is only relocated through its typedef name.
+  QualType EnumTy;
+  if (ED->getDeclName())
+    EnumTy = Info.Ctx.getCanonicalTagType(ED);
+  else if (const TypedefNameDecl *TD = ED->getTypedefNameForAnonDecl())
+    EnumTy = Info.Ctx.getTypeDeclType(TD);
+  else
+    return false;
+
+  Info.FFDiag(E, diag::note_constexpr_bpf_preserve_ai_enumerator)
+      << ECD << EnumTy << E->getSourceRange();
+  return true;
+}
+
 template <class Derived>
 class ExprEvaluatorBase
   : public ConstStmtVisitor<Derived, bool> {
@@ -8972,6 +9001,8 @@ class ExprEvaluatorBase
   }
 
   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
+    if (diagnoseBPFPreserveAIEnumerator(Info, E))
+      return false;
     for (const Expr *SemE : E->semantics()) {
       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
diff --git a/clang/lib/Basic/Targets/BPF.cpp b/clang/lib/Basic/Targets/BPF.cpp
index 2c37d56186ce52..f501dd36149026 100644
--- a/clang/lib/Basic/Targets/BPF.cpp
+++ b/clang/lib/Basic/Targets/BPF.cpp
@@ -36,6 +36,7 @@ void BPFTargetInfo::getTargetDefines(const LangOptions &Opts,
                                      MacroBuilder &Builder) const {
   Builder.defineMacro("__bpf__");
   Builder.defineMacro("__BPF__");
+  Builder.defineMacro("__BPF_FEATURE_ENUM_PRESERVE_ACCESS_INDEX");
 
   std::string CPU = getTargetOpts().CPU;
   if (CPU == "probe") {
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ae5f4e723f5129..feb6a60a405214 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -7458,6 +7458,16 @@ static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
   const Expr *resultExpr = E->getResultExpr();
   LValueOrRValue result;
 
+  // Without debug info, e.g., in a nodebug function, an enumerator of a BPF
+  // preserve_access_index enum cannot be relocated, so use its value.
+  if (!forLValue && CGF.getTarget().getTriple().isBPF() &&
+      (!CGF.CGM.getCodeGenOpts().hasReducedDebugInfo() || !CGF.getDebugInfo()))
+    if (const auto *DRE = dyn_cast<DeclRefExpr>(E->getSyntacticForm());
+        DRE && isa<EnumConstantDecl>(DRE->getDecl())) {
+      result.RV = RValue::get(CGF.EmitScalarExpr(DRE));
+      return result;
+    }
+
   for (PseudoObjectExpr::const_semantics_iterator
          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
     const Expr *semantic = *i;
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index d7f51de515449a..682851e5e23188 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1331,6 +1331,7 @@ void Sema::ActOnEndOfTranslationUnit() {
 
   DiagnoseUnterminatedPragmaAlignPack();
   DiagnoseUnterminatedPragmaAttribute();
+  BPF().DiagnoseAnonymousPreserveAIEnums();
   OpenMP().DiagnoseUnterminatedOpenMPDeclareTarget();
   DiagnosePrecisionLossInComplexDivision();
   DiagnoseUnusedAPINotesSelectors();
diff --git a/clang/lib/Sema/SemaBPF.cpp b/clang/lib/Sema/SemaBPF.cpp
index a9761764bbdc67..13b486497cf6ce 100644
--- a/clang/lib/Sema/SemaBPF.cpp
+++ b/clang/lib/Sema/SemaBPF.cpp
@@ -11,10 +11,13 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Sema/SemaBPF.h"
+#include "clang/AST/ASTDiagnostic.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/TargetBuiltins.h"
+#include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/ParsedAttr.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/ADT/APSInt.h"
@@ -102,6 +105,31 @@ static bool isValidPreserveEnumValueArg(Expr *Arg) {
   return llvm::is_contained(ED->enumerators(), Enumerator);
 }
 
+// The kind of a C-style cast of the enumerator E to a pointer, as computed by
+// Sema::PrepareScalarCast().
+static CastKind getEnumeratorToPointerCastKind(ASTContext &Context,
+                                               const Expr *E) {
+  return E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)
+             ? CK_NullToPointer
+             : CK_IntegralToPointer;
+}
+
+// In __builtin_preserve_enum_value(*(<enum_type> *)<enumerator>, flag), the
+// enumerator names itself, not its value, so undo
+// BuildPreserveAIEnumeratorRef() there, as if there were no attribute.
+static void unwrapPreserveEnumValueArg(ASTContext &Context, Expr *Arg) {
+  auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
+  if (!UO || UO->getOpcode() != UO_Deref)
+    return;
+  auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
+  if (!CE || !SemaBPF::isPreserveAIEnumeratorRef(CE->getSubExpr()))
+    return;
+  auto *DRE = cast<DeclRefExpr>(
+      cast<PseudoObjectExpr>(CE->getSubExpr())->getSyntacticForm());
+  CE->setSubExpr(DRE);
+  CE->setCastKind(getEnumeratorToPointerCastKind(Context, DRE));
+}
+
 bool SemaBPF::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
                                           CallExpr *TheCall) {
   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
@@ -145,6 +173,7 @@ bool SemaBPF::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
       kind = diag::err_preserve_type_info_invalid;
     }
   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
+    unwrapPreserveEnumValueArg(Context, Arg);
     if (!isValidPreserveEnumValueArg(Arg)) {
       InvalidArg = true;
       kind = diag::err_preserve_enum_value_invalid;
@@ -167,9 +196,10 @@ bool SemaBPF::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
 }
 
 void SemaBPF::handlePreserveAIRecord(RecordDecl *RD) {
-  // Add preserve_access_index attribute to all fields and inner records.
+  // Add preserve_access_index attribute to all fields and inner records, but
+  // not inner enums, so that their enumerators stay constants.
   for (auto *D : RD->decls()) {
-    if (D->hasAttr<BPFPreserveAccessIndexAttr>())
+    if (isa<EnumDecl>(D) || D->hasAttr<BPFPreserveAccessIndexAttr>())
       continue;
 
     D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(getASTContext()));
@@ -179,10 +209,197 @@ 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};
+  Expr *Conv = SemaRef.BuildBuiltinCallExpr(
+      Loc, BPF::BI__builtin_preserve_enum_value, Args);
+
+  // Cast the unsigned long result to the type of the enumerator, normally int,
+  // so that no type changes, e.g., hash % A stays a 32-bit unsigned remainder.
+  QualType ResultTy = E->getType();
+  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.
+  return PseudoObjectExpr::Create(Context, E, {Conv}, /*resultIndex=*/0);
+}
+
+// Return whether E is an enumerator reference built by
+// BuildPreserveAIEnumeratorRef(), i.e., a pseudo-object for an enumerator whose
+// semantic form is a __builtin_preserve_enum_value() call.
+bool SemaBPF::isPreserveAIEnumeratorRef(const Expr *E) {
+  const auto *POE = dyn_cast<PseudoObjectExpr>(E);
+  if (!POE)
+    return false;
+  const auto *DRE = dyn_cast<DeclRefExpr>(POE->getSyntacticForm());
+  if (!DRE || !isa<EnumConstantDecl>(DRE->getDecl()))
+    return false;
+  const auto *Call = dyn_cast<CallExpr>(POE->getResultExpr()->IgnoreCasts());
+  return Call &&
+         Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value;
+}
+
+// If a relocated enumerator makes E non-constant, return the constant
+// evaluator's note saying so.
+static std::optional<PartialDiagnosticAt>
+getPreserveAIEnumeratorNote(ASTContext &Context, const Expr *E) {
+  if (!Context.getTargetInfo().getTriple().isBPF() || E->isValueDependent())
+    return std::nullopt;
+  SmallVector<PartialDiagnosticAt, 8> Notes;
+  Expr::EvalResult EvalResult;
+  EvalResult.Diag = &Notes;
+  if (E->EvaluateAsRValue(EvalResult, Context, /*InConstantContext=*/true))
+    return std::nullopt;
+  for (PartialDiagnosticAt &Note : Notes)
+    if (Note.second.getDiagID() ==
+        diag::note_constexpr_bpf_preserve_ai_enumerator)
+      return std::move(Note);
+  return std::nullopt;
+}
+
+// After an error that E is not a constant, emit the note if a relocated
+// enumerator is the reason.
+void SemaBPF::notePreserveAIEnumerator(const Expr *E) {
+  if (std::optional<PartialDiagnosticAt> Note =
+          getPreserveAIEnumeratorNote(getASTContext(), E))
+    Diag(Note->first, Note->second);
+}
+
+// Replace each relocated enumerator in St with its DeclRefExpr, which has the
+// same type and value kind, and warn that it is not relocated.
+static Stmt *keepEnumeratorsConstant(SemaBPF &S, Stmt *St) {
+  if (!St)
+    return St;
+  if (auto *E = dyn_cast<Expr>(St);
+      E && SemaBPF::isPreserveAIEnumeratorRef(E)) {
+    auto *DRE =
+        cast<DeclRefExpr>(cast<PseudoObjectExpr>(E)->getSyntacticForm());
+    S.Diag(DRE->getExprLoc(),
+           diag::warn_preserve_access_index_enumerator_not_relocated)
+        << DRE->getDecl() << getPreserveAIEnumType(S.getASTContext(), DRE)
+        << DRE->getSourceRange();
+    return DRE;
+  }
+  for (Stmt *&Child : St->children())
+    Child = keepEnumeratorsConstant(S, Child);
+  return St;
+}
+
+// E must be a constant, e.g., an array designator, so keep its enumerators
+// constants and warn.
+Expr *SemaBPF::keepPreserveAIEnumeratorsConstant(Expr *E) {
+  return cast<Expr>(keepEnumeratorsConstant(*this, E));
+}
+
+// An asm operand E such as "i" must be a constant. If a relocated enumerator
+// makes it non-constant, keep its enumerators constants and warn.
+Expr *SemaBPF::checkAsmImmediateOperand(Expr *E) {
+  if (!getPreserveAIEnumeratorNote(getASTContext(), E))
+    return E;
+  return keepPreserveAIEnumeratorsConstant(E);
+}
+
+// The initializer of a static or constexpr local variable must be a constant,
+// so keep its enumerators constants and warn.
+Expr *SemaBPF::checkLocalConstantInitializer(const VarDecl *VD, Expr *Init) {
+  if (!VD->isLocalVarDecl() || (!VD->isStaticLocal() && !VD->isConstexpr()))
+    return Init;
+  return keepPreserveAIEnumeratorsConstant(Init);
 }
 
 } // namespace clang
diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index 825a98f3882ec2..cb169c3fc65f7e 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -24,6 +24,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/SemaAMDGPU.h"
+#include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaCUDA.h"
 #include "clang/Sema/SemaHLSL.h"
 #include "clang/Sema/SemaObjC.h"
@@ -2262,12 +2263,11 @@ static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
   // Not warning on reinterpret_cast, boolean, constant expressions, etc
   // are not explicit design choices, but consistent with GCC's behavior.
   // Feel free to modify them if you've reason/evidence for an alternative.
-  if (CStyle && SrcType->isIntegralType(Self.Context)
-      && !SrcType->isBooleanType()
-      && !SrcType->isEnumeralType()
-      && !SrcExpr->isIntegerConstantExpr(Self.Context)
-      && Self.Context.getTypeSize(DestType) >
-         Self.Context.getTypeSize(SrcType)) {
+  if (CStyle && SrcType->isIntegralType(Self.Context) &&
+      !SrcType->isBooleanType() && !SrcType->isEnumeralType() &&
+      !SrcExpr->isIntegerConstantExpr(Self.Context) &&
+      !SemaBPF::isPreserveAIEnumeratorRef(SrcExpr->IgnoreParens()) &&
+      Self.Context.getTypeSize(DestType) > Self.Context.getTypeSize(SrcType)) {
     // Separate between casts to void* and non-void* pointers.
     // Some APIs use (abuse) void* for something like a user context,
     // and often that value is an integer even if it isn't a pointer itself.
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 4b9c1d187dfeb9..6b6a27836c3c56 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -7073,8 +7073,10 @@ bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
   if (!R) {
     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
     auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
-    return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
-           << FDecl->getDeclName() << Arg->getSourceRange();
+    Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
+        << FDecl->getDeclName() << Arg->getSourceRange();
+    BPF().notePreserveAIEnumerator(Arg);
+    return true;
   }
   Result = *R;
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index d4fbf04ee284af..5d8bc3efb38b71 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -48,6 +48,7 @@
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaAMDGPU.h"
 #include "clang/Sema/SemaARM.h"
+#include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaCUDA.h"
 #include "clang/Sema/SemaHLSL.h"
 #include "clang/Sema/SemaInternal.h"
@@ -14325,6 +14326,9 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
     if (!HLSL().handleInitialization(VDecl, Init))
       return;
 
+  if (Context.getTargetInfo().getTriple().isBPF())
+    Init = BPF().checkLocalConstantInitializer(VDecl, Init);
+
   // Get the decls type and save a reference for later, since
   // CheckInitializerTypes may change it.
   QualType DclT = VDecl->getType(), SavT = DclT;
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 5c3541cfab0187..0ce88158cf486f 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -55,6 +55,7 @@
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaAMDGPU.h"
 #include "clang/Sema/SemaARM.h"
+#include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaCUDA.h"
 #include "clang/Sema/SemaFixItUtils.h"
 #include "clang/Sema/SemaHLSL.h"
@@ -3686,6 +3687,8 @@ ExprResult Sema::BuildDeclarationNameExpr(
   // diagnostics).
   if (VD->isInvalidDecl() && E)
     return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
+  if (isa<EnumConstantDecl>(VD) && Context.getTargetInfo().getTriple().isBPF())
+    return BPF().BuildPreserveAIEnumeratorRef(E);
   return E;
 }
 
@@ -7245,7 +7248,7 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
                                ExecConfig, IsExecConfig);
 }
 
-Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
+Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, unsigned Id,
                                  MultiExprArg CallArgs) {
   std::string Name = Context.BuiltinInfo.getName(Id);
   LookupResult R(*this, &Context.Idents.get(Name), Loc,
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 2e3c6309fec20e..78db959bc78264 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -28,6 +28,7 @@
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Ownership.h"
+#include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaHLSL.h"
 #include "clang/Sema/SemaObjC.h"
 #include "llvm/ADT/APInt.h"
@@ -3673,6 +3674,11 @@ static ExprResult
 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
   SourceLocation Loc = Index->getBeginLoc();
 
+  // An array designator must be a constant, so keep BPF enumerators in Index
+  // constants.
+  if (S.Context.getTargetInfo().getTriple().isBPF())
+    Index = S.BPF().keepPreserveAIEnumeratorsConstant(Index);
+
   // Make sure this is an integer constant expression.
   ExprResult Result =
       S.VerifyIntegerConstantExpression(Index, &Value, AllowFoldKind::Allow);
diff --git a/clang/lib/Sema/SemaStmtAsm.cpp b/clang/lib/Sema/SemaStmtAsm.cpp
index bf460ebe75ef10..51961490e00acc 100644
--- a/clang/lib/Sema/SemaStmtAsm.cpp
+++ b/clang/lib/Sema/SemaStmtAsm.cpp
@@ -20,6 +20,7 @@
 #include "clang/Sema/Ownership.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
+#include "clang/Sema/SemaBPF.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSet.h"
@@ -449,6 +450,9 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
 
       InputExpr = Exprs[i] = Result.get();
 
+      if (!Info.allowsRegister() && !Info.allowsMemory())
+        InputExpr = Exprs[i] = BPF().checkAsmImmediateOperand(InputExpr);
+
       if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
         if (!InputExpr->isValueDependent()) {
           Expr::EvalResult EVResult;
diff --git a/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-blocks.c b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-blocks.c
new file mode 100644
index 00000000000000..746cd8d250512c
--- /dev/null
+++ b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-blocks.c
@@ -0,0 +1,26 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -fblocks -debug-info-kind=limited -emit-llvm -disable-llvm-passes %s -o - | FileCheck %s
+
+// An enumerator in a block literal in sizeof is relocated only when the
+// variably modified operand is rebuilt as potentially evaluated.
+enum e1 { E1_A = 4 } __attribute__((preserve_access_index));
+
+// CHECK: @[[E1_A:[0-9]+]] = private unnamed_addr constant [7 x i8] c"E1_A:4\00"
+
+unsigned long test1(int n) {
+  return sizeof(*(int (*)[n])(^{ return (char *)0 + E1_A; })());
+}
+
+// CHECK: define internal ptr @__test1_block_invoke(
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[E1_A]], i64 1)
+
+// A static local variable needs a constant initializer, and a block literal is
+// one. Its body runs only when the block is called, so the enumerator there is
+// still relocated.
+int test2(void) {
+  static int (^b)(void) = ^{ return (int)E1_A; };
+  return b();
+}
+
+// CHECK: define internal i32 @_block_invoke(
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1)
diff --git a/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-constant.c b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-constant.c
new file mode 100644
index 00000000000000..dda039b33114ca
--- /dev/null
+++ b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-constant.c
@@ -0,0 +1,50 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -emit-llvm -disable-llvm-passes \
+// RUN:   -Wno-bpf-enum-not-relocated %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple bpf -emit-llvm -disable-llvm-passes \
+// RUN:   -Wno-bpf-enum-not-relocated %s -o - \
+// RUN:   | FileCheck --check-prefix=NODBG --implicit-check-not=@llvm.bpf.preserve.enum.value %s
+
+// With -Wno-bpf-enum-not-relocated, an enumerator of an enum with the
+// preserve_access_index attribute is a constant where a constant is required,
+// and its value in the local enum is used. Elsewhere, it is still relocated,
+// unless there is no -g to relocate against (NODBG).
+enum e1 { E1_A = 1, E1_B = 2 } __attribute__((preserve_access_index));
+
+struct ops { unsigned long flags; };
+
+// CHECK-DAG: @arr = global [2 x i32] zeroinitializer
+int arr[E1_A + 1];
+// CHECK-DAG: @ops = global %struct.ops { i64 2 }
+struct ops ops = { .flags = E1_B };
+// CHECK-DAG: @locals.s = internal global i32 2
+// CHECK-DAG: @__const.locals.a = private unnamed_addr constant [4 x i32] [i32 0, i32 0, i32 1, i32 0]
+// CHECK-DAG: @[[E1_A:[0-9]+]] = private unnamed_addr constant [7 x i8] c"E1_A:1\00"
+
+int test(int x) {
+  asm volatile("r0 = %0" :: "i"(E1_B) : "r0");
+  return x == E1_B;
+}
+
+// CHECK-LABEL: define dso_local i32 @test(
+// CHECK: call void asm sideeffect "r0 = $0", "i,~{r0}"(i32 2)
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(
+
+// NODBG-LABEL: define dso_local i32 @test(
+// NODBG: icmp eq i32 %{{[0-9a-z]+}}, 2
+
+int locals(void) {
+  static int s = E1_B;
+  int a[4] = {[E1_B] = 1};
+  int l = E1_A;
+  return s + a[0] + l;
+}
+
+// CHECK-LABEL: define dso_local i32 @locals(
+// CHECK: call void @llvm.memcpy.{{.*}}(ptr {{.*}}, ptr {{.*}}@__const.locals.a
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[E1_A]], i64 1)
+// CHECK-NOT: call i64 @llvm.bpf.preserve.enum.value(
+// CHECK: ret i32
+
+// NODBG-LABEL: define dso_local i32 @locals(
+// NODBG: store i32 1, ptr %l,
diff --git a/clang/test/CodeGen/bpf-attr-preserve-access-index-enum.c b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum.c
new file mode 100644
index 00000000000000..56fc9fae27b8e2
--- /dev/null
+++ b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum.c
@@ -0,0 +1,269 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -emit-llvm -debug-info-kind=limited -disable-llvm-passes \
+// RUN:   -Wno-error=ignored-attributes -verify %s -o - | FileCheck %s
+
+#define __reloc__ __attribute__((preserve_access_index))
+
+enum AA { VAL1 = -100 };
+enum e1 { E1_A = 1, E1_C = 10 } __reloc__;
+typedef enum { E2_A = 3 } __reloc__ e2;
+enum { E3_A = 4 } __reloc__; // expected-warning {{'preserve_access_index' attribute has no effect on an anonymous enum without a typedef name}}
+struct s {
+  enum e4 { E4_A = 5 } a;
+  enum e6 { E6_A = 6 } __reloc__ b;
+} __reloc__;
+enum s64 { S64_BIG = 0x100000000, S64_NEG = -5 } __reloc__;
+enum u64 { U64_BIG = 0xffffffff80000000 } __reloc__;
+enum e5 { E5_Z = 0 } __reloc__;
+
+// CHECK: @[[E1_C:[0-9]+]] = private unnamed_addr constant [8 x i8] c"E1_C:10\00"
+// CHECK: @[[E2_A:[0-9]+]] = private unnamed_addr constant [7 x i8] c"E2_A:3\00"
+// CHECK: @[[E6_A:[0-9]+]] = private unnamed_addr constant [7 x i8] c"E6_A:6\00"
+// CHECK: @[[S64_BIG:[0-9]+]] = private unnamed_addr constant [19 x i8] c"S64_BIG:4294967296\00"
+// CHECK: @[[S64_NEG:[0-9]+]] = private unnamed_addr constant [11 x i8] c"S64_NEG:-5\00"
+// CHECK: @[[U64_BIG:[0-9]+]] = private unnamed_addr constant [20 x i8] c"U64_BIG:-2147483648\00"
+
+// With or without __builtin_preserve_access_index(), an enumerator is
+// relocated. An enum in a struct does not get the struct's attribute, so E4_A
+// is a constant, but E6_A, whose enum has its own attribute, is relocated.
+int test1(int x) {
+  return (x == E1_C) + __builtin_preserve_access_index(E2_A) + (E4_A) + E6_A;
+}
+
+// CHECK: define dso_local i32 @test1
+// CHECK: [[X:%[0-9a-z]+]] = load i32, ptr %x.addr
+// CHECK-NEXT: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[E1_C]], i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1:[0-9]+]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: icmp eq i32 [[X]], [[T]]
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[E2_A]], i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E2:[0-9]+]]
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: add nsw i32 %{{[0-9a-z]+}}, 5
+// CHECK-NEXT: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[E6_A]], i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E6:[0-9]+]]
+
+// A condition using an enumerator is not folded.
+int test2(int x) {
+  if (E1_C == 10)
+    x++;
+  return x;
+}
+
+// CHECK: define dso_local i32 @test2
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: icmp eq i32 [[T]], 10
+
+// Local aggregates initialized with the enumerators are not constant
+// initialized.
+struct key { int a; int b; };
+void use(void *);
+void test3(void) {
+  struct key k = { E1_A, 2 };
+  long arr[4] = { 1, 2, 3, E1_C };
+  use(&k);
+  use(arr);
+}
+
+// CHECK: define dso_local void @test3
+// CHECK-NOT: memcpy
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK-NOT: memcpy
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK-NOT: memcpy
+// CHECK: ret void
+
+// Enumerators of an enum without the attribute, of an anonymous enum without
+// typedef name, and in unevaluated operands keep their compile-time value.
+int test4(int x) {
+  return x + VAL1 + E3_A + sizeof(E1_C);
+}
+
+// CHECK: define dso_local i32 @test4
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: add nsw i32 %{{[0-9a-z]+}}, -100
+// CHECK-NEXT: add nsw i32 %{{[0-9a-z]+}}, 4
+// CHECK: add i64 %{{[0-9a-z]+}}, 4
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: ret i32
+
+// Enumerators with 64-bit values are relocated without truncation, since they
+// have type long or unsigned long.
+long test5(void) {
+  return S64_BIG + S64_NEG;
+}
+
+// CHECK: define dso_local i64 @test5
+// CHECK: [[V1:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[S64_BIG]], i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[S64:[0-9]+]]
+// CHECK: [[V2:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[S64_NEG]], i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[S64]]
+// CHECK: [[ADD:%[0-9a-z]+]] = add nsw i64 [[V1]], [[V2]]
+// CHECK: ret i64 [[ADD]]
+
+unsigned long test6(void) {
+  return U64_BIG;
+}
+
+// CHECK: define dso_local i64 @test6
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @[[U64_BIG]], i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[U64:[0-9]+]]
+// CHECK: ret i64 [[V]]
+
+// Local const variables initialized with the enumerators are not constant
+// folded.
+int test7(int x) {
+  const int k = E1_C;
+  const int k2 = k + 1;
+  const struct key kk = { E1_A, 2 };
+  if (k2 == 11)
+    x++;
+  return x + k + kk.a;
+}
+
+// CHECK: define dso_local i32 @test7
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK: store i32 [[T]], ptr %k,
+// CHECK: [[K:%[0-9a-z]+]] = load i32, ptr %k,
+// CHECK: add nsw i32 [[K]], 1
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK: [[K2:%[0-9a-z]+]] = load i32, ptr %k2,
+// CHECK: icmp eq i32 [[K2]], 11
+// CHECK: load i32, ptr %k,
+// CHECK: load i32, ptr %a{{[0-9]+}},
+// CHECK: ret i32
+
+// A conditional operator with relocated enumerators uses control flow, not a
+// select, since the backend cannot relocate a select of two relocations.
+int test8(int x) {
+  return x ? E1_A : E1_C;
+}
+
+// CHECK: define dso_local i32 @test8
+// CHECK: br i1 %{{[0-9a-z]+}}, label %cond.true, label %cond.false
+// CHECK: cond.true:
+// CHECK-NEXT: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK: cond.false:
+// CHECK-NEXT: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK: cond.end:
+// CHECK-NEXT: phi i32
+// CHECK-NOT: select
+// CHECK: ret i32
+
+// Outside the argument of __builtin_preserve_enum_value(), an enumerator cast
+// to a pointer to its enum is relocated like any other use. There is no
+// -Wint-to-pointer-cast warning, as without the attribute (checked by -verify).
+enum e1 *test9(void) {
+  return (enum e1 *)E1_C;
+}
+
+// CHECK: define dso_local ptr @test9
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[S:%[0-9a-z]+]] = sext i32 [[T]] to i64
+// CHECK-NEXT: inttoptr i64 [[S]] to ptr
+
+// Only the enumerator in the argument of __builtin_preserve_enum_value() is
+// not relocated, including an enumerator with value 0 and a typedef'd enum.
+unsigned long test10(void) {
+  return __builtin_preserve_enum_value(*(enum e5 *)E5_Z, 1) +
+         __builtin_preserve_enum_value(*(e2 *)E2_A, 0) +
+         (unsigned long)(void *)E5_Z;
+}
+
+// CHECK: define dso_local i64 @test10
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E5:[0-9]+]]
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 0), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E2]]
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E5]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[S:%[0-9a-z]+]] = sext i32 [[T]] to i64
+// CHECK-NEXT: inttoptr i64 [[S]] to ptr
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: ret i64
+
+// A relocated enumerator is converted to its own type, here the enum type
+// with a fixed underlying type, as without the attribute.
+enum c8 : signed char { C8_NEG = -1 } __reloc__;
+enum u8 : unsigned char { U8_A = 200 } __reloc__;
+
+long test11(void) {
+  return C8_NEG;
+}
+
+// CHECK: define dso_local i64 @test11
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[C8:[0-9]+]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i8
+// CHECK-NEXT: [[S:%[0-9a-z]+]] = sext i8 [[T]] to i64
+// CHECK-NEXT: ret i64 [[S]]
+
+int test12(unsigned long x) {
+  return x < U8_A;
+}
+
+// CHECK: define dso_local i32 @test12
+// CHECK: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[U8:[0-9]+]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i8
+// CHECK-NEXT: [[Z:%[0-9a-z]+]] = zext i8 [[T]] to i64
+// CHECK-NEXT: icmp ult i64 %{{[0-9a-z]+}}, [[Z]]
+
+// A relocated enumerator of type int keeps that type, so hash % E1_C is an
+// unsigned 32-bit remainder, which does not need -mcpu=v4 as a signed one would.
+unsigned test13(unsigned hash) {
+  return hash % E1_C;
+}
+
+// CHECK: define dso_local i32 @test13
+// CHECK: [[H:%[0-9a-z]+]] = load i32, ptr %hash.addr
+// CHECK-NEXT: [[V:%[0-9a-z]+]] = call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E1]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: urem i32 [[H]], [[T]]
+
+// In a nodebug function, there is no debug info to relocate against, so the
+// value of the enumerator is used, as for a struct with the attribute.
+__attribute__((nodebug)) int test14(int x) {
+  return x + E1_C;
+}
+
+// CHECK: define dso_local i32 @test14
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: add nsw i32 %{{[0-9a-z]+}}, 10
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: ret i32
+
+// A named enum and an anonymous enum with a typedef name get the attribute
+// from #pragma clang attribute, and an enum gets it from a forward
+// declaration, so their enumerators are relocated.
+#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = any(record, enum))
+enum e7 { E7_A = 7 };
+typedef enum { E8_A = 8 } e8;
+#pragma clang attribute pop
+enum __reloc__ e9;
+enum e9 { E9_A = 9 };
+
+int test15(int x) {
+  return x + E7_A + E8_A + E9_A;
+}
+
+// CHECK: define dso_local i32 @test15
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E7:[0-9]+]]
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E8:[0-9]+]]
+// CHECK: call i64 @llvm.bpf.preserve.enum.value(i32 {{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}}, !llvm.preserve.access.index ![[E9:[0-9]+]]
+// CHECK: ret i32
+
+// The value of a relocated enumerator is not known at compile time, so
+// __builtin_constant_p() of it is 0, unlike for an enum without the attribute.
+int test16(void) {
+  return __builtin_constant_p(E1_C) * 10 + __builtin_constant_p(VAL1);
+}
+
+// CHECK: define dso_local i32 @test16
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: ret i32 1
+
+// CHECK-DAG: ![[E1]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e1"
+// CHECK-DAG: ![[E2]] = !DIDerivedType(tag: DW_TAG_typedef, name: "e2"
+// CHECK-DAG: ![[E6]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e6"
+// CHECK-DAG: ![[S64]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "s64"{{.*}}, size: 64,
+// CHECK-DAG: ![[U64]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "u64"{{.*}}, size: 64,
+// CHECK-DAG: ![[E5]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e5"
+// CHECK-DAG: ![[C8]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "c8"
+// CHECK-DAG: ![[U8]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "u8"
+// CHECK-DAG: ![[E7]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e7"
+// CHECK-DAG: ![[E8]] = !DIDerivedType(tag: DW_TAG_typedef, name: "e8"
+// CHECK-DAG: ![[E9]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e9"
diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index 8f8c1aa3d3f9cd..a228186ea9fdb2 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -23,7 +23,7 @@
 // CHECK-NEXT: Availability ((SubjectMatchRule_record, SubjectMatchRule_enum, SubjectMatchRule_enum_constant, SubjectMatchRule_field, SubjectMatchRule_function, SubjectMatchRule_namespace, SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, SubjectMatchRule_record, SubjectMatchRule_type_alias, SubjectMatchRule_variable))
 // CHECK-NEXT: AvailableOnlyInDefaultEvalMethod (SubjectMatchRule_type_alias)
 // CHECK-NEXT: BPFFastCall (SubjectMatchRule_hasType_functionType)
-// CHECK-NEXT: BPFPreserveAccessIndex (SubjectMatchRule_record)
+// CHECK-NEXT: BPFPreserveAccessIndex (SubjectMatchRule_record, SubjectMatchRule_enum)
 // CHECK-NEXT: BPFPreserveStaticOffset (SubjectMatchRule_record)
 // CHECK-NEXT: BTFDeclTag (SubjectMatchRule_variable, SubjectMatchRule_function, SubjectMatchRule_record, SubjectMatchRule_field, SubjectMatchRule_type_alias)
 // CHECK-NEXT: BuiltinAlias (SubjectMatchRule_function)
diff --git a/clang/test/Preprocessor/bpf-predefined-macros.c b/clang/test/Preprocessor/bpf-predefined-macros.c
index f89e04ae6327af..0a144cdab05f25 100644
--- a/clang/test/Preprocessor/bpf-predefined-macros.c
+++ b/clang/test/Preprocessor/bpf-predefined-macros.c
@@ -92,6 +92,9 @@ int ab;
 #if __BPF_CPU_VERSION__ < 5 && defined(__BPF_FEATURE_HMUL)
 #error HMUL requires CPU v5 or later
 #endif
+#ifdef __BPF_FEATURE_ENUM_PRESERVE_ACCESS_INDEX
+int ac;
+#endif
 
 // CHECK: int b;
 // CHECK: int c;
@@ -169,6 +172,14 @@ int ab;
 
 // CPU_V5: int ab;
 
+// CPU_V1: int ac;
+// CPU_V2: int ac;
+// CPU_V3: int ac;
+// CPU_V4: int ac;
+// CPU_V5: int ac;
+
 // CPU_GENERIC: int g;
+// CPU_GENERIC: int ac;
 
 // CPU_PROBE: int f;
+// CPU_PROBE: int ac;
diff --git a/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c b/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
new file mode 100644
index 00000000000000..26cdc0fc939022
--- /dev/null
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=err %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=warn \
+// RUN:   -Wno-error=bpf-enum-not-relocated %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=none \
+// RUN:   -Wno-bpf-enum-not-relocated %s
+
+// Where a constant is required, an enumerator of an enum with the
+// preserve_access_index attribute is not relocated, and its value is used.
+// This is diagnosed with -Wbpf-enum-not-relocated, an error by default, which
+// -Wno-error=, -Wno- or #pragma clang diagnostic opts out of.
+
+// none-no-diagnostics
+
+enum bpf_map_type { BPF_MAP_TYPE_UNSPEC, BPF_MAP_TYPE_HASH } __attribute__((preserve_access_index));
+enum ops_flags { OPS_ENQ_LAST = 2 } __attribute__((preserve_access_index));
+
+#define __uint(name, val) int (*name)[val]
+
+struct {
+  __uint(type, BPF_MAP_TYPE_HASH); // err-error {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}} \
+                                   // warn-warning {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}}
+} m;
+
+struct ops { unsigned long flags; };
+struct ops ops = { .flags = OPS_ENQ_LAST }; // err-error {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}} \
+                                            // warn-warning {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}}
+
+int f(int x) {
+  asm volatile("r0 = %0" :: "i"(OPS_ENQ_LAST) : "r0"); // err-error {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}} \
+                                                       // warn-warning {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}}
+  // Relocated, so not diagnosed.
+  return x == BPF_MAP_TYPE_HASH;
+}
+
+// In a function, the initializer of a static local variable and an array
+// designator are required to be constants too. A constexpr local variable is
+// checked in bpf-preserve-enum-value-parity.c.
+int locals(void) {
+  static int s = OPS_ENQ_LAST; // err-error {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}} \
+                               // warn-warning {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}}
+  static struct ops so = { .flags = OPS_ENQ_LAST }; // err-error {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}} \
+                                                    // warn-warning {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}}
+  int a[4] = {[BPF_MAP_TYPE_HASH] = 1}; // err-error {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}} \
+                                        // warn-warning {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}}
+  int r[4] = {[BPF_MAP_TYPE_HASH ... OPS_ENQ_LAST] = 1}; // err-error {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}} \
+                                                         // warn-warning {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}} \
+                                                         // err-error {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}} \
+                                                         // warn-warning {{enumerator 'OPS_ENQ_LAST' is not relocated where a constant is required, although 'enum ops_flags' has the 'preserve_access_index' attribute}}
+  static int sa[4] = {[BPF_MAP_TYPE_HASH] = 1}; // err-error {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}} \
+                                                // warn-warning {{enumerator 'BPF_MAP_TYPE_HASH' is not relocated where a constant is required, although 'enum bpf_map_type' has the 'preserve_access_index' attribute}}
+  // Relocated, so not diagnosed.
+  int l = OPS_ENQ_LAST;
+  return s + (int)so.flags + a[0] + r[0] + sa[0] + l;
+}
+
+int locals_ignored(void) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wbpf-enum-not-relocated"
+  static int s = OPS_ENQ_LAST;
+  int a[4] = {[BPF_MAP_TYPE_HASH] = 1};
+#pragma clang diagnostic pop
+  return s + a[0];
+}
+
+// No diagnostic in a region where the warning is ignored.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wbpf-enum-not-relocated"
+struct {
+  __uint(type, BPF_MAP_TYPE_HASH);
+} m2;
+#pragma clang diagnostic pop
diff --git a/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c b/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
new file mode 100644
index 00000000000000..dd070b5f6683f4
--- /dev/null
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-conversion.c
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -Wconversion -verify %s
+// RUN: %clang_cc1 -triple bpf -fsyntax-only -Wconversion -verify %s
+
+// A relocated enumerator is converted from the unsigned long result of
+// __builtin_preserve_enum_value() to its own type, e.g., int. The user does not
+// write that conversion, so -Wconversion, e.g., -Wsign-conversion or
+// -Wshorten-64-to-32, must not warn about it.
+enum E { A = 4 } __attribute__((preserve_access_index));
+enum L { BIG = 0x100000000L } __attribute__((preserve_access_index));
+enum U : unsigned char { UC = 4 } __attribute__((preserve_access_index));
+
+unsigned long big(void) { return BIG; }
+unsigned long uc(void) { return UC; }
+
+// The enumerator has type int, as without the attribute, so converting it to
+// int is not diagnosed, unlike an explicit __builtin_preserve_enum_value() call.
+int narrow(void) { int x = A; return x; }
+int narrow_builtin(void) {
+  return __builtin_preserve_enum_value(*(enum E *)A, 1); // expected-warning {{implicit conversion loses integer precision: 'unsigned long' to 'int'}}
+}
diff --git a/clang/test/Sema/bpf-attr-preserve-access-index.c b/clang/test/Sema/bpf-attr-preserve-access-index.c
index 34b8c917febf54..d166a67aae6a09 100644
--- a/clang/test/Sema/bpf-attr-preserve-access-index.c
+++ b/clang/test/Sema/bpf-attr-preserve-access-index.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -x c -triple bpf-pc-linux-gnu -dwarf-version=4 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -triple bpf-pc-linux-gnu -debug-info-kind=limited -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -triple bpf-pc-linux-gnu -fsyntax-only -verify %s
 
 #define __reloc__ __attribute__((preserve_access_index))
 #define __err_reloc__ __attribute__((preserve_access_index(0)))
@@ -36,13 +37,78 @@ struct p {
   int a;
 };
 
-int a __reloc__; // expected-error {{'preserve_access_index' attribute only applies to structs, unions, and classes}}
-struct s *p __reloc__; // expected-error {{'preserve_access_index' attribute only applies to structs, unions, and classes}}
+int a __reloc__; // expected-error {{'preserve_access_index' attribute only applies to structs, unions, classes, and enums}}
+struct s *p __reloc__; // expected-error {{'preserve_access_index' attribute only applies to structs, unions, classes, and enums}}
 
-void invalid1(const int __reloc__ *arg) {} // expected-error {{'preserve_access_index' attribute only applies to structs, unions, and classes}}
-void invalid2(void) { const int __reloc__ *arg; } // expected-error {{'preserve_access_index' attribute only applies to structs, unions, and classes}}
+void invalid1(const int __reloc__ *arg) {} // expected-error {{'preserve_access_index' attribute only applies to structs, unions, classes, and enums}}
+void invalid2(void) { const int __reloc__ *arg; } // expected-error {{'preserve_access_index' attribute only applies to structs, unions, classes, and enums}}
 int valid3(struct t4 *arg) { return arg->a + arg->b[3] + arg->c + arg->d; }
 int valid4(void *arg) {
   struct local_t { int a; int b; } __reloc__;
   return ((struct local_t *)arg)->b;
 }
+
+enum e1 { E1_A, E1_B } __reloc__;
+enum __reloc__ e2 { E2_A };
+typedef enum { E3_A } __reloc__ e3;
+enum e4 { E4_A __reloc__ }; // expected-error {{'preserve_access_index' attribute only applies to structs, unions, classes, and enums}}
+int valid5(void) { return E1_B + E2_A + E3_A; }
+
+// An anonymous enum without typedef name cannot be relocated.
+enum { A1 } __reloc__; // expected-error {{'preserve_access_index' attribute has no effect on an anonymous enum without a typedef name}}
+typedef enum { A3 } __reloc__ *t3p; // expected-error {{'preserve_access_index' attribute has no effect on an anonymous enum without a typedef name}}
+enum __reloc__ { A9 } __reloc__; // expected-error {{'preserve_access_index' attribute has no effect on an anonymous enum without a typedef name}}
+#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = enum)
+enum { A10 } __reloc__; // expected-error {{'preserve_access_index' attribute has no effect on an anonymous enum without a typedef name}}
+#pragma clang attribute pop
+
+// No diagnostic with a typedef name, in a struct with the attribute, or with
+// #pragma clang attribute.
+typedef enum __reloc__ { A6 } t6;
+struct s7 { enum { A7 } f; } __reloc__;
+#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = enum)
+enum { A8 };
+#pragma clang attribute pop
+int valid6(void) { return A6 + A7 + A8; }
+
+// With #pragma clang attribute, an enum defined in a struct gets the
+// attribute.
+#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = any(record, enum))
+struct s10 { enum e12 { E12_A } f; };
+#pragma clang attribute pop
+_Static_assert(E12_A == 0, ""); // expected-error {{enumerator 'E12_A' is not relocated where a constant is required, although 'enum e12' has the 'preserve_access_index' attribute}}
+
+// An array bound in a function, or in the operand of sizeof or typeof, is
+// kept a constant. Neither becomes variably modified.
+int local_array(int i) {
+  int a[E1_B]; // expected-error {{enumerator 'E1_B' is not relocated where a constant is required, although 'enum e1' has the 'preserve_access_index' attribute}}
+  a[i] = 1;
+  return a[0];
+}
+unsigned long vm_operand(void *p) {
+  typeof(*(int (*)[E1_B])p) *q = p; // expected-error {{enumerator 'E1_B' is not relocated where a constant is required, although 'enum e1' has the 'preserve_access_index' attribute}}
+  return sizeof(*(int (*)[E1_B])p) + sizeof(*q); // expected-error {{enumerator 'E1_B' is not relocated where a constant is required, although 'enum e1' has the 'preserve_access_index' attribute}}
+}
+enum e7 { E7_A = A6 }; // expected-error {{enumerator 'A6' is not relocated where a constant is required, although 't6' has the 'preserve_access_index' attribute}}
+
+// An enumerator referenced in the definition of its enum, in an unevaluated
+// operand, or of an anonymous enum without a typedef name, is not relocated.
+enum __reloc__ e10 { E10_A = 1, E10_B = E10_A + 1 };
+_Static_assert(sizeof(E1_B) == sizeof(int), "");
+int g4 = A1 + A7 + A8;
+
+// Only the argument of __builtin_preserve_enum_value() is checked as before.
+unsigned long casts(void) {
+  unsigned long r = __builtin_preserve_enum_value(*(int *)E1_A, 1); // expected-error {{__builtin_preserve_enum_value argument 1 invalid}}
+  r += __builtin_preserve_enum_value(*(enum e1 *)(E1_A), 1); // expected-error {{__builtin_preserve_enum_value argument 1 invalid}}
+  return r;
+}
+
+// An inline asm operand that can only be an immediate is kept a constant only
+// if a relocated enumerator makes it non-constant.
+void asm_imm(void) {
+  asm volatile("r0 = %0" :: "n"(E1_B + 1) : "r0"); // expected-error {{enumerator 'E1_B' is not relocated where a constant is required, although 'enum e1' has the 'preserve_access_index' attribute}}
+  asm volatile("r0 = %0" :: "ri"(E1_B) : "r0");
+  asm volatile("r0 = %0" :: "i"(0 && E1_B) : "r0");
+  asm volatile("r0 = %0" :: "i"(sizeof(E1_B)) : "r0");
+}
diff --git a/clang/test/Sema/bpf-preserve-enum-value-parity.c b/clang/test/Sema/bpf-preserve-enum-value-parity.c
new file mode 100644
index 00000000000000..8a129ea68cf2ea
--- /dev/null
+++ b/clang/test/Sema/bpf-preserve-enum-value-parity.c
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=expected,attr %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=expected,explicit -DEXPLICIT %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=expected,attr -std=c23 %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify=expected,explicit -std=c23 -DEXPLICIT %s
+// RUN: %clang_cc1 -triple bpf -fsyntax-only -verify=expected,attr %s
+// RUN: %clang_cc1 -triple bpf -fsyntax-only -verify=expected,explicit -DEXPLICIT %s
+
+// An enumerator of an enum with the preserve_access_index attribute is
+// accepted and rejected where __builtin_preserve_enum_value() is. Where a
+// constant is required, it is kept a constant with a single error naming the
+// attribute (attr-error) instead of the error for the call (explicit-error).
+// A builtin argument error gets an extra note naming the attribute (attr-note).
+#ifdef EXPLICIT
+enum E { A = 4 };
+#define X __builtin_preserve_enum_value(*(enum E *)A, 1)
+#else
+enum E { A = 4 } __attribute__((preserve_access_index));
+#define X A
+#endif
+
+typedef unsigned long size_t;
+void *memcpy(void *, const void *, size_t);
+
+// Rejected where a compile-time constant is required.
+int g1 = X; // explicit-error {{initializer element is not a compile-time constant}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+int *g3 = (int[]){X}; // explicit-error {{initializer element is not a compile-time constant}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+int g4[X]; // explicit-error {{variable length array declaration not allowed at file scope}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+int g5[8] = {[X] = 1}; // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+_Alignas(X) int g6; // explicit-error {{'aligned' attribute requires integer constant}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+typedef int v4 __attribute__((vector_size(X * 4))); // explicit-error {{vector_size attribute requires an integer constant}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+struct s1 {
+  int a[X]; // explicit-error {{fields must have a constant size: 'variable length array in structure' extension will never be supported}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+  int b : X; // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+};
+enum F { F1 = X }; // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+_Static_assert(X == 4, ""); // explicit-error {{static assertion expression is not an integral constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+
+void h(int);
+int rejected(int v, void *p) {
+  static int s = X; // explicit-error {{initializer element is not a compile-time constant}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+  int a[8] = {[X] = 1}; // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+  switch (v) {
+  case X: // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+    return 1;
+  case 5 ... X + 2: // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+    return 2;
+  }
+#pragma unroll X // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+  for (int i = 0; i < 8; i++)
+    h(i);
+#pragma clang loop unroll_count(X) // explicit-error {{expression is not an integer constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+  for (int i = 0; i < 8; i++)
+    h(i);
+  __builtin_prefetch(p, X - 4); // expected-error {{argument to '__builtin_prefetch' must be a constant integer}} attr-note {{enumerator 'A' is not a constant expression since 'enum E' has the 'preserve_access_index' attribute}}
+  return v + a[0] + s;
+}
+
+#if __STDC_VERSION__ >= 202311L
+struct item { int v; };
+constexpr int cx2 = X; // explicit-error {{constexpr variable 'cx2' must be initialized by a constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+int constexpr_locals(void) {
+  constexpr struct item cx3 = {X}; // explicit-error {{constexpr variable 'cx3' must be initialized by a constant expression}} attr-error {{enumerator 'A' is not relocated where a constant is required, although 'enum E' has the 'preserve_access_index' attribute}}
+  return cx3.v;
+}
+#endif
+
+// Accepted where the value is used at runtime, or not used at all.
+struct key { int a; int b; };
+void use(void *);
+unsigned long accepted(int v, int *p, void *d, const void *s) {
+  const int k = X;
+  struct key kk = {X, 1};
+  int arr[2] = {X, 1};
+  use(&kk);
+  use(arr);
+  switch (X) {
+  case 4:
+    v++;
+  }
+  v += p[X] + (v == X) + (v && X ? X : 0) + (v << X) + k;
+  v += __builtin_bswap32(X) + __builtin_expect(v, X);
+  v += __builtin_constant_p(X) + sizeof(X) + _Generic(X, int: 1, default: 2);
+  memcpy(d, s, X);
+  __builtin___memcpy_chk(d, s, X, 64);
+  return v + __builtin_align_up((unsigned long)v, X);
+}



More information about the cfe-commits mailing list