Hi Jasper,

On 10/31/26 7:54 PM, York Jasper Niebuhr wrote:
Use deferred constants to preserve semantic information required for BPF
CO-RE relocations.

Mark enum types for deferred enum values and record types carrying
"preserve_access_index" for deferred field offsets.  Deferred constants
encountered during BPF lowering are either turned into CO-RE relocations
or resolved to their ordinary compile-time values when no relocation is
requested.

Add a "preserve_enum_values" attribute for enum types.  Enumerators of a
type carrying this attribute automatically generate
BPF_RELO_ENUMVAL_VALUE relocations.

Thanks for the patch and for discussing at the gccbpf meeting today.
This is interesting work and would be good to have for the backend.

Having such an attribute to parallel the preserve_access_index attribute
would be a nice improvement for usability.  Currently BPF program authors
need to remember to manually annotate access to kernel enums with the
appropriate builtin.

Inserting relos for offsetof when used on preserve-access-index types
would also be a good improvement.

As we discussed, it may be good to good to split the new attribute into
its own patch since that will need some coordination with the kernel
and clang folks.

Minor but I think "preserve_enum_value" (non-plural) would be more inline
with the naming used by existing CO-RE builtins/attributes/macros.


Remove the bpf_enum_mappings workaround in favor of direct enum identity
recovery from deferred cst arguments to __builtin_preserve_enum_value.

For record types carrying "preserve_access_index", deferred field
offsets originating from offsetof expressions are converted into
BPF_RELO_FIELD_BYTE_OFFSET relocations.

Cupertino is most familiar with the existing CO-RE implementation so it
would be good if he can take a more detailed look.

Overall the changes seem sensible to me.
I have a few questions/comments inline below.


BPF CO-RE relocations can not currently be emitted for static data.  Add
an IPA pass which resolves deferred constants in static initializers
before the generic deferred-constant barrier.  Initializers which would
require CO-RE relocations are diagnosed.  Support for such initializers
could be added in the future by generating relocated runtime
initialization code, for cases such as:

   struct task_struct {
     ...
     int x;
     ...
   } __attribute__((preserve_access_index));

   static size_t OFF_X = offsetof (struct task_struct, x);

Curious whether you tried compiling the kernel BPF selftests with this
patch and whether this was actually a problem in practice, i.e.
whether any of the selftests fail to compile.

I will check and experiment a bit, but we might need to support this.

Note you should also add ChangeLog entires for each patch.

Thanks!


Signed-off-by: York Jasper Niebuhr <[email protected]>
---
  gcc/config/bpf/bpf-passes.def                 |   1 +
  gcc/config/bpf/bpf-protos.h                   |   3 +
  gcc/config/bpf/bpf.cc                         |  24 +
  gcc/config/bpf/core-builtins.cc               | 637 ++++++++++++++++--
  .../gcc.target/bpf/core-auto-drain-1.c        |  29 +
  .../gcc.target/bpf/core-auto-enum-value-1.c   |  33 +
  .../gcc.target/bpf/core-auto-field-offset-1.c |  36 +
  7 files changed, 712 insertions(+), 51 deletions(-)
  create mode 100644 gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c
  create mode 100644 gcc/testsuite/gcc.target/bpf/core-auto-enum-value-1.c
  create mode 100644 gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c

diff --git a/gcc/config/bpf/bpf-passes.def b/gcc/config/bpf/bpf-passes.def
index eb0e9837d3a..eb0507fbec0 100644
--- a/gcc/config/bpf/bpf-passes.def
+++ b/gcc/config/bpf/bpf-passes.def
@@ -18,3 +18,4 @@
     <http://www.gnu.org/licenses/>.  */
INSERT_PASS_BEFORE (pass_lower_omp, 1, pass_lower_bpf_core);
+INSERT_PASS_BEFORE (pass_deferred_cst_barrier, 1, pass_bpf_deferred_static);
diff --git a/gcc/config/bpf/bpf-protos.h b/gcc/config/bpf/bpf-protos.h
index eee260b799b..db1e379577b 100644
--- a/gcc/config/bpf/bpf-protos.h
+++ b/gcc/config/bpf/bpf-protos.h
@@ -36,6 +36,9 @@ const char *bpf_output_move (rtx *operands, const char 
*templ);
  class gimple_opt_pass;
  gimple_opt_pass *make_pass_lower_bpf_core (gcc::context *ctxt);
+class simple_ipa_opt_pass;
+simple_ipa_opt_pass *make_pass_bpf_deferred_static (gcc::context *ctxt);
+
  bool bpf_expand_cpymem (rtx *, bool);
  bool bpf_expand_setmem (rtx *);
diff --git a/gcc/config/bpf/bpf.cc b/gcc/config/bpf/bpf.cc
index d852e2fbd70..06fd34ff542 100644
--- a/gcc/config/bpf/bpf.cc
+++ b/gcc/config/bpf/bpf.cc
@@ -138,6 +138,25 @@ bpf_handle_preserve_access_index_attribute (tree *node, 
tree name,
    return NULL_TREE;
  }
+/* Handle preserve_enum_values attribute, which can be applied to
+   enums.  Just warn for non-enumeration types.  */
+
+static tree
+bpf_handle_preserve_enum_values_attribute (tree *node, tree name,
+                                          tree args ATTRIBUTE_UNUSED,
+                                          int flags ATTRIBUTE_UNUSED,
+                                          bool *no_add_attrs)
+{
+  if (TREE_CODE (*node) != ENUMERAL_TYPE)
+    {
+      warning (OPT_Wattributes,
+              "%qE attribute only applies to enumeration types", name);
+      *no_add_attrs = true;
+    }
+
+  return NULL_TREE;
+}
+
  /* Target-specific attributes.  */
TARGET_GNU_ATTRIBUTES (bpf_attribute_table,
@@ -155,6 +174,11 @@ TARGET_GNU_ATTRIBUTES (bpf_attribute_table,
   { "preserve_access_index", 0, -1, false, true, false, true,
     bpf_handle_preserve_access_index_attribute, NULL },
+ /* CO-RE supoort: attribute to mark that all occurrences of values
+    of the declared enum should be recorded.  */
+ { "preserve_enum_values", 0, 0, false, true, false, true,
+   bpf_handle_preserve_enum_values_attribute, NULL },
+
   /* Support for `naked' function attribute.  */
   { "naked", 0, 1, false, false, false, false,
     bpf_handle_fndecl_attribute, NULL }
diff --git a/gcc/config/bpf/core-builtins.cc b/gcc/config/bpf/core-builtins.cc
index a5c973cd385..9930026119e 100644
--- a/gcc/config/bpf/core-builtins.cc
+++ b/gcc/config/bpf/core-builtins.cc
@@ -42,6 +42,9 @@ along with GCC; see the file COPYING3.  If not see
  #include "tree-pass.h"
  #include "plugin.h"
  #include "gimplify.h"
+#include "gimplify-me.h"
+#include "cgraph.h"
+#include "deferred-cst.h"
#include "ctfc.h"
  #include "btf.h"
@@ -356,6 +359,45 @@ is_attr_preserve_access (tree t)
    return false;
  }
+/* Like is_attr_preserve_access, but FIELD is a FIELD_DECL. Returns
+   true if FIELD belongs to a struct type with the
+   PRESERVE_ACCESS_INDEX attribute.  */
+
+static bool
+is_attr_preserve_access_field (tree field)
+{
+  gcc_assert (field && TREE_CODE (field) == FIELD_DECL);
+
+  tree type = DECL_FIELD_CONTEXT (field);
+
+  return (type
+         && TREE_CODE (type) == RECORD_TYPE
+         && lookup_attribute ("preserve_access_index",
+                              TYPE_ATTRIBUTES (type)));
+}
+
+/* Handling for __attribute__((preserve_enum_values)) for BPF CO-RE support.
+
+   This attribute marks an enum type as "preserve", so that every use
+   of its values should be recorded and replayed by the BPF loader;
+   This is just the same functionality as __builtin_preserve_enum_value,
+   but in the form of an attribute for an entire enumeral type.  */
+
+/* True if DECL is a literal of an enumeral type which is marked with the
+   PRESERVE_ENUM_VALUES attribute.  */
+
+static bool
+is_attr_preserve_enum_values (tree decl)
+{
+  gcc_assert (TREE_CODE (decl) == CONST_DECL);
+
+  tree type = TREE_TYPE (decl);
+  gcc_assert (TREE_CODE (type) == ENUMERAL_TYPE);
+
+  return lookup_attribute ("preserve_enum_values",
+                          TYPE_ATTRIBUTES (type)) != NULL_TREE;
+}
+
  static tree
  root_for_core_field_info (tree node)
  {
@@ -812,7 +854,6 @@ process_field_expr (struct cr_builtins *data)
    return ret;
  }
-static GTY(()) hash_map<tree, tree> *bpf_enum_mappings;
  tree enum_value_type = NULL_TREE;
static int
@@ -832,6 +873,74 @@ get_index_for_enum_value (tree type, tree expr)
    return -1;
  }
