https://github.com/yonghong-song created
https://github.com/llvm/llvm-project/pull/243338
This is a follow-up to #232498, which added the preserve_access_index attribute
for enums. It resolves two points from the review.
Switch cases
------------
An enumerator in a case label was not relocated: the case label requires a
constant, so the local value was used and -Wbpf-enum-not-relocated was
reported. Now it is relocated, so `case A:` behaves like `if (cond == A)`. For
example:
```
enum bpf_func_id { BPF_FUNC_a = 1, BPF_FUNC_b = 4 }
__attribute__((preserve_access_index));
int f(int id) {
switch (id) {
case 2:
return 1;
case BPF_FUNC_a:
return 2;
case BPF_FUNC_b ... BPF_FUNC_b + 3:
return 3;
}
return 0;
}
```
With -g, the switch condition is compared with each relocated case value before
the switch, in source order, so a relocated case is taken if its value equals
the value of another case at load time. A case range with a relocated bound
needs two comparisons, since the relocated range may be empty. The generated
code is like the following, where BPF_FUNC_a and BPF_FUNC_b are the relocated
values:
```
int f(int id) {
if (id == BPF_FUNC_a)
goto L_a;
if (id >= BPF_FUNC_b && id <= BPF_FUNC_b + 3)
goto L_b;
switch (id) {
case 2:
return 1;
L_a:
return 2;
L_b:
return 3;
}
return 0;
}
```
A switch with a constant condition is not folded if it has a relocated case
label. Without -g, or in a nodebug function, the case values are constants in
the switch, as before.
Sema checks a case label with the values in the local enum, so the existing
checks, e.g., for duplicate case values, empty ranges, -Wswitch and overflow,
are done as before. The case value is a ConstantExpr with the local value
around the relocated expression, in a no-op implicit cast since
ActOnFinishSwitchStmt() looks through a top-level ConstantExpr. The duplicate
case value diagnostic still names the enumerator.
An explicit __builtin_preserve_enum_value() call in a case label is still an
error, since it is not a constant, but now has notes that say why:
```
error: expression is not an integer constant expression
case __builtin_preserve_enum_value(*(enum E *)A, 1):
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: an explicit '__builtin_preserve_enum_value' call is relocated at
load time, so it is not a constant
note: a case label with an enumerator of an enum with the
'preserve_access_index' attribute is relocated, and compared like an
'if' condition before the switch
```
Opt-out
-------
With -Wno-error=bpf-enum-not-relocated, an enumerator was relocated in a
runtime expression but not where a constant is required, e.g., in an array
bound, so the same enumerator could have two different values. Add
-fbpf-no-enum-reloc=<enum>[,<enum>...] to disable the relocation for the named
enums, or the typedef names of anonymous enums. Their enumerators are always
constants, and -Wbpf-enum-not-relocated is not reported for them. E.g., with
vmlinux.h:
```
clang --target=bpf -O2 -g -fbpf-no-enum-reloc=bpf_map_type,bpf_prog_type ...
```
The driver passes the option only for BPF targets.
>From ac0f26d2655c501df6f82d801c27a4325d6dd8f8 Mon Sep 17 00:00:00 2001
From: Yonghong Song <[email protected]>
Date: Sat, 14 Nov 2026 10:15:26 -0800
Subject: [PATCH] [BPF] Relocate enumerators in case labels and add
-fbpf-no-enum-reloc=
This is a follow-up to #232498, which added the preserve_access_index
attribute for enums. It resolves two points from the review.
Switch cases
------------
An enumerator in a case label was not relocated: the case label requires
a constant, so the local value was used and -Wbpf-enum-not-relocated was
reported. Now it is relocated, so `case A:` behaves like
`if (cond == A)`. For example:
```
enum bpf_func_id { BPF_FUNC_a = 1, BPF_FUNC_b = 4 }
__attribute__((preserve_access_index));
int f(int id) {
switch (id) {
case 2:
return 1;
case BPF_FUNC_a:
return 2;
case BPF_FUNC_b ... BPF_FUNC_b + 3:
return 3;
}
return 0;
}
```
With -g, the switch condition is compared with each relocated case value
before the switch, in source order, so a relocated case is taken if its
value equals the value of another case at load time. A case range with a
relocated bound needs two comparisons, since the relocated range may be
empty. The generated code is like the following, where BPF_FUNC_a and
BPF_FUNC_b are the relocated values:
```
int f(int id) {
if (id == BPF_FUNC_a)
goto L_a;
if (id >= BPF_FUNC_b && id <= BPF_FUNC_b + 3)
goto L_b;
switch (id) {
case 2:
return 1;
L_a:
return 2;
L_b:
return 3;
}
return 0;
}
```
A switch with a constant condition is not folded if it has a relocated
case label. Without -g, or in a nodebug function, the case values are
constants in the switch, as before.
Sema checks a case label with the values in the local enum, so the
existing checks, e.g., for duplicate case values, empty ranges, -Wswitch
and overflow, are done as before. The case value is a ConstantExpr with
the local value around the relocated expression, in a no-op implicit
cast since ActOnFinishSwitchStmt() looks through a top-level
ConstantExpr. The duplicate case value diagnostic still names the
enumerator.
An explicit __builtin_preserve_enum_value() call in a case label is
still an error, since it is not a constant, but now has notes that say
why:
```
error: expression is not an integer constant expression
case __builtin_preserve_enum_value(*(enum E *)A, 1):
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: an explicit '__builtin_preserve_enum_value' call is relocated at
load time, so it is not a constant
note: a case label with an enumerator of an enum with the
'preserve_access_index' attribute is relocated, and compared like an
'if' condition before the switch
```
Opt-out
-------
With -Wno-error=bpf-enum-not-relocated, an enumerator was relocated in a
runtime expression but not where a constant is required, e.g., in an
array bound, so the same enumerator could have two different values. Add
-fbpf-no-enum-reloc=<enum>[,<enum>...] to disable the relocation for the
named enums, or the typedef names of anonymous enums. Their enumerators
are always constants, and -Wbpf-enum-not-relocated is not reported for
them. E.g., with vmlinux.h:
```
clang --target=bpf -O2 -g -fbpf-no-enum-reloc=bpf_map_type,bpf_prog_type ...
```
The driver passes the option only for BPF targets.
---
clang/include/clang/Basic/AttrDocs.td | 19 +-
.../clang/Basic/DiagnosticSemaKinds.td | 7 +
clang/include/clang/Basic/LangOptions.h | 4 +
clang/include/clang/Options/Options.td | 7 +
clang/include/clang/Sema/SemaBPF.h | 1 +
clang/lib/CodeGen/CGStmt.cpp | 116 ++++++++++-
clang/lib/CodeGen/CodeGenFunction.h | 2 +
clang/lib/Driver/ToolChains/Clang.cpp | 5 +
clang/lib/Sema/SemaBPF.cpp | 126 ++++++++++--
clang/lib/Sema/SemaStmt.cpp | 10 +-
...f-attr-preserve-access-index-enum-switch.c | 192 ++++++++++++++++++
clang/test/Driver/bpf-no-enum-reloc.c | 8 +
...attr-preserve-access-index-enum-constant.c | 3 +
...f-attr-preserve-access-index-enum-switch.c | 44 ++++
.../Sema/bpf-preserve-enum-value-parity.c | 6 +-
15 files changed, 526 insertions(+), 24 deletions(-)
create mode 100644
clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
create mode 100644 clang/test/Driver/bpf-no-enum-reloc.c
create mode 100644 clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
diff --git a/clang/include/clang/Basic/AttrDocs.td
b/clang/include/clang/Basic/AttrDocs.td
index 9828968c9d0f41..f7df0069c1bf3a 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3087,11 +3087,20 @@ 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.
+Where a constant is required, e.g., in an array bound, 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.
+
+A case label of a switch is relocated, so that `case A:` behaves like
+`if (cond == A)`: the switch condition is compared with the relocated values
+before the other case labels, in source order. The values in the local enum are
+used to check the case labels, e.g., for duplicates.
+
+`-fbpf-no-enum-reloc=<enum>[,<enum>...]` disables the relocation for the named
+enums, or the typedef names of anonymous enums: their enumerators are always
+constants, as if the enums did not have the attribute.
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/DiagnosticSemaKinds.td
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index dff45a081f2e8c..9dc5cc7315c42d 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13648,6 +13648,13 @@ 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 note_preserve_enum_value_not_const : Note<
+ "an explicit '__builtin_preserve_enum_value' call is relocated at load time,
"
+ "so it is not a constant">;
+def note_preserve_enum_value_case_attr : Note<
+ "a case label with an enumerator of an enum with the "
+ "'preserve_access_index' attribute is relocated, and compared like an 'if' "
+ "condition before the switch">;
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/Basic/LangOptions.h
b/clang/include/clang/Basic/LangOptions.h
index 8607fbae8d8fce..b36f4346fb156b 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -515,6 +515,10 @@ class LangOptions : public LangOptionsBase {
/// (files, functions) should or should not be instrumented.
std::vector<std::string> ProfileListFiles;
+ /// Names of BPF enums whose enumerators are not relocated, from
+ /// -fbpf-no-enum-reloc=.
+ std::vector<std::string> BPFNoEnumRelocs;
+
clang::ObjCRuntime ObjCRuntime;
CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
diff --git a/clang/include/clang/Options/Options.td
b/clang/include/clang/Options/Options.td
index 9156640ff67c79..167737c43fe7cb 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -2188,6 +2188,13 @@ defm borland_extensions :
BoolFOption<"borland-extensions",
PosFlag<SetTrue, [], [ClangOption, CC1Option],
"Accept non-standard constructs supported by the Borland compiler">,
NegFlag<SetFalse>>;
+def fbpf_no_enum_reloc_EQ : CommaJoined<["-"], "fbpf-no-enum-reloc=">,
+ Group<f_Group>, Flags<[TargetSpecific]>,
+ Visibility<[ClangOption, CC1Option]>, MetaVarName<"<enum>">,
+ HelpText<"Do not relocate the enumerators of the comma-separated enums, "
+ "although the enums have the preserve_access_index attribute "
+ "(BPF only)">,
+ MarshallingInfoStringVector<LangOpts<"BPFNoEnumRelocs">>;
def fbuiltin : Flag<["-"], "fbuiltin">, Group<f_Group>,
Visibility<[ClangOption, CLOption, DXCOption, FlangOption, FC1Option]>;
def fbuiltin_module_map : Flag <["-"], "fbuiltin-module-map">, Group<f_Group>,
diff --git a/clang/include/clang/Sema/SemaBPF.h
b/clang/include/clang/Sema/SemaBPF.h
index 16d12e21e88ef0..517f42654f2810 100644
--- a/clang/include/clang/Sema/SemaBPF.h
+++ b/clang/include/clang/Sema/SemaBPF.h
@@ -35,6 +35,7 @@ class SemaBPF : public SemaBase {
Expr *checkAsmImmediateOperand(Expr *E);
Expr *keepPreserveAIEnumeratorsConstant(Expr *E);
Expr *checkLocalConstantInitializer(const VarDecl *VD, Expr *Init);
+ ExprResult verifyCaseExpr(Expr *E);
private:
llvm::MapVector<EnumDecl *, const BPFPreserveAccessIndexAttr *>
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 455c4352661043..8924e5c3b9b4c6 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1747,6 +1747,99 @@ void CodeGenFunction::EmitContinueStmt(const
ContinueStmt &S) {
EmitBranchThroughCleanup(GetDestForLoopControlStmt(S)->ContinueBlock);
}
+/// Return whether S has an enumerator of a BPF preserve_access_index enum,
+/// which Sema keeps as a pseudo-object for __builtin_preserve_enum_value().
+static bool hasBPFEnumeratorRef(const Stmt *S) {
+ if (!S)
+ return false;
+ if (const auto *POE = dyn_cast<PseudoObjectExpr>(S))
+ if (const auto *DRE = dyn_cast<DeclRefExpr>(POE->getSyntacticForm());
+ DRE && isa<EnumConstantDecl>(DRE->getDecl()))
+ return true;
+ return llvm::any_of(S->children(), hasBPFEnumeratorRef);
+}
+
+/// If the case value E has a relocated enumerator, see
+/// SemaBPF::verifyCaseExpr(), and debug info is available, return E without
its
+/// ConstantExpr and casts.
+static const Expr *getBPFRelocatedCaseValue(CodeGenFunction &CGF,
+ const Expr *E) {
+ if (!E || !CGF.getTarget().getTriple().isBPF() ||
+ !CGF.CGM.getCodeGenOpts().hasReducedDebugInfo() || !CGF.getDebugInfo())
+ return nullptr;
+ while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
+ E = ICE->getSubExpr();
+ const auto *CE = dyn_cast<ConstantExpr>(E);
+ if (!CE || !hasBPFEnumeratorRef(CE->getSubExpr()))
+ return nullptr;
+ return CE->getSubExpr();
+}
+
+static bool isBPFRelocatedCase(CodeGenFunction &CGF, const CaseStmt &S) {
+ return getBPFRelocatedCaseValue(CGF, S.getLHS()) ||
+ getBPFRelocatedCaseValue(CGF, S.getRHS());
+}
+
+/// Emit a case statement whose value is relocated: move the switch to a new
+/// block, and in its old block, branch to the case if the condition matches
the
+/// relocated value, otherwise to the switch. So the relocated cases are
checked
+/// in source order, before the other cases. E.g., with relocated A, B and C,
+///
+/// switch (x) { case 1: ... case A: ... case B ... C: ... }
+///
+/// is emitted like:
+///
+/// if (x == A) goto case_A;
+/// if (x >= B && x <= C) goto case_BC;
+/// switch (x) { case 1: ... }
+void CodeGenFunction::EmitBPFRelocatedCaseStmt(const CaseStmt &S,
+ ArrayRef<const Attr *> Attrs) {
+ llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
+ EmitBlockWithFallThrough(CaseDest, &S);
+
+ llvm::BasicBlock *CheckBB = SwitchInsn->getParent();
+ llvm::BasicBlock *SwitchBB = createBasicBlock("sw.dispatch");
+ CurFn->insert(std::next(CheckBB->getIterator()), SwitchBB);
+ SwitchInsn->removeFromParent();
+ SwitchInsn->insertInto(SwitchBB, SwitchBB->end());
+
+ // Emit the check at the end of CheckBB, then come back to the case body.
+ {
+ llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
+ Builder.SetInsertPoint(CheckBB);
+ ApplyDebugLocation DL(*this, S.getLHS());
+ llvm::Value *CondV = SwitchInsn->getCondition();
+ auto EmitCaseValue = [&](const Expr *E) -> llvm::Value * {
+ if (const Expr *Reloc = getBPFRelocatedCaseValue(*this, E))
+ return Builder.CreateIntCast(
+ EmitScalarExpr(Reloc), CondV->getType(),
+ Reloc->getType()->isSignedIntegerOrEnumerationType());
+ return Builder.getInt(E->EvaluateKnownConstInt(getContext()));
+ };
+
+ llvm::Value *Cond;
+ if (!S.getRHS()) {
+ Cond = Builder.CreateICmpEQ(CondV, EmitCaseValue(S.getLHS()));
+ } else {
+ // The relocated range may be empty.
+ bool IsSigned =
S.getLHS()->getType()->isSignedIntegerOrEnumerationType();
+ llvm::Value *Lo = Builder.CreateICmp(IsSigned ? llvm::CmpInst::ICMP_SGE
+ : llvm::CmpInst::ICMP_UGE,
+ CondV, EmitCaseValue(S.getLHS()));
+ llvm::Value *Hi = Builder.CreateICmp(IsSigned ? llvm::CmpInst::ICMP_SLE
+ : llvm::CmpInst::ICMP_ULE,
+ CondV, EmitCaseValue(S.getRHS()));
+ Cond = Builder.CreateAnd(Lo, Hi);
+ }
+ if (SwitchLikelihood)
+ Cond = emitCondLikelihoodViaExpectIntrinsic(Cond,
+ Stmt::getLikelihood(Attrs));
+ Builder.CreateCondBr(Cond, CaseDest, SwitchBB);
+ }
+
+ EmitStmt(S.getSubStmt());
+}
+
/// EmitCaseStmtRange - If case statement range is not too big then
/// add multiple cases to switch instruction, one for each value within
/// the range. If range is too big then emit "if" condition check.
@@ -1848,6 +1941,11 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
return;
}
+ if (isBPFRelocatedCase(*this, S)) {
+ EmitBPFRelocatedCaseStmt(S, Attrs);
+ return;
+ }
+
// Handle case ranges.
if (S.getRHS()) {
EmitCaseStmtRange(S, Attrs);
@@ -1917,7 +2015,8 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
// Otherwise, iteratively add consecutive cases to this switch stmt.
- while (NextCase && NextCase->getRHS() == nullptr) {
+ while (NextCase && NextCase->getRHS() == nullptr &&
+ !isBPFRelocatedCase(*this, *NextCase)) {
CurCase = NextCase;
llvm::ConstantInt *CaseVal =
Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
@@ -2338,6 +2437,15 @@ getLikelihoodWeights(ArrayRef<Stmt::Likelihood>
Likelihoods) {
return Result;
}
+static bool hasBPFRelocatedCase(CodeGenFunction &CGF, const SwitchStmt &S) {
+ for (const SwitchCase *SC = S.getSwitchCaseList(); SC;
+ SC = SC->getNextSwitchCase())
+ if (const auto *CS = dyn_cast<CaseStmt>(SC);
+ CS && isBPFRelocatedCase(CGF, *CS))
+ return true;
+ return false;
+}
+
void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
// Handle nested switch statements.
llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
@@ -2346,9 +2454,11 @@ void CodeGenFunction::EmitSwitchStmt(const SwitchStmt
&S) {
llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
// See if we can constant fold the condition of the switch and therefore only
- // emit the live case statement (if any) of the switch.
+ // emit the live case statement (if any) of the switch. A relocated case
value
+ // is not known until load time.
llvm::APSInt ConstantCondValue;
- if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
+ if (!hasBPFRelocatedCase(*this, S) &&
+ ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
SmallVector<const Stmt*, 4> CaseStmts;
const SwitchCase *Case = nullptr;
if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
diff --git a/clang/lib/CodeGen/CodeGenFunction.h
b/clang/lib/CodeGen/CodeGenFunction.h
index c73cae01f15084..c46c33a19cce28 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3774,6 +3774,8 @@ class CodeGenFunction : public CodeGenTypeCache {
void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs);
void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
+ void EmitBPFRelocatedCaseStmt(const CaseStmt &S,
+ ArrayRef<const Attr *> Attrs);
void EmitDeferStmt(const DeferStmt &S);
void EmitAsmStmt(const AsmStmt &S);
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp
b/clang/lib/Driver/ToolChains/Clang.cpp
index bd80f146f3a45d..5d5e96b908b8ee 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1679,6 +1679,11 @@ void Clang::RenderTargetOptions(const llvm::Triple
&EffectiveTriple,
case llvm::Triple::ve:
AddVETargetArgs(Args, CmdArgs);
break;
+
+ case llvm::Triple::bpfel:
+ case llvm::Triple::bpfeb:
+ Args.AddAllArgs(CmdArgs, options::OPT_fbpf_no_enum_reloc_EQ);
+ break;
}
}
diff --git a/clang/lib/Sema/SemaBPF.cpp b/clang/lib/Sema/SemaBPF.cpp
index 13b486497cf6ce..0e36531c841371 100644
--- a/clang/lib/Sema/SemaBPF.cpp
+++ b/clang/lib/Sema/SemaBPF.cpp
@@ -19,6 +19,7 @@
#include "clang/Basic/TargetBuiltins.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/ParsedAttr.h"
+#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/APSInt.h"
#include <optional>
@@ -243,12 +244,23 @@ static QualType getPreserveAIEnumType(ASTContext &Context,
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();
+ // typedef name. An enum named by -fbpf-no-enum-reloc= is not relocated.
+ const TypedefNameDecl *TD = nullptr;
+ if (!ED->getDeclName()) {
+ TD = ED->getTypedefNameForAnonDecl();
+ if (!TD)
+ return QualType();
+ }
+ StringRef Name = TD ? TD->getName() : ED->getName();
+ if (llvm::is_contained(Context.getLangOpts().BPFNoEnumRelocs, Name))
+ return QualType();
+ return TD ? Context.getTypeDeclType(TD) : Context.getCanonicalTagType(ED);
+}
+
+static bool isInSwitchCaseLabel(Sema &S) {
+ const sema::FunctionScopeInfo *FSI = S.getCurFunction();
+ return S.currentEvaluationContext().IsCaseExpr && FSI &&
+ !FSI->SwitchStack.empty();
}
// Return the enumerator reference E, or, if it is relocated, a pseudo-object
@@ -263,9 +275,10 @@ Expr *SemaBPF::BuildPreserveAIEnumeratorRef(DeclRefExpr
*E) {
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() ||
+ // evaluated context, e.g., an array bound, or outside of a function, e.g., a
+ // global initializer. Warn, and use the enumerator's value. A case label is
+ // an exception, see verifyCaseExpr().
+ if ((SemaRef.isConstantEvaluatedContext() && !isInSwitchCaseLabel(SemaRef))
||
SemaRef.CurContext->getRedeclContext()->isFileContext()) {
Diag(E->getExprLoc(),
diag::warn_preserve_access_index_enumerator_not_relocated)
@@ -360,6 +373,13 @@ void SemaBPF::notePreserveAIEnumerator(const Expr *E) {
Diag(Note->first, Note->second);
}
+static void warnEnumeratorNotRelocated(SemaBPF &S, const DeclRefExpr *DRE) {
+ S.Diag(DRE->getExprLoc(),
+ diag::warn_preserve_access_index_enumerator_not_relocated)
+ << DRE->getDecl() << getPreserveAIEnumType(S.getASTContext(), DRE)
+ << DRE->getSourceRange();
+}
+
// 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) {
@@ -369,10 +389,7 @@ static Stmt *keepEnumeratorsConstant(SemaBPF &S, Stmt *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();
+ warnEnumeratorNotRelocated(S, DRE);
return DRE;
}
for (Stmt *&Child : St->children())
@@ -402,4 +419,87 @@ Expr *SemaBPF::checkLocalConstantInitializer(const VarDecl
*VD, Expr *Init) {
return keepPreserveAIEnumeratorsConstant(Init);
}
+// Replace each relocated enumerator in Slot with its DeclRefExpr, and record
it
+// in Replaced to be restored.
+static void
+replaceEnumeratorRefs(Stmt *&Slot,
+ SmallVectorImpl<std::pair<Stmt **, Stmt *>> &Replaced) {
+ if (!Slot)
+ return;
+ if (auto *E = dyn_cast<Expr>(Slot);
+ E && SemaBPF::isPreserveAIEnumeratorRef(E)) {
+ Replaced.push_back({&Slot, Slot});
+ Slot = cast<PseudoObjectExpr>(E)->getSyntacticForm();
+ return;
+ }
+ for (Stmt *&Child : Slot->children())
+ replaceEnumeratorRefs(Child, Replaced);
+}
+
+// Return an explicit __builtin_preserve_enum_value() call in S, not in an
+// operand of sizeof or alignof.
+static const CallExpr *findPreserveEnumValueCall(const Stmt *S) {
+ if (!S || isa<UnaryExprOrTypeTraitExpr>(S))
+ return nullptr;
+ if (const auto *Call = dyn_cast<CallExpr>(S);
+ Call && Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value)
+ return Call;
+ for (const Stmt *Child : S->children())
+ if (const CallExpr *Call = findPreserveEnumValueCall(Child))
+ return Call;
+ return nullptr;
+}
+
+// Verify that the case label value E is an integer constant expression with
the
+// local enumerator values. A relocated enumerator in E is kept, so that
+// "case A:" behaves like "if (cond == A)". Return E in a ConstantExpr with the
+// local value, which is used to check the case values, e.g., for duplicates.
+ExprResult SemaBPF::verifyCaseExpr(Expr *E) {
+ SmallVector<std::pair<Stmt **, Stmt *>, 4> Replaced;
+ Stmt *Root = E;
+ replaceEnumeratorRefs(Root, Replaced);
+
+ // Check E with the local enumerator values.
+ auto *ConstE = cast<Expr>(Root);
+ ExprResult ER =
+ SemaRef.VerifyIntegerConstantExpression(ConstE, AllowFoldKind::Allow);
+ if (ER.isInvalid()) {
+ // An explicit __builtin_preserve_enum_value() call is not a constant, but
+ // an enumerator of an enum with the attribute would be relocated here.
+ if (const CallExpr *Call = findPreserveEnumValueCall(ConstE)) {
+ Diag(Call->getBeginLoc(), diag::note_preserve_enum_value_not_const)
+ << Call->getSourceRange();
+ Diag(Call->getBeginLoc(), diag::note_preserve_enum_value_case_attr);
+ }
+ return ER;
+ }
+ if (Replaced.empty())
+ return ER;
+
+ // Evaluate E with the local enumerator values.
+ Expr::EvalResult Result;
+ if (ConstE->isGLValue() ||
+ !ConstE->EvaluateAsRValue(Result, getASTContext(),
+ /*InConstantContext=*/true) ||
+ !Result.Val.isInt()) {
+ // The value is not an integer rvalue, e.g., a compound literal folded as
+ // an extension. Keep the enumerators constants and warn.
+ for (const auto &R : Replaced)
+ warnEnumeratorNotRelocated(*this, cast<DeclRefExpr>(*R.first));
+ return ER;
+ }
+
+ // Restore the relocated enumerators. ActOnFinishSwitchStmt() looks through a
+ // ConstantExpr at the top of a case value to find its unpromoted type, so
put
+ // the ConstantExpr in a no-op cast to keep its value, e.g.,
+ // NoOp(ConstantExpr(A)) for "case A:".
+ for (auto [Slot, Ref] : Replaced)
+ *Slot = Ref;
+ ASTContext &Context = getASTContext();
+ Expr *CE = ConstantExpr::Create(Context, E, Result.Val);
+ return ImplicitCastExpr::Create(Context, E->getType(), CK_NoOp, CE,
+ /*BasePath=*/nullptr, VK_PRValue,
+ FPOptionsOverride());
+}
+
} // namespace clang
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 4bf5b3f3ec6b74..a4b569f8a89007 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -33,6 +33,7 @@
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
+#include "clang/Sema/SemaBPF.h"
#include "clang/Sema/SemaCUDA.h"
#include "clang/Sema/SemaHLSL.h"
#include "clang/Sema/SemaObjC.h"
@@ -556,7 +557,9 @@ Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
{
ExprResult ER = E;
if (!E->isValueDependent())
- ER = VerifyIntegerConstantExpression(E, AllowFoldKind::Allow);
+ ER = Context.getTargetInfo().getTriple().isBPF()
+ ? BPF().verifyCaseExpr(E)
+ : VerifyIntegerConstantExpression(E, AllowFoldKind::Allow);
if (!ER.isInvalid())
ER = DefaultLvalueConversion(ER.get());
if (!ER.isInvalid())
@@ -1526,6 +1529,11 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch,
StringRef PrevString, CurrString;
Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
+ // A relocated BPF enumerator is a pseudo-object.
+ if (auto *POE = dyn_cast<PseudoObjectExpr>(PrevCase))
+ PrevCase = POE->getSyntacticForm();
+ if (auto *POE = dyn_cast<PseudoObjectExpr>(CurrCase))
+ CurrCase = POE->getSyntacticForm();
if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
PrevString = DeclRef->getDecl()->getName();
}
diff --git a/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
new file mode 100644
index 00000000000000..64d4562a833698
--- /dev/null
+++ b/clang/test/CodeGen/bpf-attr-preserve-access-index-enum-switch.c
@@ -0,0 +1,192 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -emit-llvm -debug-info-kind=limited
-disable-llvm-passes \
+// RUN: %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple bpf -emit-llvm -disable-llvm-passes %s -o - \
+// RUN: | FileCheck --check-prefix=CONST %s
+// RUN: %clang_cc1 -triple bpf -emit-llvm -debug-info-kind=limited
-disable-llvm-passes \
+// RUN: -fbpf-no-enum-reloc=e1,e2,e3 %s -o - | FileCheck
--check-prefix=CONST %s
+
+// A case value with an enumerator of a preserve_access_index enum is relocated
+// and compared before the switch. Without debug info, or with
+// -fbpf-no-enum-reloc=, the case values are constants in the switch.
+
+#define __reloc__ __attribute__((preserve_access_index))
+
+enum e1 { E1_A = 1, E1_B = 4, E1_C = 8 } __reloc__;
+typedef enum : signed char { E2_A = 3 } __reloc__ e2;
+enum e3 : long { E3_A = 5 } __reloc__;
+
+void h(int);
+
+int test1(int x) {
+ switch (x) {
+ case 2:
+ return 1;
+ case E1_A:
+ return 2;
+ case E1_B ... E1_C:
+ return 3;
+ case E2_A + 100:
+ return 4;
+ case 10 ... E3_A + 10:
+ return 5;
+ default:
+ return 6;
+ }
+}
+
+// CHECK-LABEL: define dso_local i32 @test1
+// CHECK: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32
{{[0-9]+}}, ptr @{{[0-9]+}}, 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: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_A:[0-9a-z.]+]], label
%[[D1:[0-9a-z.]+]]
+// CHECK: [[D1]]:
+// CHECK-NEXT: [[V:%[0-9]+]] = 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: [[LO:%[0-9]+]] = icmp sge i32 [[X]], [[T]]
+// CHECK-NEXT: [[V:%[0-9]+]] = 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: [[HI:%[0-9]+]] = icmp sle i32 [[X]], [[T]]
+// CHECK-NEXT: [[C:%[0-9]+]] = and i1 [[LO]], [[HI]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_BC:[0-9a-z.]+]], label
%[[D2:[0-9a-z.]+]]
+// CHECK: [[D2]]:
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}},
!llvm.preserve.access.index ![[E2:[0-9]+]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i8
+// CHECK-NEXT: [[S:%[0-9a-z]+]] = sext i8 [[T]] to i32
+// CHECK-NEXT: [[ADD:%[0-9a-z]+]] = add nsw i32 [[S]], 100
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[ADD]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_A2:[0-9a-z.]+]], label
%[[D3:[0-9a-z.]+]]
+// CHECK: [[D3]]:
+// CHECK-NEXT: [[LO:%[0-9]+]] = icmp sge i32 [[X]], 10
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}},
!llvm.preserve.access.index ![[E3:[0-9]+]]
+// CHECK-NEXT: [[ADD:%[0-9a-z]+]] = add nsw i64 [[V]], 10
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[ADD]] to i32
+// CHECK-NEXT: [[HI:%[0-9]+]] = icmp sle i32 [[X]], [[T]]
+// CHECK-NEXT: [[C:%[0-9]+]] = and i1 [[LO]], [[HI]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_R:[0-9a-z.]+]], label
%[[D4:[0-9a-z.]+]]
+// CHECK: [[D4]]:
+// CHECK-NEXT: switch i32 [[X]], label %sw.default [
+// CHECK-NEXT: i32 2, label %sw.bb
+// CHECK-NEXT: ]
+// CHECK: [[BB_A]]:
+// CHECK-NEXT: store i32 2, ptr %retval
+// CHECK: [[BB_BC]]:
+// CHECK-NEXT: store i32 3, ptr %retval
+// CHECK: [[BB_A2]]:
+// CHECK-NEXT: store i32 4, ptr %retval
+// CHECK: [[BB_R]]:
+// CHECK-NEXT: store i32 5, ptr %retval
+
+// CONST-LABEL: define dso_local i32 @test1
+// CONST-NOT: @llvm.bpf.preserve.enum.value
+// CONST: switch i32 %{{[0-9]+}}, label %sw.default [
+// CONST-NEXT: i32 2, label %sw.bb
+// CONST-NEXT: i32 1, label %sw.bb1
+// CONST-NEXT: i32 4, label %sw.bb2
+// CONST-NEXT: i32 5, label %sw.bb2
+// CONST-NEXT: i32 6, label %sw.bb2
+// CONST-NEXT: i32 7, label %sw.bb2
+// CONST-NEXT: i32 8, label %sw.bb2
+// CONST-NEXT: i32 103, label %sw.bb3
+// CONST-NEXT: i32 10, label %sw.bb4
+// CONST-NEXT: i32 11, label %sw.bb4
+// CONST-NEXT: i32 12, label %sw.bb4
+// CONST-NEXT: i32 13, label %sw.bb4
+// CONST-NEXT: i32 14, label %sw.bb4
+// CONST-NEXT: i32 15, label %sw.bb4
+// CONST-NEXT: ]
+
+int test2(int x) {
+ switch (4) {
+ case E1_B:
+ switch (x) {
+ case E3_A:
+ h(1);
+ }
+ return 1;
+ case 6:
+ return 2;
+ }
+ return 0;
+}
+
+// CHECK-LABEL: define dso_local i32 @test2
+// CHECK: [[V:%[0-9]+]] = 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: [[C:%[0-9]+]] = icmp eq i32 4, [[T]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_B:[0-9a-z.]+]], label
%[[D1:[0-9a-z.]+]]
+// CHECK: [[D1]]:
+// CHECK-NEXT: switch i32 4, label %{{[0-9a-z.]+}} [
+// CHECK-NEXT: i32 6, label %{{[0-9a-z.]+}}
+// CHECK-NEXT: ]
+// CHECK: [[BB_B]]:
+// CHECK-NEXT: [[X:%[0-9]+]] = load i32, ptr %x.addr
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}},
!llvm.preserve.access.index ![[E3]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i32
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i32 [[X]], [[T]]
+// CHECK-NEXT: br i1 [[C]], label %{{[0-9a-z.]+}}, label %[[D2:[0-9a-z.]+]]
+// CHECK: [[D2]]:
+// CHECK-NEXT: switch i32 [[X]], label %{{[0-9a-z.]+}} [
+// CHECK-NEXT: ]
+
+// CONST-LABEL: define dso_local i32 @test2
+// CONST-NOT: @llvm.bpf.preserve.enum.value
+// CONST: switch i32 %{{[0-9]+}}, label %sw.epilog [
+// CONST-NEXT: i32 5, label %sw.bb
+// CONST-NEXT: ]
+// CONST-NOT: switch
+// CONST: ret i32 1
+
+void test3(long x) {
+ switch (x) {
+ case 1:
+ case E2_A:
+ case 9:
+ h(x);
+ }
+}
+
+// CHECK-LABEL: define dso_local void @test3
+// CHECK: [[X:%[0-9]+]] = load i64, ptr %x.addr
+// CHECK-NEXT: [[V:%[0-9]+]] = call i64 @llvm.bpf.preserve.enum.value(i32
{{[0-9]+}}, ptr @{{[0-9]+}}, i64 1), !dbg !{{[0-9]+}},
!llvm.preserve.access.index ![[E2]]
+// CHECK-NEXT: [[T:%[0-9a-z]+]] = trunc i64 [[V]] to i8
+// CHECK-NEXT: [[S:%[0-9]+]] = sext i8 [[T]] to i64
+// CHECK-NEXT: [[C:%[0-9]+]] = icmp eq i64 [[X]], [[S]]
+// CHECK-NEXT: br i1 [[C]], label %[[BB_C:[0-9a-z.]+]], label
%[[D1:[0-9a-z.]+]]
+// CHECK: [[D1]]:
+// CHECK-NEXT: switch i64 [[X]], label %sw.epilog [
+// CHECK-NEXT: i64 1, label %[[BB_1:[0-9a-z.]+]]
+// CHECK-NEXT: i64 9, label %[[BB_9:[0-9a-z.]+]]
+// CHECK-NEXT: ]
+// CHECK: [[BB_1]]:
+// CHECK-NEXT: br label %[[BB_C]]
+// CHECK: [[BB_C]]:
+// CHECK-NEXT: br label %[[BB_9]]
+// CHECK: [[BB_9]]:
+// CHECK: call void @h
+
+// CONST-LABEL: define dso_local void @test3
+// CONST: switch i64 %{{[0-9]+}}, label %sw.epilog [
+// CONST-NEXT: i64 1, label %sw.bb
+// CONST-NEXT: i64 3, label %sw.bb
+// CONST-NEXT: i64 9, label %sw.bb
+// CONST-NEXT: ]
+
+__attribute__((nodebug)) int test4(int x) {
+ switch (x) {
+ case E1_A:
+ return 1;
+ }
+ return 0;
+}
+
+// CHECK-LABEL: define dso_local i32 @test4
+// CHECK-NOT: @llvm.bpf.preserve.enum.value
+// CHECK: switch i32 %{{[0-9]+}}, label %sw.epilog [
+// CHECK-NEXT: i32 1, label %sw.bb
+// CHECK-NEXT: ]
+
+// CHECK: ![[E1]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e1"
+// CHECK: ![[E3]] = !DICompositeType(tag: DW_TAG_enumeration_type, name: "e3"
+// CHECK: ![[E2]] = !DIDerivedType(tag: DW_TAG_typedef, name: "e2"
diff --git a/clang/test/Driver/bpf-no-enum-reloc.c
b/clang/test/Driver/bpf-no-enum-reloc.c
new file mode 100644
index 00000000000000..53f42a8893b64e
--- /dev/null
+++ b/clang/test/Driver/bpf-no-enum-reloc.c
@@ -0,0 +1,8 @@
+// RUN: %clang -### -c --target=bpf -fbpf-no-enum-reloc=e1,e2 \
+// RUN: -fbpf-no-enum-reloc=e3 %s 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-fbpf-no-enum-reloc=e1,e2" "-fbpf-no-enum-reloc=e3"
+
+// RUN: not %clang -### -c --target=x86_64 -fbpf-no-enum-reloc=e1 %s 2>&1 | \
+// RUN: FileCheck --check-prefix=ERR %s
+// ERR: error: unsupported option '-fbpf-no-enum-reloc=' for target 'x86_64'
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
index 26cdc0fc939022..a184de7f07be8a 100644
--- a/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-constant.c
@@ -3,11 +3,14 @@
// 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
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only
-verify=none \
+// RUN: -fbpf-no-enum-reloc=bpf_map_type,ops_flags %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.
+// -fbpf-no-enum-reloc= disables the relocation, so there is no diagnostic.
// none-no-diagnostics
diff --git a/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
b/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
new file mode 100644
index 00000000000000..6c24cc94602239
--- /dev/null
+++ b/clang/test/Sema/bpf-attr-preserve-access-index-enum-switch.c
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only
-verify=expected,reloc -Wswitch %s
+// RUN: %clang_cc1 -triple bpf -fsyntax-only -verify=expected,reloc -Wswitch %s
+// RUN: %clang_cc1 -triple bpf -debug-info-kind=limited -fsyntax-only -verify
-Wswitch \
+// RUN: -fbpf-no-enum-reloc=E %s
+
+// A relocated enumerator in a case label is not diagnosed by
+// -Wbpf-enum-not-relocated. The case labels are checked with the local values,
+// as with -fbpf-no-enum-reloc=.
+
+enum E { A = 1, B = 4, C = 8, D = 300 } __attribute__((preserve_access_index));
+
+int f(int i, char c, enum E e) {
+ switch (i) {
+ case A: // expected-note {{previous case defined here}}
+ return 1;
+ case 1: // expected-error {{duplicate case value: 'A' and '1' both equal
'1'}}
+ return 2;
+ case B: // expected-note {{previous case defined here}}
+ return 3;
+ case B + 1 ... C:
+ return 4;
+ case B: // expected-error {{duplicate case value 'B'}}
+ return 5;
+ case C + 1 ... B: // expected-warning {{empty case range specified}}
+ return 6;
+ case A + __builtin_preserve_enum_value(*(enum E *)B, 1): // expected-error
{{expression is not an integer constant expression}} expected-note {{an
explicit '__builtin_preserve_enum_value' call is relocated at load time, so it
is not a constant}} expected-note {{a case label with an enumerator of an enum
with the 'preserve_access_index' attribute is relocated, and compared like an
'if' condition before the switch}}
+ return 7;
+ // A compound literal is not an integer rvalue, so A is kept a constant.
+ case (int){A + 10}: // reloc-error {{enumerator 'A' is not relocated where a
constant is required, although 'enum E' has the 'preserve_access_index'
attribute}}
+ return 8;
+ }
+
+ switch (e) { // expected-warning {{enumeration values 'C' and 'D' not
handled in switch}}
+ case A:
+ case B:
+ break;
+ }
+
+ switch (c) {
+ case D: // expected-warning {{overflow converting case value to switch
condition type (300 to 44)}}
+ break;
+ }
+ return 0;
+}
diff --git a/clang/test/Sema/bpf-preserve-enum-value-parity.c
b/clang/test/Sema/bpf-preserve-enum-value-parity.c
index 8a129ea68cf2ea..451f5e016289ae 100644
--- a/clang/test/Sema/bpf-preserve-enum-value-parity.c
+++ b/clang/test/Sema/bpf-preserve-enum-value-parity.c
@@ -10,6 +10,8 @@
// 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).
+// A case label is an exception: the enumerator is relocated there, and the
+// error for the call gets notes suggesting the attribute (explicit-note).
#ifdef EXPLICIT
enum E { A = 4 };
#define X __builtin_preserve_enum_value(*(enum E *)A, 1)
@@ -40,9 +42,9 @@ 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}}
+ case X: // explicit-error {{expression is not an integer constant
expression}} explicit-note {{an explicit '__builtin_preserve_enum_value' call
is relocated at load time, so it is not a constant}} explicit-note {{a case
label with an enumerator of an enum with the 'preserve_access_index' attribute
is relocated, and compared like an 'if' condition before the switch}}
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}}
+ case 5 ... X + 2: // explicit-error {{expression is not an integer constant
expression}} explicit-note {{an explicit '__builtin_preserve_enum_value' call
is relocated at load time, so it is not a constant}} explicit-note {{a case
label with an enumerator of an enum with the 'preserve_access_index' attribute
is relocated, and compared like an 'if' condition before the switch}}
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}}
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits