Add an opt-in mechanism for preserving select semantic origins of constant expressions through C frontend folding.
Normally, enum constants and field offsets lose their source-level identity when the C frontend folds them to INTEGER_CST nodes. Introduce DEFERRED_CST_EXPR to represent expressions which retain most of normal constant semantics while postponing their final evaluation. Consumers can mark RECORD_TYPE and ENUMERAL_TYPE nodes for constant deferral through the deferred-cst interface. Marking a type has no effect on the type's C semantics; it only causes selected constants originating from that type to retain their identity during folding. For marked enum types, references to enumerators are represented using a deferred enum-value expression which retains the originating CONST_DECL. For marked record types, fold_offsetof preserves field offsets using a deferred field-offset expression which retains the originating FIELD_DECL. If not types are marked for constant deferral, absolutely no DEFERRED_CST_EXPRs are ever generated! c_fully_fold propagates deferred constants through otherwise constant, side-effect-free expressions. Const-ness checks in static initializers permit deferred constants. It is the responsibility of the consumer that marked types for constant deferral to instrument all DEFERRED_CST_EXPRs before an IPA barrier pass that runs right after all_lowering_passes. Deferred constants may never survive beyond this lifetime boundary. Signed-off-by: York Jasper Niebuhr <[email protected]> --- gcc/Makefile.in | 4 +- gcc/c-family/c-common.cc | 109 ++- gcc/c/c-fold.cc | 173 +++++ gcc/c/c-typeck.cc | 55 +- gcc/deferred-cst.cc | 403 ++++++++++++ gcc/deferred-cst.h | 54 ++ gcc/gimple-expr.cc | 5 + gcc/gimple.cc | 3 +- gcc/gimplify.cc | 5 + gcc/internal-fn.cc | 18 + gcc/internal-fn.def | 6 + gcc/passes.def | 1 + .../gcc.dg/plugin/deferred_cst-test.c | 80 +++ .../gcc.dg/plugin/deferred_cst_plugin.cc | 619 ++++++++++++++++++ gcc/testsuite/gcc.dg/plugin/plugin.exp | 1 + gcc/tree-pass.h | 1 + gcc/tree-pretty-print.cc | 7 + gcc/tree.def | 10 + gcc/varasm.cc | 5 +- 19 files changed, 1541 insertions(+), 18 deletions(-) create mode 100644 gcc/deferred-cst.cc create mode 100644 gcc/deferred-cst.h create mode 100644 gcc/testsuite/gcc.dg/plugin/deferred_cst-test.c create mode 100644 gcc/testsuite/gcc.dg/plugin/deferred_cst_plugin.cc diff --git a/gcc/Makefile.in b/gcc/Makefile.in index 19e35f6149b..28816c2dc7d 100644 --- a/gcc/Makefile.in +++ b/gcc/Makefile.in @@ -1481,6 +1481,7 @@ OBJS = \ dce.o \ ddg.o \ debug.o \ + deferred-cst.o \ hierarchical_discriminator.o \ dep-fusion.o \ df-core.o \ @@ -3191,6 +3192,7 @@ GTFILES = $(CPPLIB_H) $(srcdir)/input.h $(srcdir)/coretypes.h \ $(srcdir)/internal-fn.h \ $(srcdir)/calls.cc \ $(srcdir)/analyzer/analyzer-language.cc \ + $(srcdir)/deferred-cst.cc \ @all_gtfiles@ # Compute the list of GT header files from the corresponding C sources, @@ -4207,7 +4209,7 @@ PLUGIN_HEADERS = $(TREE_H) $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \ lcm.h cfgloopmanip.h file-prefix-map.h builtins.def $(INSN_ATTR_H) \ pass-instances.def params.list $(srcdir)/../include/gomp-constants.h \ $(EXPR_H) $(srcdir)/analyzer/*.h $(srcdir)/diagnostics/*.h \ - $(srcdir)/text-art/*.h $(srcdir)/topics/*.h + $(srcdir)/text-art/*.h $(srcdir)/topics/*.h deferred-cst.h # generate the 'build fragment' b-header-vars s-header-vars: Makefile diff --git a/gcc/c-family/c-common.cc b/gcc/c-family/c-common.cc index 6380bec4515..ed69ffa2b9b 100644 --- a/gcc/c-family/c-common.cc +++ b/gcc/c-family/c-common.cc @@ -57,6 +57,7 @@ along with GCC; see the file COPYING3. If not see #include "gcc-rich-location.h" #include "gcc-urlifier.h" #include "diagnostics/diagnostics-selftests.h" +#include "deferred-cst.h" cpp_reader *parse_in; /* Declared in c-pragma.h. */ @@ -7215,13 +7216,33 @@ c_common_to_target_charset (HOST_WIDE_INT c) return uc; } +/* Helper for fold_offsetof_internal. Add OFFSET to the ACCUMULATOR + tree. */ +static void +accumulate_offset (tree *accumulator, tree offset) +{ + gcc_assert (accumulator); + gcc_assert (offset); + + offset = convert (sizetype, offset); + + if (*accumulator == NULL_TREE) + *accumulator = offset; + else + *accumulator = size_binop_loc ( + input_location, PLUS_EXPR, *accumulator, offset); +} + /* Fold an offsetof-like expression. EXPR is a nested sequence of component references with an INDIRECT_REF of a constant at the bottom; much like the traditional rendering of offsetof as a macro. TYPE is the desired type of - the whole expression. Return the folded result. */ + the whole expression. Return the folded result. NON_CST is set to the + sum of all non-constant portions of the offset. DEFERRED is set to the + deferred constant portion of the offset. */ -tree -fold_offsetof (tree expr, tree type, enum tree_code ctx) +static tree +fold_offsetof_internal (tree expr, tree type, enum tree_code ctx, tree *non_cst, + tree *deferred) { tree base, off, t; tree_code code = TREE_CODE (expr); @@ -7231,10 +7252,12 @@ fold_offsetof (tree expr, tree type, enum tree_code ctx) return expr; case REALPART_EXPR: - return fold_offsetof (TREE_OPERAND (expr, 0), type, code); + return fold_offsetof_internal (TREE_OPERAND (expr, 0), type, code, non_cst, + deferred); case IMAGPART_EXPR: - base = fold_offsetof (TREE_OPERAND (expr, 0), type, code); + base = fold_offsetof_internal (TREE_OPERAND (expr, 0), type, code, non_cst, + deferred); if (base == error_mark_node) return base; off = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (TREE_OPERAND (expr, 0)))); @@ -7259,7 +7282,8 @@ fold_offsetof (tree expr, tree type, enum tree_code ctx) return convert (type, TREE_OPERAND (expr, 0)); case COMPONENT_REF: - base = fold_offsetof (TREE_OPERAND (expr, 0), type, code); + base = fold_offsetof_internal (TREE_OPERAND (expr, 0), type, code, + non_cst, deferred); if (base == error_mark_node) return base; @@ -7270,13 +7294,21 @@ fold_offsetof (tree expr, tree type, enum tree_code ctx) "member %qD", t); return error_mark_node; } - off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t), - size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t)) - / BITS_PER_UNIT)); + if (deferred_cst_type_p (DECL_CONTEXT (t))) + { + off = deferred_cst_call_ifn_field_offset (EXPR_LOCATION (expr), t); + accumulate_offset (deferred, off); + return base; + } + else + off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t), + size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t)) + / BITS_PER_UNIT)); break; case ARRAY_REF: - base = fold_offsetof (TREE_OPERAND (expr, 0), type, code); + base = fold_offsetof_internal (TREE_OPERAND (expr, 0), type, code, + non_cst, deferred); if (base == error_mark_node) return base; @@ -7328,13 +7360,26 @@ fold_offsetof (tree expr, tree type, enum tree_code ctx) t = convert (sizetype, t); off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t); + + /* For classification as cst/non-cst, the array index has to be + fully folded. */ + off = c_fully_fold (off, false, NULL); + + if (off == error_mark_node) + return off; + + if (!TREE_CONSTANT (off)) + { + accumulate_offset (non_cst, off); + return base; + } break; case COMPOUND_EXPR: /* Handle static members of volatile structs. */ t = TREE_OPERAND (expr, 1); gcc_checking_assert (VAR_P (get_base_address (t))); - return fold_offsetof (t, type); + return fold_offsetof_internal (t, type, ERROR_MARK, non_cst, deferred); default: gcc_unreachable (); @@ -7344,6 +7389,48 @@ fold_offsetof (tree expr, tree type, enum tree_code ctx) return size_binop (PLUS_EXPR, base, convert (type, off)); return fold_build_pointer_plus (base, off); } + +/* Like fold_offsetof_internal, but integrates deferred constant components + into the result. If such components exist, the result is wrapped in a + DEFERRED_CST_EXPR node. */ + +tree +fold_offsetof (tree expr, tree type, enum tree_code ctx) +{ + tree res = NULL_TREE; + tree non_cst = NULL_TREE; + tree deferred = NULL_TREE; + tree cst = fold_offsetof_internal (expr, type, ctx, &non_cst, &deferred); + + res = cst; + + if (res == error_mark_node) + return res; + + /* DEFERRED_CST_EXPRs contain only ordinary constants and deferred + constant components. */ + if (deferred != NULL_TREE) + { + if (POINTER_TYPE_P (type)) + res = fold_build_pointer_plus (res, convert (sizetype, deferred)); + else + res = size_binop (PLUS_EXPR, res, convert (type, deferred)); + + res = deferred_cst_build_expr (res); + } + + /* Runtime-dependent terms are added only after the deferred + boundary has been constructed. */ + if (non_cst != NULL_TREE) + { + if (POINTER_TYPE_P (type)) + res = fold_build_pointer_plus (res, convert (type, non_cst)); + else + res = size_binop (PLUS_EXPR, res, convert (type, non_cst)); + } + + return res; +} /* *PTYPE is an incomplete array. Complete it with a domain based on INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT diff --git a/gcc/c/c-fold.cc b/gcc/c/c-fold.cc index 40e8ae79727..0988f00ce93 100644 --- a/gcc/c/c-fold.cc +++ b/gcc/c/c-fold.cc @@ -26,9 +26,11 @@ along with GCC; see the file COPYING3. If not see #include "c-tree.h" #include "intl.h" #include "gimplify.h" +#include "deferred-cst.h" static tree c_fully_fold_internal (tree expr, bool, bool *, bool *, bool, bool); +static tree c_fully_fold_deferred_cst_internal (tree expr); /* If DISABLE is true, stop issuing warnings. This is used when parsing code that we know will not be executed. This function may @@ -123,6 +125,7 @@ c_fully_fold (tree expr, bool in_init, bool *maybe_const, bool lval) } ret = c_fully_fold_internal (expr, in_init, maybe_const, &maybe_const_itself, false, lval); + ret = c_fully_fold_deferred_cst_internal (ret); if (eptype) ret = fold_convert_loc (loc, eptype, ret); *maybe_const &= maybe_const_itself; @@ -718,6 +721,176 @@ c_fully_fold_internal (tree expr, bool in_init, bool *maybe_const_operands, return ret; } +/* Return true if CODE is an operation which may be absorbed into a + DEFERRED_CST_EXPR. */ + +static bool +deferred_cst_operator_p (enum tree_code code) +{ + switch (TREE_CODE_CLASS (code)) + { + case tcc_unary: + case tcc_binary: + case tcc_comparison: + return true; + + default: + break; + } + + switch (code) + { + case COND_EXPR: + case VEC_COND_EXPR: + return true; + + default: + return false; + } +} + +/* Internal helper for c_fully_fold. Fold surrounding constant + operations into DEFERRED_CST_EXPR nodes. + + An operation is absorbed when: + + - its tree code is explicitly supported by + deferred_cst_operator_p; + - every operand is constant-like; and + - at least one operand is a DEFERRED_CST_EXPR. + + Existing deferred wrappers are removed when an operation is absorbed, + giving a single outer DEFERRED_CST_EXPR. For example: + + DEFERRED_CST_EXPR (A) + 1 + -> DEFERRED_CST_EXPR (A + 1) + + (DEFERRED_CST_EXPR (A) + 1) * 2 + -> DEFERRED_CST_EXPR ((A + 1) * 2) + + DEFERRED_CST_EXPR (A) + DEFERRED_CST_EXPR (B) + -> DEFERRED_CST_EXPR (A + B) + + DEFERRED_CST_EXPR (C) ? 1 : 2 + -> DEFERRED_CST_EXPR (C ? 1 : 2) + + An operation involving a nonconstant operand is not absorbed: + + X + DEFERRED_CST_EXPR (A) + -> X + DEFERRED_CST_EXPR (A) */ + +static tree +c_fully_fold_deferred_cst_internal (tree expr) +{ + if (expr == NULL_TREE) + return NULL_TREE; + + enum tree_code code = TREE_CODE (expr); + + /* The true constants inside deferred constants can be folded here, + while the deferred components are represented as calls to + internal functions and thus can not and should not be folded + here. */ + if (code == DEFERRED_CST_EXPR) + { + tree old_inner = TREE_OPERAND (expr, 0); + + bool maybe_const_operands = true; + bool maybe_const_itself = true; + + tree inner + = c_fully_fold_internal (old_inner, false, + &maybe_const_operands, + &maybe_const_itself, + false, false); + + if (inner == old_inner) + return expr; + + return deferred_cst_build_expr (inner); + } + + /* Unsupported operations form a boundary for deferred folding. */ + if (!deferred_cst_operator_p (code)) + return expr; + + int nops = TREE_OPERAND_LENGTH (expr); + + /* Every currently-supported operator has at most three operands. */ + gcc_assert (nops >= 1 && nops <= 3); + + tree ops[3]; + bool changed = false; + bool has_deferred = false; + bool all_constant = true; + bool has_side_effects = false; + + for (int i = 0; i < nops; ++i) + { + tree old_op = TREE_OPERAND (expr, i); + tree op = c_fully_fold_deferred_cst_internal (old_op); + + ops[i] = op; + + if (op != old_op) + changed = true; + + if (TREE_CODE (op) == DEFERRED_CST_EXPR) + has_deferred = true; + else if (!TREE_CONSTANT (op)) + all_constant = false; + + if (TREE_SIDE_EFFECTS (op)) + has_side_effects = true; + } + + /* There is no deferred expression directly participating in this + operation, or there are non-constant operands or operands with + side effects involved, so the operation itself must not become + deferred. + + We may nevertheless need to propagate a transformation made in one + of the operands. */ + if (!has_deferred || !all_constant || has_side_effects) + { + if (!changed) + return expr; + + tree copy = copy_node (expr); + for (int i = 0; i < nops; i++) + TREE_OPERAND (copy, i) = ops[i]; + + return copy; + } + + /* Every operand is constant-like and at least one operand is + deferred. Move this complete operation inside one deferred + wrapper. */ + + tree inner = copy_node (expr); + for (int i = 0; i < nops; i++) + { + bool op_deferred_cst = ops[i] != NULL_TREE + && TREE_CODE (ops[i]) == DEFERRED_CST_EXPR; + TREE_OPERAND (inner, i) = op_deferred_cst + ? TREE_OPERAND (ops[i], 0) : ops[i]; + } + + bool maybe_const_operands = true; + bool maybe_const_itself = true; + + /* The true constants inside deferred constants can be folded here, + while the deferred components are represented as calls to + internal functions and thus can not and should not be folded + here. */ + inner = c_fully_fold_internal (inner, false, + &maybe_const_operands, + &maybe_const_itself, + false, false); + + return deferred_cst_build_expr (inner); +} + /* Fold X for consideration by one of the warning functions when checking whether an expression has a constant value. */ diff --git a/gcc/c/c-typeck.cc b/gcc/c/c-typeck.cc index 2d020085833..6813ec8d202 100644 --- a/gcc/c/c-typeck.cc +++ b/gcc/c/c-typeck.cc @@ -55,6 +55,7 @@ along with GCC; see the file COPYING3. If not see #include "realmpfr.h" #include "tree-pretty-print-markup.h" #include "gcc-urlifier.h" +#include "deferred-cst.h" /* Possible cases of implicit conversions. Used to select diagnostic messages and control folding initializers in convert_for_assignment. */ @@ -2293,6 +2294,17 @@ c_size_in_bytes (const_tree type) / BITS_PER_UNIT)); } +/* Return true if INIT is a valid deferred constant initializer. */ +static bool +deferred_constant_initializer_p (tree init) +{ + if (!init || !deferred_cst_present_p (init)) + return false; + + return initializer_constant_valid_p (init, TREE_TYPE (init)) + != NULL_TREE; +} + /* Return either DECL or its known constant value (if it has one). */ tree @@ -2307,7 +2319,8 @@ decl_constant_value_1 (tree decl, bool in_init) /* This is invalid if initial value is not constant. If it has either a function call, a memory reference, or a variable, then re-evaluating it could give different results. */ - && TREE_CONSTANT (DECL_INITIAL (decl)) + && (TREE_CONSTANT (DECL_INITIAL (decl)) + || deferred_constant_initializer_p (DECL_INITIAL (decl))) /* Check for cases where this is sub-optimal, even though valid. */ && (in_init || TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)) return DECL_INITIAL (decl); @@ -3865,6 +3878,33 @@ mark_decl_used (tree ref, bool address) } } +/* Return true if DECL is a literal of an enum type that is marked for + constant deferral. */ +static bool +deferred_cst_enum_literal_p (tree decl) +{ + if (TREE_CODE (decl) != CONST_DECL) + return false; + + tree enum_type = TREE_TYPE (decl); + + return (enum_type + && TREE_CODE (enum_type) == ENUMERAL_TYPE + && deferred_cst_type_p (enum_type)); +} + +/* Build a deferred constant for the enumeration constant DECL. */ +static tree +deferred_cst_build_enum_literal (tree decl) +{ + tree call + = deferred_cst_call_ifn_enum_value (DECL_SOURCE_LOCATION (decl), decl); + + gcc_assert (call != error_mark_node); + + return deferred_cst_build_expr (call); +} + /* Build an external reference to identifier ID. FUN indicates whether this will be used for a function call. LOC is the source @@ -3938,8 +3978,13 @@ build_external_ref (location_t loc, tree id, bool fun, tree *type) inform (DECL_SOURCE_LOCATION (ref), "enum constant defined here"); } - ref = DECL_INITIAL (ref); - TREE_CONSTANT (ref) = 1; + if (deferred_cst_enum_literal_p (ref)) + ref = deferred_cst_build_enum_literal (ref); + else + { + ref = DECL_INITIAL (ref); + TREE_CONSTANT (ref) = 1; + } } /* C99 6.7.4p3: An inline definition of a function with external linkage ... shall not contain a reference to an identifier with @@ -10269,7 +10314,9 @@ digest_init (location_t init_loc, tree decl, tree type, tree init, /* Check to see if we have already given an error message. */ if (inside_init == error_mark_node) ; - else if (require_constant && !TREE_CONSTANT (inside_init)) + else if (require_constant + && !TREE_CONSTANT (inside_init) + && !deferred_constant_initializer_p (inside_init)) { error_init (init_loc, "initializer element is not constant"); inside_init = error_mark_node; diff --git a/gcc/deferred-cst.cc b/gcc/deferred-cst.cc new file mode 100644 index 00000000000..261cd189e91 --- /dev/null +++ b/gcc/deferred-cst.cc @@ -0,0 +1,403 @@ +/* Deferred constant expression support for GCC. + Copyright (C) 2026 Free Software Foundation, Inc. + +This file is part of GCC. + +GCC is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free +Software Foundation; either version 3, or (at your option) any later +version. + +GCC is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License +along with GCC; see the file COPYING3. If not see +<http://www.gnu.org/licenses/>. */ + +#include "config.h" +#include "system.h" +#include "coretypes.h" +#include "tree.h" +#include "stringpool.h" +#include "fold-const.h" +#include "internal-fn.h" +#include "attribs.h" +#include "tree-pass.h" +#include "context.h" +#include "cgraph.h" +#include "function.h" +#include "cfg.h" +#include "basic-block.h" +#include "gimple.h" +#include "gimple-iterator.h" +#include "gimple-walk.h" +#include "diagnostic.h" + +#include "deferred-cst.h" + +struct deferred_cst_type_hasher : ggc_cache_ptr_hash<tree_node> +{ + static hashval_t + hash (tree t) + { + return htab_hash_pointer (t); + } +}; + +/* Set of types marked for constant deferral. */ +static GTY((cache)) hash_table<deferred_cst_type_hasher> *deferred_cst_types; + +/* Weak mappings from unique STRING_CST tokens used as arguments to + IFN_DEFERRED_CST_* calls to the tree associated with that call. + + IFN_DEFERRED_CST_FIELD_OFFSET (field_offset_decls) + Maps to the FIELD_DECL of the field whose offset the call + represents. + + IFN_DEFERRED_CST_ENUM_VALUE (enum_value_decls) + Maps to the CONST_DECL of the enum literal whose value the call + represents. */ +static GTY((cache)) tree_cache_map *field_offset_decls; +static GTY((cache)) tree_cache_map *enum_value_decls; + +/* Used only to make STRING_CST contents unique. The actual string + values have no semantic meaning; the STRING_CST nodes themselves + are the metadata tokens. */ +static unsigned HOST_WIDE_INT next_token = 0; + +static bool +markable_type_p (tree type) +{ + if (!type) + return false; + + switch (TREE_CODE (type)) + { + case RECORD_TYPE: + case ENUMERAL_TYPE: + return true; + default: + return false; + } +} + +void +deferred_cst_mark_type (tree type) +{ + type = TYPE_MAIN_VARIANT (type); + + if (!markable_type_p (type)) + internal_error ( + "attempted to mark unsupported type for constant deferral"); + + if (!deferred_cst_types) + deferred_cst_types + = hash_table<deferred_cst_type_hasher>::create_ggc (13); + + tree *slot = deferred_cst_types->find_slot (type, INSERT); + if (*slot == NULL_TREE) + *slot = type; +} + +bool +deferred_cst_type_p (tree type) +{ + type = TYPE_MAIN_VARIANT (type); + return (deferred_cst_types + && deferred_cst_types->find (type) != NULL); +} + +tree +deferred_cst_build_expr (tree expr) +{ + return build1_loc (EXPR_LOCATION (expr), DEFERRED_CST_EXPR, + TREE_TYPE (expr), expr); +} + +/* Create a unique STRING_CST to use as a metadata token. */ +static tree +make_token () +{ + char buf[64]; + + int len = snprintf (buf, sizeof (buf), + "__deferred_cst_token_" HOST_WIDE_INT_PRINT_UNSIGNED, + next_token++); + + gcc_assert (len > 0); + gcc_assert ((unsigned int) len < sizeof (buf)); + + /* Include the trailing NUL. */ + unsigned int string_len = len + 1; + + tree token = build_string (string_len, buf); + + TREE_TYPE (token) + = build_array_type_nelts (char_type_node, string_len); + + return token; +} + +/* Generate a new key token and store VALUE under that token in MAP. + If MAP was not yet allocated, allocate it. */ +static tree +register_ifn_entry (tree_cache_map **map, tree value) +{ + if (!map) + return NULL_TREE; + + tree token = make_token (); + + if (!*map) + *map = tree_cache_map::create_ggc (); + + bool existed = (*map)->put (token, value); + + /* Every token create above should be unique. */ + gcc_assert (!existed); + + return token; +} + +/* Look up the value associated with TOKEN in MAP. */ +static tree +lookup_ifn_entry (tree_cache_map **map, tree token) +{ + if (!token || !map || !*map) + return NULL_TREE; + + tree *slot = (*map)->get (token); + return slot ? *slot : NULL_TREE; +} + +/* Create a call to IFN_DEFERRED_CST_FIELD_OFFSET for the physical, + addressable FIELD whose byte offset is deferred. + + FIELD must not be a bit-field. Callers handling bit-fields must pass + DECL_BIT_FIELD_REPRESENTATIVE (field). + + Internally, these call hold the field declarations in a side-map + keyed by tokens used as call arguments. */ +tree +deferred_cst_call_ifn_field_offset (location_t loc, tree field) +{ + if (!field || TREE_CODE (field) != FIELD_DECL || DECL_BIT_FIELD (field)) + return error_mark_node; + + tree token = register_ifn_entry (&field_offset_decls, field); + return build_call_expr_internal_loc (loc, + IFN_DEFERRED_CST_FIELD_OFFSET, + sizetype, 1, token); +} + +tree +deferred_cst_ifn_field_offset_field (tree token) +{ + return lookup_ifn_entry (&field_offset_decls, token); +} + +/* Create a call to IFN_DEFERRED_CST_ENUM_VALUE for an enum value + declaration DECL. */ +tree +deferred_cst_call_ifn_enum_value (location_t loc, tree decl) +{ + if (!decl || TREE_CODE (decl) != CONST_DECL) + return error_mark_node; + + tree enum_type = TREE_TYPE (decl); + + if (!enum_type || TREE_CODE (enum_type) != ENUMERAL_TYPE) + return error_mark_node; + + tree init_type = TREE_TYPE (DECL_INITIAL (decl)); + + tree token = register_ifn_entry (&enum_value_decls, decl); + return build_call_expr_internal_loc (loc, + IFN_DEFERRED_CST_ENUM_VALUE, + init_type, 1, token); +} + +tree +deferred_cst_ifn_enum_value_decl (tree token) +{ + return lookup_ifn_entry (&enum_value_decls, token); +} + +static tree +find_deferred_cst_node (tree *tp, int *walk_subtrees, void *) +{ + tree node = *tp; + + if (!node) + return NULL_TREE; + + switch (TREE_CODE (node)) + { + case DEFERRED_CST_EXPR: + *walk_subtrees = 0; + return node; + + default: + break; + } + + /* Declarations and types are metadata here. Do not walk into their + contexts, types, or initializers. */ + if (DECL_P (node) || TYPE_P (node)) + *walk_subtrees = 0; + + return NULL_TREE; +} + +bool +deferred_cst_present_p (tree expr) +{ + if (!expr) + return false; + + tree root = expr; + + return walk_tree_without_duplicates ( + &root, + find_deferred_cst_node, + NULL) + != NULL_TREE; +} + +/* Walker to go through functions and initializers. ICE if + DEFERRED_CST_EXPR is encountered. */ +static tree +deferred_cst_barrier_walk (tree *tp, int *walk_subtrees, void *) +{ + 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) + internal_error ("unresolved deferred constant reached barrier"); + + return NULL_TREE; +} + +static void +deferred_cst_barrier_function (function *fn) +{ + basic_block bb; + + FOR_EACH_BB_FN (bb, fn) + { + for (gimple_stmt_iterator gsi = gsi_start_bb (bb); + !gsi_end_p (gsi); + gsi_next (&gsi)) + { + gimple *stmt = gsi_stmt (gsi); + + for (unsigned int i = 0; i < gimple_num_ops (stmt); ++i) + { + tree *operand = gimple_op_ptr (stmt, i); + + if (!operand || !*operand) + continue; + + walk_tree (operand, + deferred_cst_barrier_walk, + NULL, + NULL); + } + } + } +} + +static tree +deferred_cst_barrier_init (tree init) +{ + if (!init) + return init; + + walk_tree (&init, deferred_cst_barrier_walk, NULL, NULL); + return init; +} + +static void +deferred_cst_barrier_functions () +{ + cgraph_node *node; + + FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node) + { + function *fn = DECL_STRUCT_FUNCTION (node->decl); + gcc_assert (fn); + + push_cfun (fn); + deferred_cst_barrier_function (fn); + pop_cfun (); + } +} + +static void +deferred_cst_barrier_inits () +{ + varpool_node *vnode; + + FOR_EACH_VARIABLE (vnode) + { + tree decl = vnode->decl; + tree init = DECL_INITIAL (decl); + + if (!init || init == error_mark_node) + continue; + + tree clean_init = deferred_cst_barrier_init (init); + if (clean_init != init) + DECL_INITIAL (decl) = clean_init; + } +} + +namespace { + +const pass_data pass_data_deferred_cst_barrier = +{ + SIMPLE_IPA_PASS, + "deferred-cst-barrier", + OPTGROUP_NONE, + TV_NONE, + 0, 0, 0, 0, 0 +}; + +class pass_deferred_cst_barrier : public simple_ipa_opt_pass +{ +public: + pass_deferred_cst_barrier (gcc::context *ctxt) + : simple_ipa_opt_pass (pass_data_deferred_cst_barrier, ctxt) + {} + + unsigned int execute (function *) final override; +}; + +unsigned int +pass_deferred_cst_barrier::execute (function *) +{ + deferred_cst_barrier_functions (); + deferred_cst_barrier_inits (); + return 0; +} + +} // anonymous namespace + +simple_ipa_opt_pass * +make_pass_deferred_cst_barrier (gcc::context *ctxt) +{ + return new pass_deferred_cst_barrier (ctxt); +} + +#include "gt-deferred-cst.h" diff --git a/gcc/deferred-cst.h b/gcc/deferred-cst.h new file mode 100644 index 00000000000..85e65f6854f --- /dev/null +++ b/gcc/deferred-cst.h @@ -0,0 +1,54 @@ +/* Deferred constant expression support for GCC. + Copyright (C) 2026 Free Software Foundation, Inc. + +This file is part of GCC. + +GCC is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free +Software Foundation; either version 3, or (at your option) any later +version. + +GCC is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License +along with GCC; see the file COPYING3. If not see +<http://www.gnu.org/licenses/>. */ + +#ifndef GCC_DEFERRED_CST_H +#define GCC_DEFERRED_CST_H + +/* Mark a record or enum TYPE for constant deferral. */ +extern void deferred_cst_mark_type (tree type); + +/* Return true if TYPE is marked for constant deferral. */ +extern bool deferred_cst_type_p (tree type); + +/* Build a DEFERRED_CST_EXPR around EXPR. */ +extern tree deferred_cst_build_expr (tree expr); + +/* Return true if EXPR contains a DEFERRED_CST_EXPR. */ +extern bool deferred_cst_present_p (tree expr); + +/* Create a call to IFN_DEFERRED_CST_FIELD_OFFSET for the physical + FIELD whose byte offset is deferred. + + FIELD must not be a bit-field. Callers handling bit-fields must pass + DECL_BIT_FIELD_REPRESENTATIVE (field). */ +extern tree deferred_cst_call_ifn_field_offset (location_t loc, tree field); + +/* Get the FIELD_DECL associated with the argument TOKEN to a call of + IFN_DEFERRED_CST_FIELD_OFFSET. */ +extern tree deferred_cst_ifn_field_offset_field (tree token); + +/* Create a call to IFN_DEFERRED_CST_ENUM_VALUE for an enum value + declaration DECL. */ +extern tree deferred_cst_call_ifn_enum_value (location_t loc, tree decl); + +/* Get the CONST_DECL associated with the argument TOKEN to a call of + IFN_DEFERRED_CST_ENUM_VALUE. */ +extern tree deferred_cst_ifn_enum_value_decl (tree token); + +#endif diff --git a/gcc/gimple-expr.cc b/gcc/gimple-expr.cc index fcc31b99390..acb4b59e371 100644 --- a/gcc/gimple-expr.cc +++ b/gcc/gimple-expr.cc @@ -844,6 +844,11 @@ is_gimple_val (tree t) || TREE_CODE (t) == OMP_TARGET_DEVICE_MATCHES) return true; + /* Technically, deferred constant expressions act as min invariants, + but they do not survice to where that would be relevant. */ + if (TREE_CODE (t) == DEFERRED_CST_EXPR) + return true; + return (is_gimple_variable (t) || is_gimple_min_invariant (t)); } diff --git a/gcc/gimple.cc b/gcc/gimple.cc index 2295f353472..7f3c0734a23 100644 --- a/gcc/gimple.cc +++ b/gcc/gimple.cc @@ -2574,7 +2574,8 @@ get_gimple_rhs_num_ops (enum tree_code code) || (SYM) == WITH_SIZE_EXPR \ || (SYM) == SSA_NAME \ || (SYM) == OMP_NEXT_VARIANT \ - || (SYM) == OMP_TARGET_DEVICE_MATCHES) ? GIMPLE_SINGLE_RHS \ + || (SYM) == OMP_TARGET_DEVICE_MATCHES \ + || (SYM) == DEFERRED_CST_EXPR) ? GIMPLE_SINGLE_RHS \ : GIMPLE_INVALID_RHS), #define END_OF_BASE_TREE_CODES (unsigned char) GIMPLE_INVALID_RHS, diff --git a/gcc/gimplify.cc b/gcc/gimplify.cc index 94d71d71fc2..84820380ac5 100644 --- a/gcc/gimplify.cc +++ b/gcc/gimplify.cc @@ -20705,6 +20705,11 @@ gimplify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, ret = GS_ALL_DONE; break; + case DEFERRED_CST_EXPR: + /* DEFERRED_CST_EXPRs act as min invariants. */ + ret = GS_ALL_DONE; + break; + case CONST_DECL: /* If we require an lvalue, such as for ADDR_EXPR, retain the CONST_DECL node. Otherwise the decl is replaceable by its diff --git a/gcc/internal-fn.cc b/gcc/internal-fn.cc index 40fe58dc4f6..e04b95cbbb6 100644 --- a/gcc/internal-fn.cc +++ b/gcc/internal-fn.cc @@ -4322,6 +4322,24 @@ expand_reduc_sbool_optab_fn (internal_fn fn, gcall *stmt, direct_optab optab) assign_call_lhs (lhs, lhs_rtx, &ops[0]); } +/* IFN_DEFERRED_CST_FIELD_OFFSET should not survice GIMPLE. */ + +void +expand_DEFERRED_CST_FIELD_OFFSET (internal_fn, gcall *) +{ + internal_error ("%qs reached RTL expansion", + "IFN_DEFERRED_CST_FIELD_OFFSET"); +} + +/* IFN_DEFERRED_CST_ENUM_VALUE should not survive GIMPLE. */ + +void +expand_DEFERRED_CST_ENUM_VALUE (internal_fn, gcall *) +{ + internal_error ("%qs reached RTL expansion", + "IFN_DEFERRED_CST_ENUM_VALUE"); +} + /* Expanders for optabs that can use expand_direct_optab_fn. */ #define expand_unary_optab_fn(FN, STMT, OPTAB) \ diff --git a/gcc/internal-fn.def b/gcc/internal-fn.def index 7feb236d802..dfb7bd2e034 100644 --- a/gcc/internal-fn.def +++ b/gcc/internal-fn.def @@ -649,6 +649,12 @@ DEF_INTERNAL_FN (BITINTTOFLOAT, ECF_PURE | ECF_LEAF, ". R . ") DEF_INTERNAL_OPTAB_FN (BIT_ANDN, ECF_CONST, andn, binary) DEF_INTERNAL_OPTAB_FN (BIT_IORN, ECF_CONST, iorn, binary) +/* Deferred constant functions. */ +DEF_INTERNAL_FN (DEFERRED_CST_FIELD_OFFSET, ECF_CONST | ECF_LEAF | ECF_NOTHROW, + NULL) +DEF_INTERNAL_FN (DEFERRED_CST_ENUM_VALUE, ECF_CONST | ECF_LEAF | ECF_NOTHROW, + NULL) + #undef DEF_INTERNAL_WIDENING_OPTAB_FN #undef DEF_INTERNAL_SIGNED_COND_FN #undef DEF_INTERNAL_COND_FN diff --git a/gcc/passes.def b/gcc/passes.def index 9095c134f49..e981dbb412d 100644 --- a/gcc/passes.def +++ b/gcc/passes.def @@ -47,6 +47,7 @@ along with GCC; see the file COPYING3. If not see /* Interprocedural optimization passes. */ INSERT_PASSES_AFTER (all_small_ipa_passes) + NEXT_PASS (pass_deferred_cst_barrier); /* auto_profile_offline uses dwarf_name hook that only works before free_lang_data. */ NEXT_PASS (pass_ipa_auto_profile_offline); diff --git a/gcc/testsuite/gcc.dg/plugin/deferred_cst-test.c b/gcc/testsuite/gcc.dg/plugin/deferred_cst-test.c new file mode 100644 index 00000000000..fb73510881d --- /dev/null +++ b/gcc/testsuite/gcc.dg/plugin/deferred_cst-test.c @@ -0,0 +1,80 @@ +/* { dg-do compile } */ +/* { dg-options "-std=gnu11" } */ + +/* { dg-final { scan-file deferred-cst.out "\\\[var\\\] var_aggregate\\.nested\\.y -- \\(offsetof\\(struct S, c\\) \\+ \\(E::E_C \\* 4\\)\\)" } } */ +/* { dg-final { scan-file deferred-cst.out "\\\[var\\\] var_aggregate\\.x -- E::E_B" } } */ +/* { dg-final { scan-file deferred-cst.out "\\\[var\\\] var_enum -- E::E_B" } } */ +/* { dg-final { scan-file deferred-cst.out "\\\[var\\\] var_offset -- offsetof\\(struct S, b\\)" } } */ +/* { dg-final { scan-file deferred-cst.out "\\\[fun\\\] test_enum -- E::E_B" } } */ +/* { dg-final { scan-file deferred-cst.out "\\\[fun\\\] test_expression -- \\(offsetof\\(struct S, c\\) \\+ \\(E::E_C \\* 4\\)\\)" } } */ +/* { dg-final { scan-file deferred-cst.out "\\\[fun\\\] test_offset -- offsetof\\(struct S, b\\)" } } */ + +#include <stddef.h> + +#define __dc __attribute__((defer_constants)) + +struct S +{ + int a, b, c; +} __dc; + +enum E +{ + E_A = 1, + E_B = 1, + E_C = 2 +} __dc; + + +/* Basic field-offset preservation. */ + +size_t +test_offset (void) +{ + return offsetof (struct S, b); +} + + +/* Basic enumerator preservation. Use E_B so that its identity cannot be + reconstructed from its numeric value. */ + +int +test_enum (void) +{ + return E_B; +} + + +/* Propagation through a non-trivial constant expression, including both + kinds of deferred leaf. */ + +size_t +test_expression (void) +{ + return offsetof (struct S, c) + E_C * 4; +} + + +/* Deferred constants in scalar static initializers. */ + +static int var_enum = E_B; + +static size_t var_offset = offsetof (struct S, b); + + +/* Deferred constants recursively contained in an aggregate initializer. */ + +struct aggregate +{ + int x; + struct + { + size_t y; + } nested; +}; + +static struct aggregate var_aggregate = +{ + .x = E_B, + .nested.y = offsetof (struct S, c) + E_C * 4 +}; diff --git a/gcc/testsuite/gcc.dg/plugin/deferred_cst_plugin.cc b/gcc/testsuite/gcc.dg/plugin/deferred_cst_plugin.cc new file mode 100644 index 00000000000..575f59bd85b --- /dev/null +++ b/gcc/testsuite/gcc.dg/plugin/deferred_cst_plugin.cc @@ -0,0 +1,619 @@ +/* Test plugin for deferred constant expressions. + Copyright (C) 2026 Free Software Foundation, Inc. + +This file is part of GCC. + +GCC is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free +Software Foundation; either version 3, or (at your option) any later +version. + +GCC is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License +along with GCC; see the file COPYING3. If not see +<http://www.gnu.org/licenses/>. */ + +#include <gcc-plugin.h> +#include <plugin-version.h> +#include <tree.h> +#include <tree-pass.h> +#include <context.h> +#include <cgraph.h> +#include <gimple.h> +#include <gimple-iterator.h> +#include <function.h> +#include <internal-fn.h> +#include <print-tree.h> +#include <tree-pretty-print.h> +#include <diagnostic-core.h> +#include <deferred-cst.h> + +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <string> +#include <vector> + +int plugin_is_GPL_compatible; + +static const char *output_file = "deferred-cst.out"; + +enum class context_kind +{ + variable, + function +}; + +struct deferred_report +{ + context_kind kind; + std::string context; + std::string expression; +}; + +static std::vector<deferred_report> reports; + +static tree +check_defer_constants_attribute (tree *node, tree name, tree args, int flags, bool *no_add_attrs) +{ + if (!node || !*node) + return NULL_TREE; + + tree type = *node; + + switch (TREE_CODE (type)) + { + case RECORD_TYPE: + case ENUMERAL_TYPE: + deferred_cst_mark_type (type); + break; + default: + error ("%'defer_constants%' attribute on invalid type"); + *no_add_attrs = true; + } + + return NULL_TREE; +} + +static struct attribute_spec defer_constants_attribute = { + "defer_constants", 0, 0, false, false, false, false, + check_defer_constants_attribute, NULL +}; + +void +on_register_attributes (void *plugin_data, void *user_data) +{ + register_attribute (&defer_constants_attribute); +} + +/* Small stable printer for deferred constant expressions. + + The intentionally supported grammar is: + + EXPR := + LEAF + | (EXPR + EXPR) + | (EXPR - EXPR) + | (EXPR * EXPR) + + LEAF := + INTEGER + | offsetof(TYPE, FIELD) + | ENUM::VALUE + + Every non-leaf expression is parenthesized. */ + +/* Return a stable printable name for DECL. + + For tests we require declarations involved in deferred constants to have + names. */ +static const char * +decl_name (tree decl) +{ + gcc_assert (decl); + gcc_assert (DECL_P (decl)); + gcc_assert (DECL_NAME (decl)); + + return IDENTIFIER_POINTER (DECL_NAME (decl)); +} + +/* Append the name of a record/enum type. + + Prefer TYPE_NAME's declaration/name. Tests using this plugin should use + named types rather than anonymous types, since the textual format is + deliberately intended to be stable. */ +static void +append_type_name (std::string &out, tree type) +{ + gcc_assert (type); + + tree name = TYPE_NAME (type); + + if (name && TREE_CODE (name) == TYPE_DECL) + name = DECL_NAME (name); + + gcc_assert (name && TREE_CODE (name) == IDENTIFIER_NODE); + + out += IDENTIFIER_POINTER (name); +} + +/* Print an INTEGER_CST without relying on host integer width. */ +static void +append_integer_cst (std::string &out, tree t) +{ + gcc_assert (TREE_CODE (t) == INTEGER_CST); + + char *p = print_generic_expr_to_str (t); + + /* INTEGER_CSTs appearing in the test grammar should print as a simple + integer. */ + gcc_assert (p); + out += p; + free (p); +} + +/* Print a deferred field-offset IFN. */ +static void +append_field_offset (std::string &out, tree call) +{ + gcc_assert (TREE_CODE (call) == CALL_EXPR); + gcc_assert (CALL_EXPR_IFN (call) == IFN_DEFERRED_CST_FIELD_OFFSET); + gcc_assert (call_expr_nargs (call) == 1); + + tree token = CALL_EXPR_ARG (call, 0); + tree field = deferred_cst_ifn_field_offset_field (token); + + gcc_assert (field); + gcc_assert (TREE_CODE (field) == FIELD_DECL); + + tree record = DECL_CONTEXT (field); + + gcc_assert (record); + gcc_assert (TREE_CODE (record) == RECORD_TYPE); + + out += "offsetof(struct "; + + append_type_name (out, record); + out += ", "; + out += decl_name (field); + out += ")"; +} + +/* Print a deferred enum-value IFN. */ +static void +append_enum_value (std::string &out, tree call) +{ + gcc_assert (TREE_CODE (call) == CALL_EXPR); + gcc_assert (CALL_EXPR_IFN (call) == IFN_DEFERRED_CST_ENUM_VALUE); + gcc_assert (call_expr_nargs (call) == 1); + + tree token = CALL_EXPR_ARG (call, 0); + tree decl = deferred_cst_ifn_enum_value_decl (token); + + gcc_assert (decl); + gcc_assert (TREE_CODE (decl) == CONST_DECL); + + tree enum_type = TREE_TYPE (decl); + + gcc_assert (enum_type); + gcc_assert (TREE_CODE (enum_type) == ENUMERAL_TYPE); + + append_type_name (out, enum_type); + out += "::"; + out += decl_name (decl); +} + +/* Print one internal-function leaf. */ +static void +append_deferred_ifn (std::string &out, tree call) +{ + gcc_assert (TREE_CODE (call) == CALL_EXPR); + gcc_assert (CALL_EXPR_FN (call) == NULL_TREE); + + switch (CALL_EXPR_IFN (call)) + { + case IFN_DEFERRED_CST_FIELD_OFFSET: + append_field_offset (out, call); + return; + + case IFN_DEFERRED_CST_ENUM_VALUE: + append_enum_value (out, call); + return; + + default: + /* The test consumer intentionally understands only the deferred + constant IFNs. */ + gcc_unreachable (); + } +} + +/* Append EXPR in the stable test grammar. + + Nested DEFERRED_CST_EXPR wrappers are transparent. */ +static void +append_deferred_expr (std::string &out, tree expr) +{ + gcc_assert (expr); + + while (CONVERT_EXPR_P (expr)) + { + gcc_assert (TREE_OPERAND (expr, 0)); + expr = TREE_OPERAND (expr, 0); + } + + switch (TREE_CODE (expr)) + { + case DEFERRED_CST_EXPR: + append_deferred_expr (out, TREE_OPERAND (expr, 0)); + return; + + case INTEGER_CST: + append_integer_cst (out, expr); + return; + + case CALL_EXPR: + append_deferred_ifn (out, expr); + return; + + case PLUS_EXPR: + case MINUS_EXPR: + case MULT_EXPR: + { + const char *op; + + switch (TREE_CODE (expr)) + { + case PLUS_EXPR: + op = " + "; + break; + + case MINUS_EXPR: + op = " - "; + break; + + case MULT_EXPR: + op = " * "; + break; + + default: + gcc_unreachable (); + } + + out += "("; + append_deferred_expr (out, TREE_OPERAND (expr, 0)); + out += op; + append_deferred_expr (out, TREE_OPERAND (expr, 1)); + out += ")"; + return; + } + + default: + /* If the core starts propagating a new operation into deferred + constants, force the test consumer to be updated explicitly. */ + debug_tree (expr); + internal_error ("unsupported expression in deferred constant test " + "consumer"); + } +} + +/* Record one outermost DEFERRED_CST_EXPR. */ +static void +record_deferred_expr (context_kind kind, const std::string &context, tree expr) +{ + gcc_assert (TREE_CODE (expr) == DEFERRED_CST_EXPR); + + std::string text; + append_deferred_expr (text, expr); + + reports.push_back ({ kind, context, text }); +} + +static tree +function_tree_walker (tree *tp, int *walk_subtrees, void *data) +{ + tree t = *tp; + + if (!t) + return NULL_TREE; + + if (TREE_CODE (t) != DEFERRED_CST_EXPR) + return NULL_TREE; + + const char *fn_name = static_cast<const char *> (data); + + record_deferred_expr (context_kind::function, fn_name, t); + + *walk_subtrees = 0; + return NULL_TREE; +} + +static void +scan_function (cgraph_node *node) +{ + gcc_assert (node); + gcc_assert (node->decl); + + if (!node->has_gimple_body_p ()) + return; + + const char *name = decl_name (node->decl); + + push_cfun (DECL_STRUCT_FUNCTION (node->decl)); + + basic_block bb; + FOR_EACH_BB_FN (bb, cfun) + { + for (gimple_stmt_iterator gsi = gsi_start_bb (bb); + !gsi_end_p (gsi); + gsi_next (&gsi)) + { + gimple *stmt = gsi_stmt (gsi); + + for (unsigned i = 0; i < gimple_num_ops (stmt); ++i) + { + tree op = gimple_op (stmt, i); + + if (!op || !deferred_cst_present_p (op)) + continue; + + walk_tree (&op, function_tree_walker, + const_cast<char *> (name), NULL); + } + } + } + + pop_cfun (); +} + +/* Append ".field" or "[index]" for one CONSTRUCTOR element. + + FIELD_DECL indices give us struct/union paths. INTEGER_CST indices give + us array paths. */ +static std::string +constructor_element_context (const std::string &parent, tree index) +{ + std::string result = parent; + + if (!index) + return result; + + if (TREE_CODE (index) == FIELD_DECL) + { + result += "."; + result += decl_name (index); + return result; + } + + if (TREE_CODE (index) == INTEGER_CST) + { + result += "["; + append_integer_cst (result, index); + result += "]"; + return result; + } + + debug_tree (index); + internal_error ("unsupported constructor index in deferred constant " + "test consumer"); +} + +static void +scan_initializer (tree init, const std::string &context) +{ + if (!init) + return; + + if (TREE_CODE (init) == DEFERRED_CST_EXPR) + { + record_deferred_expr (context_kind::variable, context, init); + return; + } + + if (TREE_CODE (init) == CONSTRUCTOR) + { + unsigned HOST_WIDE_INT ix; + tree index; + tree value; + + FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), + ix, index, value) + { + std::string child + = constructor_element_context (context, index); + scan_initializer (value, child); + } + + return; + } + + /* A deferred expression can also be nested below some tree which is not + itself a CONSTRUCTOR. Walk that tree, retaining the same initializer + context. */ + if (deferred_cst_present_p (init)) + { + struct initializer_walk_data + { + const std::string *context; + } data = { &context }; + + auto walker = [] (tree *tp, int *walk_subtrees, void *opaque) -> tree + { + tree t = *tp; + + if (!t) + return NULL_TREE; + + if (TREE_CODE (t) != DEFERRED_CST_EXPR) + return NULL_TREE; + + initializer_walk_data *d + = static_cast<initializer_walk_data *> (opaque); + + record_deferred_expr (context_kind::variable, *d->context, t); + *walk_subtrees = 0; + return NULL_TREE; + }; + + walk_tree (&init, walker, &data, NULL); + } +} + +static void +scan_static_initializers () +{ + varpool_node *node; + + FOR_EACH_VARIABLE (node) + { + tree decl = node->decl; + + if (!decl) + continue; + + tree init = DECL_INITIAL (decl); + + if (!init || init == error_mark_node) + continue; + + /* Externals don't have a definition whose initializer belongs to this + compilation unit. */ + if (DECL_EXTERNAL (decl)) + continue; + + if (!deferred_cst_present_p (init)) + continue; + + scan_initializer (init, decl_name (decl)); + } +} + +static const char * +context_kind_name (context_kind kind) +{ + switch (kind) + { + case context_kind::function: + return "fun"; + + case context_kind::variable: + return "var"; + } + + gcc_unreachable (); +} + +static bool +report_less (const deferred_report &a, const deferred_report &b) +{ + if (a.kind != b.kind) + return a.kind < b.kind; + + if (a.context != b.context) + return a.context < b.context; + + return a.expression < b.expression; +} + +static void +emit_reports () +{ + /* Don't make tests depend on cgraph/varpool traversal order. */ + std::sort (reports.begin (), reports.end (), report_less); + + FILE *out = fopen (output_file, "w"); + if (!out) + fatal_error (UNKNOWN_LOCATION, + "cannot open %s", + output_file); + + for (const deferred_report &report : reports) + fprintf (out, "[%s] %s -- %s\n", + context_kind_name (report.kind), + report.context.c_str (), + report.expression.c_str ()); + + fclose (out); +} + +namespace { + +const pass_data pass_data_deferred_cst_test = +{ + SIMPLE_IPA_PASS, + "deferred-cst-test", + OPTGROUP_NONE, + TV_NONE, + 0, /* properties_required */ + 0, /* properties_provided */ + 0, /* properties_destroyed */ + 0, /* todo_flags_start */ + 0 /* todo_flags_finish */ +}; + +class pass_deferred_cst_test : public simple_ipa_opt_pass +{ +public: + pass_deferred_cst_test (gcc::context *ctxt) + : simple_ipa_opt_pass (pass_data_deferred_cst_test, ctxt) + {} + + unsigned int execute (function *) final override + { + reports.clear (); + + scan_static_initializers (); + + cgraph_node *node; + FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node) + scan_function (node); + + emit_reports (); + + fflush (stdout); + fflush (stderr); + + /* This plugin is a testsuite consumer of deferred constants. It + intentionally leaves the constants unresolved, so stop compilation + successfully after observing them rather than allowing them to escape + their supported lifetime. */ + exit (EXIT_SUCCESS); + + gcc_unreachable (); + } +}; + +} /* anonymous namespace */ + +int +plugin_init (struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) +{ + /* Don't allow output from earlier invocation to satisfy tests. */ + unlink (output_file); + + if (!plugin_default_version_check (version, &gcc_version)) + { + error ("incompatible GCC/plugin versions: plugin built for GCC %s, " + "loaded by GCC %s", + gcc_version.basever, version->basever); + return 1; + } + + register_callback (plugin_info->base_name, PLUGIN_ATTRIBUTES, + on_register_attributes, NULL); + + static struct register_pass_info pass_info; + pass_info.pass = new pass_deferred_cst_test (g); + pass_info.reference_pass_name = "deferred-cst-barrier"; + pass_info.ref_pass_instance_number = 1; + pass_info.pos_op = PASS_POS_INSERT_BEFORE; + + register_callback (plugin_info->base_name, + PLUGIN_PASS_MANAGER_SETUP, + NULL, &pass_info); + return 0; +} diff --git a/gcc/testsuite/gcc.dg/plugin/plugin.exp b/gcc/testsuite/gcc.dg/plugin/plugin.exp index deef8e8570c..660d1548730 100644 --- a/gcc/testsuite/gcc.dg/plugin/plugin.exp +++ b/gcc/testsuite/gcc.dg/plugin/plugin.exp @@ -201,6 +201,7 @@ set plugin_test_list [list \ cpython-plugin-test-PyList_New.c \ cpython-plugin-test-PyLong_FromLong.c } \ { progress_notifications_plugin.cc } \ + { deferred_cst_plugin.cc deferred_cst-test.c } \ ] foreach plugin_test $plugin_test_list { diff --git a/gcc/tree-pass.h b/gcc/tree-pass.h index a3b35e009e0..939e9a4aed9 100644 --- a/gcc/tree-pass.h +++ b/gcc/tree-pass.h @@ -512,6 +512,7 @@ extern gimple_opt_pass *make_pass_coroutine_early_expand_ifns (gcc::context *ctx extern gimple_opt_pass *make_pass_adjust_alignment (gcc::context *ctxt); /* IPA Passes */ +extern simple_ipa_opt_pass *make_pass_deferred_cst_barrier (gcc::context *ctxt); extern simple_ipa_opt_pass *make_pass_ipa_lower_emutls (gcc::context *ctxt); extern simple_ipa_opt_pass *make_pass_ipa_function_and_variable_visibility (gcc::context *ctxt); extern simple_ipa_opt_pass *make_pass_ipa_strub_mode (gcc::context *ctxt); diff --git a/gcc/tree-pretty-print.cc b/gcc/tree-pretty-print.cc index 9655870cfc8..5ccc5cd57e8 100644 --- a/gcc/tree-pretty-print.cc +++ b/gcc/tree-pretty-print.cc @@ -4452,6 +4452,13 @@ dump_generic_node (pretty_printer *pp, tree node, int spc, dump_flags_t flags, } break; + case DEFERRED_CST_EXPR: + pp_string (pp, "DEFERRED_CST_EXPR <"); + dump_generic_node (pp, TREE_OPERAND (node, 0), + spc, flags, false); + pp_character (pp, '>'); + break; + case OMP_TARGET_DEVICE_MATCHES: pp_string (pp, "OMP_TARGET_DEVICE_MATCHES <"); dump_generic_node (pp, OMP_TARGET_DEVICE_MATCHES_SELECTOR (node), spc, diff --git a/gcc/tree.def b/gcc/tree.def index c11ad1abf24..76108bf4c3d 100644 --- a/gcc/tree.def +++ b/gcc/tree.def @@ -1626,6 +1626,16 @@ DEFTREECODE (TARGET_OPTION_NODE, "target_option_node", tcc_exceptional, 0) Operand 2 is additional data. */ DEFTREECODE (ANNOTATE_EXPR, "annotate_expr", tcc_expression, 3) +/* DEFERRED_CST_EXPR. + Operand 0 is an expression with deferred const-ness. + Such expressions are not known constants during frontend execution + but may act like compile-time constants to some parts of code + generation. + For example, DEFERRED_CST_EXPRs may wrap offsetof-like expressions + or enum literals to prevent semantic meaning from being lost during + constant folding in language frontends. */ +DEFTREECODE (DEFERRED_CST_EXPR, "deferred_cst_expr", tcc_expression, 1) + /* Local variables: mode:c diff --git a/gcc/varasm.cc b/gcc/varasm.cc index 7ce5032a6cb..8ac38c9a270 100644 --- a/gcc/varasm.cc +++ b/gcc/varasm.cc @@ -62,6 +62,7 @@ along with GCC; see the file COPYING3. If not see #include "opts.h" #include "recog.h" #include "gimple-expr.h" +#include "deferred-cst.h" /* The (assembler) name of the first globally-visible object output. */ extern GTY(()) const char *first_global_object_name; @@ -5058,7 +5059,8 @@ initializer_constant_valid_p_1 (tree value, tree endtype, tree *cache) switch (TREE_CODE (value)) { case CONSTRUCTOR: - if (constructor_static_from_elts_p (value)) + if (constructor_static_from_elts_p (value) + || deferred_cst_present_p (value)) { unsigned HOST_WIDE_INT idx; tree elt; @@ -5107,6 +5109,7 @@ initializer_constant_valid_p_1 (tree value, tree endtype, tree *cache) case STRING_CST: case COMPLEX_CST: case RAW_DATA_CST: + case DEFERRED_CST_EXPR: return null_pointer_node; case ADDR_EXPR: -- 2.43.0