+static bool
+deferred_enum_value_call_p (tree expr)
+{
+  return (expr
+         && TREE_CODE (expr) == CALL_EXPR
+         && CALL_EXPR_IFN (expr) == IFN_DEFERRED_CST_ENUM_VALUE);
+}
+
+static tree
+enum_decl_from_deferred_call (tree call)
+{
+  if (!deferred_enum_value_call_p (call)
+      || call_expr_nargs (call) != 1)
+    return NULL_TREE;
+
+  tree decl
+    = deferred_cst_ifn_enum_value_decl (CALL_EXPR_ARG (call, 0));
+
+  if (!decl
+      || TREE_CODE (decl) != CONST_DECL
+      || TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE)
+    return NULL_TREE;
+
+  return decl;
+}
+
+static bool
+deferred_field_offset_call_p (tree expr)
+{
+  return (expr
+         && TREE_CODE (expr) == CALL_EXPR
+         && CALL_EXPR_IFN (expr) == IFN_DEFERRED_CST_FIELD_OFFSET);
+}
+
+static tree
+field_decl_from_deferred_call (tree call)
+{
+  if (!deferred_field_offset_call_p (call)
+      || call_expr_nargs (call) != 1)
+    return NULL_TREE;
+
+  tree field
+    = deferred_cst_ifn_field_offset_field (CALL_EXPR_ARG (call, 0));
+
+  if (!field || TREE_CODE (field) != FIELD_DECL)
+    return NULL_TREE;
+
+  return field;
+}
+
+/* Helper for pack_enum_value to retrieve the CONST_DECL for an enum
+   value that is given as argument to __builtin_preserve_enum_value.
+
+   ENUM_VALUE is expected to be a DEFERRED_CST_EXPR wrapping only a
+   call to IFN_DEFERRED_CST_ENUM_VALUE, resembling a builtin parameter
+   that is only a canonical enum value (no complex expressions).
+
+   Returns NULL_TREE on failure.  */
+
+static tree
+deferred_cst_canonical_enum_value_decl (tree enum_value)
+{
+  if (!enum_value || TREE_CODE (enum_value) != DEFERRED_CST_EXPR)
+    return NULL_TREE;
+
+  return enum_decl_from_deferred_call (TREE_OPERAND (enum_value, 0));
+}
+
  /* Pack helper for the __builtin_preserve_enum_value.  */
static struct cr_local
@@ -842,9 +951,8 @@ pack_enum_value (tree *args, enum btf_core_reloc_kind kind,
    ret.reloc_decision = REPLACE_CREATE_RELOCATION;
    ret.fail = false;
- tree *result = NULL;
    tree tmp = args[0];
-  tree enum_value = args[1];
+  tree deferred_enum_value = args[1];
    tree type = NULL_TREE;
/* Deconstructing "*(typeof (enum_type) *) enum_value" to collect both the
@@ -859,33 +967,25 @@ pack_enum_value (tree *args, enum btf_core_reloc_kind 
kind,
        ret.fail = true;
      }
- if (TREE_CODE (enum_value) != INTEGER_CST)
-    goto pack_enum_value_fail;
-
-  result = bpf_enum_mappings->get (enum_value);
-  if (result == NULL)
-    goto pack_enum_value_fail;
-
-  tmp = *result;
-
-  if (TREE_CODE (tmp) != CONST_DECL)
+  tree enum_value
+    = deferred_cst_canonical_enum_value_decl (deferred_enum_value);
+  if (enum_value == NULL_TREE)
      {
-pack_enum_value_fail:
        bpf_error ("invalid enum value argument for enum value builtin");
        ret.fail = true;
      }
    else
      {
-      ret.reloc_data.expr = tmp;
+      ret.reloc_data.expr = enum_value;
        if (kind == BPF_RELO_ENUMVAL_VALUE)
-       ret.reloc_data.default_value = enum_value;
+       ret.reloc_data.default_value = DECL_INITIAL (enum_value);
        else
        ret.reloc_data.default_value = integer_one_node;
      }
- if (ret.fail == false )
+  if (ret.fail == false)
      {
-      int index = get_index_for_enum_value (type, tmp);
+      int index = get_index_for_enum_value (type, enum_value);
        if (index == -1 || index >= (1 << 16))
        {
          bpf_error ("enum value in CO-RE builtin cannot be represented");
@@ -1101,10 +1201,15 @@ read_kind (tree kind, char max_value, char enum_offset)
    if (kind == NULL_TREE)
      goto invalid_kind_arg_error;
- if (TREE_CODE (kind) != CONST_DECL
-      && TREE_CODE (kind) == NOP_EXPR)
+  if (TREE_CODE (kind) == NOP_EXPR)
      kind = TREE_OPERAND (kind, 0);
+ if (TREE_CODE (kind) == DEFERRED_CST_EXPR)
+    kind = deferred_cst_canonical_enum_value_decl (kind);
+
+  if (kind == NULL_TREE)
+    goto invalid_kind_arg_error;
+
    if (TREE_CODE (kind) == CONST_DECL)
      kind = DECL_INITIAL (kind);
@@ -1178,8 +1283,10 @@ kind_preserve_type_info (tree *args, int nargs)
    return BPF_RELO_INVALID;
  }
-/* Plugin handler used in the parser that allows to collect enum value
-   information that other wise would be folded and non recoverable.  */
+/* Plugin handler used in the parser that allows to mark all enum types
+   and struct types attributed with "preserve_access_index" for constant
+   deferral.  This preserves information that would otherwise be
+   folded by the frontend and non recoverable.  */
void
  bpf_handle_plugin_finish_type (void *event_data,
@@ -1187,22 +1294,12 @@ bpf_handle_plugin_finish_type (void *event_data,
  {
    tree type = (tree) event_data;
- if (bpf_enum_mappings == NULL)
-    bpf_enum_mappings = hash_map<tree, tree>::create_ggc (10);
-
    if (TREE_CODE (type) == ENUMERAL_TYPE)
-    for (tree l = TYPE_VALUES (type); l; l = TREE_CHAIN (l))
-      {
-       tree value = TREE_VALUE (l);
-
-       tree initial = DECL_INITIAL (value);
-       initial = copy_node (initial);
-       DECL_INITIAL (value) = initial;
-
-       tree *found = bpf_enum_mappings->get (initial);
-       if (found == NULL)
-         bpf_enum_mappings->put (initial, value);
-      }
+    deferred_cst_mark_type (type);
+  else if (TREE_CODE (type) == RECORD_TYPE
+          && lookup_attribute ("preserve_access_index",
+                               TYPE_ATTRIBUTES (type)))
+    deferred_cst_mark_type (type);
  }
/* Initializes support information to process CO-RE builtins.
@@ -1258,6 +1355,25 @@ bpf_init_core_builtins (void)
                     bpf_handle_plugin_finish_type, NULL);
  }
+static tree
+construct_core_reloc_from_data (location_t loc,
+                               struct cr_builtins *reloc_data,
+                               builtin_helpers helper)
+{
+  int index = search_builtin_data (helper.compare, reloc_data);
+
+  if (index == -1)
+    index = allocate_builtin_data ();
+
+  struct cr_builtins *data = get_builtin_data (index);
+  memcpy (data, reloc_data, sizeof (struct cr_builtins));
+
+  tree fndecl = bpf_builtins[BPF_BUILTIN_CORE_RELOC];
+
+  return build_call_expr_loc (loc, fndecl, 1,
+                             build_int_cst (integer_type_node, index));
+}
+
  /* This function returns the related __builtin_core_reloc call tree node to a
     particular CO-RE builtin definition in FNDECL when called with
     arguments ARGS.  */
@@ -1294,23 +1410,364 @@ construct_builtin_core_reloc (location_t loc, tree 
fndecl, tree *args,
        return error_mark_node;
if (local_data.reloc_decision == REPLACE_CREATE_RELOCATION)
+       return construct_core_reloc_from_data (loc,
+                                              &local_data.reloc_data,
+                                              helper);
+    }
+  return NULL_TREE;
+}
+
+/* Build a relocation for the enumerator DECL at LOC.  */
+
+static tree
+bpf_core_enum_value_reloc (location_t loc, tree decl)
+{
+  gcc_assert (TREE_CODE (decl) == CONST_DECL);
+
+  tree type = TREE_TYPE (decl);
+  gcc_assert (TREE_CODE (type) == ENUMERAL_TYPE);
+
+  int enum_index = get_index_for_enum_value (type, decl);
+
+  if (enum_index < 0 || enum_index >= (1 << 16))
+    {
+      error_at (loc,
+               "enum value cannot be represented in BPF CO-RE relocation");
+      return error_mark_node;
+    }

Hm, isn't this exact check already done by pack_enum_type ?
Is it needed also here?

+
+  struct cr_builtins data;
+  memset (&data, 0, sizeof (data));
+
+  data.expr = decl;
+  data.type = type;
+  data.default_value = DECL_INITIAL (decl);
+  data.kind = BPF_RELO_ENUMVAL_VALUE;
+  data.orig_builtin_code = BPF_BUILTIN_PRESERVE_ENUM_VALUE;
+  data.orig_arg_expr = decl;
+
+  builtin_helpers helper
+    = core_builtin_helpers[BPF_BUILTIN_PRESERVE_ENUM_VALUE];
+
+  return construct_core_reloc_from_data (loc, &data, helper);
+}
+
+/* Build a relocation for the offset of FIELD at LOC.  Internally
+   constructs a component reference for FIELD and passes it through
+   the existing preserve-field-info builtin machinery.  */
+
+static tree
+bpf_core_field_offset_reloc (location_t loc, tree field)
+{
+  gcc_assert (TREE_CODE (field) == FIELD_DECL);
+
+  tree record_type = DECL_FIELD_CONTEXT (field);
+  gcc_assert (TREE_CODE (record_type) == RECORD_TYPE);
+
+  /* Build an artificial COMPONENT_REF solely to feed the existing
+     preserve-field-info packing machinery.  */
+  tree object = build_decl (loc, VAR_DECL, NULL_TREE, record_type);
+  DECL_ARTIFICIAL (object) = 1;
+  DECL_IGNORED_P (object) = 1;
+
+  tree ref = build3_loc (loc, COMPONENT_REF, TREE_TYPE (field),
+                        object, field, NULL_TREE);
+
+  tree args[2];
+  args[0] = ref;
+  args[1] = build_int_cst (integer_type_node, BPF_FIELD_BYTE_OFFSET);
+
+  tree fndecl = bpf_builtins[BPF_BUILTIN_PRESERVE_FIELD_INFO];
+
+  return construct_builtin_core_reloc (loc, fndecl, args, 2);
+}
+
+enum bpf_deferred_mode
+{
+  BPF_DEFERRED_GIMPLE,
+  BPF_DEFERRED_STATIC
+};
+
+
+/* Lower the expression EXPR under a DEFERRED_CST_EXPR wrapper according
+   to MODE.
+
+   Deferred enum values and field offsets selected for CO-RE via type
+   attributes are replaced by corresponding relocation expressions.
+
+   Deferred values that are not selected for CO-RE are resolved to
+   their ordinary compile-time values.
+
+   In BPF_DEFERRED_STATIC mode, CO-RE relocations may not be emitted.
+   Future instrumentation logic could automatically generate update-code
+   or relocations for static data that depends on CO-RE values.
+*/
+
+static tree
+bpf_lower_deferred_inner (tree expr, enum bpf_deferred_mode mode)
+{
+  if (!expr)
+    return NULL_TREE;
+
+  if (CONSTANT_CLASS_P (expr))
+    return expr;
+
+  if (TREE_CODE (expr) == DEFERRED_CST_EXPR)
+    {
+      error_at (EXPR_LOCATION (expr), "nested deferred constant expression");
+      return error_mark_node;

Can this error case result from valid code, or is it something that would
only arise from the compiler doing something incorrect?

+    }
+
+  if (deferred_enum_value_call_p (expr))
+    {
+      tree decl = enum_decl_from_deferred_call (expr);
+
+      if (!decl)
+       {
+         error_at (EXPR_LOCATION (expr),
+                   "malformed deferred enum value");
+         return error_mark_node;

Same question here, and I think once more below.

If these malformations are a result of compiler doing something wrong
then I think a gcc_assert (decl) is warranted instead, i.e. ICE.

+       }
+
+      if (!is_attr_preserve_enum_values (decl))
+       return fold_convert_loc (EXPR_LOCATION (expr),
+                                TREE_TYPE (expr),
+                                DECL_INITIAL (decl));
+
+      if (mode == BPF_DEFERRED_STATIC)
+       {
+         error_at (EXPR_LOCATION (expr),
+                   "BPF CO-RE enum values are not yet supported "
+                   "in static initializers");
+
+         /* Remove the deferred node after diagnosing, so that the generic
+            deferred-CST barrier doesn't diagnose it again.  */
+         return fold_convert_loc (EXPR_LOCATION (expr),
+                                  TREE_TYPE (expr),
+                                  DECL_INITIAL (decl));
+       }
+
+      tree reloc
+       = bpf_core_enum_value_reloc (EXPR_LOCATION (expr), decl);
+
+      if (reloc == error_mark_node)
+       return reloc;
+
+      return fold_convert_loc (EXPR_LOCATION (expr),
+                              TREE_TYPE (expr), reloc);
+    }
+
+  if (deferred_field_offset_call_p (expr))
+    {
+      tree field = field_decl_from_deferred_call (expr);
+
+      if (!field)
        {
-         int index = search_builtin_data (helper.compare,
-                                          &local_data.reloc_data);
-         if (index == -1)
-           index = allocate_builtin_data ();
-         struct cr_builtins *data = get_builtin_data (index);
-         memcpy (data, &local_data.reloc_data, sizeof (struct cr_builtins));
-
-         tree fndecl = bpf_builtins[BPF_BUILTIN_CORE_RELOC];
-         return  build_call_expr_loc (loc,
-                               fndecl, 1,
-                               build_int_cst (integer_type_node, index));
+         error_at (EXPR_LOCATION (expr),
+                   "malformed deferred field offset");
+         return error_mark_node;
        }
+
+      if (!is_attr_preserve_access_field (field))
+       return fold_convert_loc (EXPR_LOCATION (expr),
+                                TREE_TYPE (expr),
+                                byte_position (field));
+
+      if (mode == BPF_DEFERRED_STATIC)
+       {
+         error_at (EXPR_LOCATION (expr),
+                   "BPF CO-RE field offsets are not yet supported "
+                   "in static initializers");
+
+         return fold_convert_loc (EXPR_LOCATION (expr),
+                                  TREE_TYPE (expr),
+                                  byte_position (field));
+       }
+
+      tree reloc
+       = bpf_core_field_offset_reloc (EXPR_LOCATION (expr), field);
+
+      if (reloc == error_mark_node)
+       return reloc;
+
+      return fold_convert_loc (EXPR_LOCATION (expr),
+                              TREE_TYPE (expr), reloc);
      }
+
+  tree copy = copy_node (expr);
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    {
+      tree op = TREE_OPERAND (expr, i);
+
+      if (!op)
+       continue;
+
+      TREE_OPERAND (copy, i)
+       = bpf_lower_deferred_inner (op, mode);
+    }
+
+  return mode == BPF_DEFERRED_STATIC ? fold (copy) : copy;
+}
+
+/* Lower a deferred constant expression WRAPPER according to the
+   transformations defined in bpf_lower_deferred_inner.  */
+
+static tree
+bpf_lower_deferred_wrapper (tree wrapper, enum bpf_deferred_mode mode)
+{
+  gcc_assert (wrapper && TREE_CODE (wrapper) == DEFERRED_CST_EXPR);
+
+  tree inner = TREE_OPERAND (wrapper, 0);
+  return bpf_lower_deferred_inner (inner, mode);
+}
+
+/* Tree-walk callback for lowering deferred constants in GIMPLE statements.
+
+   Replaces each DEFERRED_CST_EXPR with its lowered and gimplified
+   equivalent.  Any new gimple statements are inserted immediately
+   before the current statement.  */
+
+static tree
+bpf_lower_deferred_tree (tree *tp, int *walk_subtrees, void *data)
+{
+  tree node = *tp;
+
+  if (!node)
+    return NULL_TREE;
+
+  if (TYPE_P (node) || DECL_P (node))
+    {
+      *walk_subtrees = 0;
+      return NULL_TREE;
+    }
+
+  if (TREE_CODE (node) != DEFERRED_CST_EXPR)
+    return NULL_TREE;
+
+  struct walk_stmt_info *wi
+    = static_cast<struct walk_stmt_info *> (data);
+
+  /* First transform the complete deferred expression.  */
+  tree replacement
+    = bpf_lower_deferred_wrapper (node, BPF_DEFERRED_GIMPLE);
+
+  if (replacement == error_mark_node)
+    {
+      *tp = replacement;
+      *walk_subtrees = 0;
+      return NULL_TREE;
+    }
+
+  /* Turn the resulting GENERIC expression into a GIMPLE value.  Any
+     statements required to compute it are emitted into BEFORE.  */
+  gimple_seq before = NULL;
+
+  push_gimplify_context ();
+
+  gimplify_expr (&replacement, &before, NULL,
+                is_gimple_val, fb_rvalue);
+
+  pop_gimplify_context (NULL);
+
+  /* Insert computation of REPLACEMENT immediately before the
+     statement containing the original DEFERRED_CST_EXPR.  */
+  if (before)
+    gsi_insert_seq_before (&wi->gsi, before, GSI_SAME_STMT);
+
+  /* REPLACEMENT is now a valid GIMPLE value.  */
+  *tp = replacement;
+
+  /* Do not walk the newly generated expression.  */
+  *walk_subtrees = 0;
+
    return NULL_TREE;
  }
+/* Return true if the initializer expression EXPR contains deferred
+   constants.  */
+
+static bool
+bpf_initializer_has_deferred (tree expr)
+{
+  if (!expr || DECL_P (expr) || TYPE_P (expr))
+    return false;
+
+  if (TREE_CODE (expr) == DEFERRED_CST_EXPR)
+    return true;
+
+  if (TREE_CODE (expr) == CONSTRUCTOR)
+    {
+      unsigned HOST_WIDE_INT i;
+      tree index, value;
+
+      FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (expr), i, index, value)
+       if (bpf_initializer_has_deferred (value))
+         return true;
+
+      return false;
+    }
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    if (bpf_initializer_has_deferred (TREE_OPERAND (expr, i)))
+      return true;
+
+  return false;
+}
+
+/* Resolves deferred constants in the static initializer expression
+   EXPR.  Deferred constants that do not require CO-RE relocations
+   (because the corresponding types are not attributed accordingly)
+   are replaced with their ordinary compile-time values.
+
+   Expressions that would require CO-RE relocations are diagnosed as
+   errors.  Support for those may be added in the future.  */
+
+static tree
+bpf_transform_initializer (tree expr)
+{
+  if (!expr || DECL_P (expr) || TYPE_P (expr) || CONSTANT_CLASS_P (expr))
+    return expr;
+
+  if (TREE_CODE (expr) == DEFERRED_CST_EXPR)
+    return bpf_lower_deferred_wrapper (expr, BPF_DEFERRED_STATIC);
+
+  if (TREE_CODE (expr) == CONSTRUCTOR)
+    {
+      vec<constructor_elt, va_gc> *elts = NULL;
+      unsigned HOST_WIDE_INT i;
+      tree index, value;
+
+      FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (expr), i, index, value)
+       {
+         tree replacement = bpf_transform_initializer (value);
+         CONSTRUCTOR_APPEND_ELT (elts, index, replacement);
+       }
+
+      tree result = build_constructor (TREE_TYPE (expr), elts);
+
+      TREE_CONSTANT (result) = TREE_CONSTANT (expr);
+      TREE_STATIC (result) = TREE_STATIC (expr);
+
+      return result;
+    }
+
+  if (!bpf_initializer_has_deferred (expr))
+    return expr;
+
+  tree copy = copy_node (expr);
+
+  for (int i = 0; i < TREE_OPERAND_LENGTH (expr); ++i)
+    {
+      tree op = TREE_OPERAND (expr, i);
+
+      if (op)
+       TREE_OPERAND (copy, i) = bpf_transform_initializer (op);
+    }
+
+  return fold (copy);
+}
+
  /* This function constructs the CO-RE safe code around field expressions.
     If the expression is an array access, create an offset by multiplying the
     index access by the __builtin_type_info call requesting the size of the
@@ -1944,11 +2401,13 @@ core_make_builtins (tree *tp, int *walk_subtrees, void 
*data)
    return NULL_TREE;
  }
-/* This is the entry point for the pass_data_lower_bpg_core. It walks all the
+/* This is the entry point for the pass_lower_bpf_core.  It walks all the
     statements in gimple, looking for expressions that are suppose to be CO-RE
     preserve_access_index attributed, and should not.
-   It first splits CO-RE expressions from non CO-RE ones.
-   Then the CO-RE expressions are processed by core_make_builtins which will
+   It first instruments only deferred constant field offsets and enum values,
+   turning those relevant to CO-RE into relocations.
+   Then it splits all CO-RE expressions from non CO-RE ones.
+   Finally, the CO-RE expressions are processed by core_make_builtins which 
will
     create the required builtins that will result in the CO-RE relocations.  */
  static unsigned int
  execute_lower_bpf_core (void)
@@ -1962,6 +2421,11 @@ execute_lower_bpf_core (void)
    struct walk_stmt_info wi;
    memset (&wi, 0, sizeof (wi));
+ /* Deferred constants are still represented as GENERIC expression trees
+     embedded in GIMPLE operands.  Replace their leaves with ordinary
+     constants or BPF CO-RE relocation calls.  */
+  walk_gimple_seq_mod (&body, NULL, bpf_lower_deferred_tree, &wi);
+
    /* Early split to guarantee base of expression is a preserve_access_index
       structure.  */
    walk_gimple_seq_mod (&body, NULL, gimple_core_early_split_expr, &wi);
@@ -1971,6 +2435,45 @@ execute_lower_bpf_core (void)
    return 0;
  }
+/* This is the entry point for pass_bpf_deferred_static. It iterates
+   over all static initializers to lower deferred constants.  */
+
+static unsigned int
+execute_bpf_deferred_static (void)
+{
+  if (!TARGET_BPF_CORE)
+    return 0;
+
+  varpool_node *vnode;
+
+  FOR_EACH_VARIABLE (vnode)
+    {
+      tree decl = vnode->decl;
+
+      if (!decl
+         || TREE_CODE (decl) != VAR_DECL
+         || DECL_EXTERNAL (decl)
+         || !TREE_STATIC (decl))
+       continue;
+
+      tree init = DECL_INITIAL (decl);
+
+      if (!init || !bpf_initializer_has_deferred (init))
+       continue;
+
+      tree replacement = bpf_transform_initializer (init);
+
+      DECL_INITIAL (decl) = replacement;
+
+      /* Even after emitting an error for an attributed leaf we replace it by
+        its local compile-time value.  Therefore absolutely no deferred node
+        should survive this pass.  */
+      gcc_assert (!bpf_initializer_has_deferred (replacement));
+    }
+
+  return 0;
+}
+
  namespace {
const pass_data pass_data_lower_bpf_core =
@@ -2001,6 +2504,32 @@ public:
}; /* class pass_lower_bpf_core */ +const pass_data pass_data_bpf_deferred_static =
+{
+  SIMPLE_IPA_PASS, /* type */
+  "bpf_deferred_static", /* name */
+  OPTGROUP_NONE, /* optinfo_flags */
+  TV_NONE, /* tv_id */
+  0, /* properties_required */
+  0, /* properties_provided */
+  0, /* properties_destroyed */
+  0, /* todo_flags_start */
+  0, /* todo_flags_finish */
+};
+
+class pass_bpf_deferred_static : public simple_ipa_opt_pass
+{
+public:
+  pass_bpf_deferred_static (gcc::context *ctxt)
+    : simple_ipa_opt_pass (pass_data_bpf_deferred_static, ctxt)
+  {}
+
+  unsigned int execute (function *) final override
+  {
+    return execute_bpf_deferred_static ();
+  }
+};
+
  } /* anon namespace */
gimple_opt_pass *
@@ -2009,4 +2538,10 @@ make_pass_lower_bpf_core (gcc::context *ctxt)
    return new pass_lower_bpf_core (ctxt);
  }
+simple_ipa_opt_pass *
+make_pass_bpf_deferred_static (gcc::context *ctxt)
+{
+  return new pass_bpf_deferred_static (ctxt);
+}
+
  #include "gt-core-builtins.h"
diff --git a/gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c 
b/gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c
new file mode 100644
index 00000000000..660b5df9d3f
--- /dev/null
+++ b/gcc/testsuite/gcc.target/bpf/core-auto-drain-1.c
@@ -0,0 +1,29 @@
+/* { dg-do compile } */
+/* { dg-options "-O0 -dA -gbtf -mco-re -masm=normal" } */
+
+enum E
+{
+  A = 1,
+  B = 2
+};
+
+int
+foo (void)
+{
+  return B;
+}
+
+struct S
+{
+  int a;
+  long b;
+  int c;
+};
+
+unsigned long
+bar (void)
+{
+  return __builtin_offsetof (struct S, c);
+}
+
+/* { dg-final { scan-assembler-not "bpfcr_kind" } } */
diff --git a/gcc/testsuite/gcc.target/bpf/core-auto-enum-value-1.c 
b/gcc/testsuite/gcc.target/bpf/core-auto-enum-value-1.c
new file mode 100644
index 00000000000..2bd21fa6146
--- /dev/null
+++ b/gcc/testsuite/gcc.target/bpf/core-auto-enum-value-1.c
@@ -0,0 +1,33 @@
+/* { dg-do compile } */
+/* { dg-options "-O0 -dA -gbtf -mco-re -masm=normal" } */
+
+enum E
+{
+  A = 1,
+  B = 1,
+  C = 3
+} __attribute__((preserve_enum_values));
+
+int
+foo (void)
+{
+  return A + B + C;
+}
+
+/* Check the local values.  A and B deliberately have the same value.  */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],1" 2 } } */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],3" 1 } } */
+
+/* Check the BTF access strings for the three enumerators.  */
+/* { dg-final { scan-assembler-times "ascii \"0.0\"\[\t 
\]+\[^\n\]*btf_aux_string" 1 } } */
+/* { dg-final { scan-assembler-times "ascii \"1.0\"\[\t 
\]+\[^\n\]*btf_aux_string" 1 } } */
+/* { dg-final { scan-assembler-times "ascii \"2.0\"\[\t 
\]+\[^\n\]*btf_aux_string" 1 } } */
+
+/* Check that the relocations identify A, B and C independently.  */
+/* { dg-final { scan-assembler-times "bpfcr_type \\(E\\)" 3 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0\"\\)" 1 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"1\"\\)" 1 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"2\"\\)" 1 } } */
+
+/* All three are BPF_CORE_ENUMVAL_VALUE relocations.  */
+/* { dg-final { scan-assembler-times "0xb\[\t \]+\[^\n\]*bpfcr_kind" 3 } } */
diff --git a/gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c 
b/gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c
new file mode 100644
index 00000000000..e06d42ef45c
--- /dev/null
+++ b/gcc/testsuite/gcc.target/bpf/core-auto-field-offset-1.c
@@ -0,0 +1,36 @@
+/* { dg-do compile } */
+/* { dg-options "-O0 -dA -gbtf -mco-re -masm=normal" } */
+
+struct S
+{
+  int a;
+  long b;
+  int c;
+} __attribute__((preserve_access_index));
+
+unsigned long
+foo (void)
+{
+  return (__builtin_offsetof (struct S, a)
+         + __builtin_offsetof (struct S, b)
+         + __builtin_offsetof (struct S, c));
+}
+
+/* Check the local field offsets.  */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],0" 1 } } */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],8" 1 } } */
+/* { dg-final { scan-assembler-times "\[\t \]lddw\[\t \]%r\[0-9\],16" 1 } } */
+
+/* Check the BTF access strings.  */
+/* { dg-final { scan-assembler-times "ascii \"0:0.0\"\[\t 
\]+\[^\n\]*btf_aux_string" 1 } } */
+/* { dg-final { scan-assembler-times "ascii \"0:1.0\"\[\t 
\]+\[^\n\]*btf_aux_string" 1 } } */
+/* { dg-final { scan-assembler-times "ascii \"0:2.0\"\[\t 
\]+\[^\n\]*btf_aux_string" 1 } } */
+
+/* Check that each relocation identifies the correct field.  */
+/* { dg-final { scan-assembler-times "bpfcr_type \\(struct S\\)" 3 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0:0\"\\)" 1 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0:1\"\\)" 1 } } */
+/* { dg-final { scan-assembler-times "bpfcr_astr_off \\(\"0:2\"\\)" 1 } } */
+
+/* All three are BPF_FIELD_BYTE_OFFSET relocations.  */
+/* { dg-final { scan-assembler-times "0\[\t \]+\[^\n\]*bpfcr_kind" 3 } } */

Reply via email to