In the case the sprintf argument for %u and %d are unknown during
compilation time, emit functions utoa and itoa to the translation
unit in order to convert the number to string at execution time.
Only emit these functions if we can use COMDAT groups, weak symbols or
similar mechanisms to deduplicate them at link time (they may be emitted
for multiple TUs). This helps against code bloat.
Generating new tests and tweaking the existing ones was done by Claude.
gcc/ChangeLog:
* Makefile.in (GTFILES): Add gimple-ssa-sprintf.cc
* gimple-ssa-sprintf.cc: (build_itoa_utoa_fn): New.
(utoa_fn, itoa_fn): New GTY variables.
(gimple_fold_builtin_sprintf): Handle %d, %i and %u directives
whose argument is not an INTEGER_CSTby emitting calls to itoa or
utoa.
(build_conversion_fn_decl): New.
gcc/testsuite/ChangeLog:
* gcc.dg/tree-ssa/builtin-sprintf-30.c: Tweak comment.
* gcc.dg/tree-ssa/builtin-sprintf-32.c: Factor out non-const
integer testcases into the new files.
* gcc.dg/tree-ssa/builtin-sprintf-33.c: New test.
* gcc.dg/tree-ssa/builtin-sprintf-34.c: New test.
* gcc.dg/tree-ssa/builtin-sprintf-35.c: New test.
Signed-off-by: Filip Kastl <[email protected]>
Co-authored-by: Giuliano Belinassi <[email protected]>
Assisted-by: Claude Opus 5.5 <[email protected]>
---
gcc/Makefile.in | 1 +
gcc/gimple-ssa-sprintf.cc | 495 +++++++++++++++++-
.../gcc.dg/tree-ssa/builtin-sprintf-30.c | 4 +-
.../gcc.dg/tree-ssa/builtin-sprintf-32.c | 16 +-
.../gcc.dg/tree-ssa/builtin-sprintf-33.c | 253 +++++++++
.../gcc.dg/tree-ssa/builtin-sprintf-34.c | 5 +
.../gcc.dg/tree-ssa/builtin-sprintf-35.c | 97 ++++
7 files changed, 836 insertions(+), 35 deletions(-)
create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-33.c
create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-34.c
create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-35.c
diff --git a/gcc/Makefile.in b/gcc/Makefile.in
index 19e35f6149b..76aa22892d1 100644
--- a/gcc/Makefile.in
+++ b/gcc/Makefile.in
@@ -3190,6 +3190,7 @@ GTFILES = $(CPPLIB_H) $(srcdir)/input.h
$(srcdir)/coretypes.h \
$(srcdir)/ipa-strub.cc \
$(srcdir)/internal-fn.h \
$(srcdir)/calls.cc \
+ $(srcdir)/gimple-ssa-sprintf.cc \
$(srcdir)/analyzer/analyzer-language.cc \
@all_gtfiles@
diff --git a/gcc/gimple-ssa-sprintf.cc b/gcc/gimple-ssa-sprintf.cc
index f2975fbd8ae..3167ff64ce9 100644
--- a/gcc/gimple-ssa-sprintf.cc
+++ b/gcc/gimple-ssa-sprintf.cc
@@ -87,6 +87,11 @@ along with GCC; see the file COPYING3. If not see
#include "vr-values.h"
#include "tree-ssa-strlen.h"
#include "tree-dfa.h"
+#include "varasm.h"
+
+#include "cgraph.h"
+#include "cfghooks.h"
+#include "tree-into-ssa.h"
/* The likely worst case value of MB_LEN_MAX for the target, large enough
for UTF-8. Ideally, this would be obtained by a target hook if it were
@@ -107,6 +112,17 @@ namespace {
static int warn_level;
+/* Emit utoa and itoa functions that convert unsigned and signed integers to
+ string in runtime. */
+
+static tree build_itoa_utoa_fn (bool sign);
+
+/* Emitted utoa and itoa functions in the translation unit. Should survive
+ while the pass executes. */
+
+static GTY(()) tree utoa_fn;
+static GTY(()) tree itoa_fn;
+
/* The minimum, maximum, likely, and unlikely maximum number of bytes
of output either a formatting function or an individual directive
can result in. */
@@ -4551,34 +4567,105 @@ gimple_fold_builtin_sprintf (const call_info &info,
gimple_stmt_iterator *gsi)
if (dir.prec[1] >= 0)
return false;
- /* If the parameter to %d is not known in compile time, then do
- not optimize it. */
- if (TREE_CODE (dir.arg) != INTEGER_CST)
- return false;
-
tree dirtype = get_type_tree_for_integer (sign, dir);
if (dirtype == NULL_TREE)
return false;
- /* In case the value doesn't fit, give up. */
- if (!int_fits_type_p (dir.arg, dirtype))
- return false;
+ if (TREE_CODE (dir.arg) == INTEGER_CST)
+ {
+ /* The integer is known in compilation time. */
+
+ /* In case the value doesn't fit, give up. */
+ if (!int_fits_type_p (dir.arg, dirtype))
+ return false;
+
+ /* Build the string. */
+ tree str = build_string_from_int (10, dir.arg);
+ tree addr_str = build1 (ADDR_EXPR,
+ build_pointer_type (TREE_TYPE
(str)),
+ str);
+
+ /* Now TREE_STRING_LENGTH returns the SIZE of the string.
So
+ subtract one so we have its LENGTH. */
+ int str_len = TREE_STRING_LENGTH (str) - 1;
+
+ /* Emit the memcpy. */
+ len = build_int_cst (sizetype, str_len);
+ gimple *repl = gimple_build_call (fn_memcpy, 3, last_head,
+ addr_str, len);
+ gimple_seq_add_stmt_without_update (&stmts, repl);
+ }
+ else
+ {
+ /* The integer is not known in compilation time. Emit a
+ function itoa or utoa according to sign to build the
+ string in execution time. */
+
+ /* We only emit itoa and utoa for targets that support
+ mechanisms in the linker for merging duplicate
+ symbols. */
+ if (!supports_one_only ())
+ return false;
+
+ /* If it requires more precision than what we support, then
+ do not optimize. This happens for example in platforms
+ where longs are 32-bits and long longs are 64-bits, like
+ 32-bits x86 (which requires register concatenation for
+ 64-bits operations) or MS-Windows on x86_64. */
+ if (TYPE_PRECISION (dirtype)
+ > TYPE_PRECISION (long_integer_type_node))
+ return false;
+
+ tree fn, fn_arg_type;
+ if (sign)
+ {
+ /* %d case. Emit itoa. */
+ if (itoa_fn == NULL_TREE)
+ itoa_fn = build_itoa_utoa_fn (true);
+ fn = itoa_fn;
+ fn_arg_type = long_integer_type_node;
+ }
+ else
+ {
+ /* %u case. Emit utoa. */
+ if (utoa_fn == NULL_TREE)
+ utoa_fn = build_itoa_utoa_fn (false);
- /* Build the string. */
- tree str = build_string_from_int (10, dir.arg);
- tree addr_str = build1 (ADDR_EXPR,
- build_pointer_type (TREE_TYPE (str)),
- str);
+ fn = utoa_fn;
+ fn_arg_type = long_unsigned_type_node;
+ }
- /* Now TREE_STRING_LENGTH returns the SIZE of the string. So
- subtract one so we have its LENGTH. */
- size_t str_len = TREE_STRING_LENGTH (str) - 1;
+ /* Do casting to the argument to the directive first to
+ ensure truncation. For example, for %hhd directive
+ and an int is passed, we must cast it to char. */
+ tree arg;
+ if (useless_type_conversion_p (dirtype, TREE_TYPE
(dir.arg)))
+ arg = dir.arg;
+ else
+ {
+ arg = make_temp_ssa_name (dirtype, NULL, "");
+ gassign *conv = gimple_build_assign (arg, NOP_EXPR,
+ dir.arg);
+ gimple_seq_add_stmt_without_update (&stmts, conv);
+ }
- /* Emit the memcpy. */
- len = build_int_cst (sizetype, str_len);
- gimple *repl = gimple_build_call (fn_memcpy, 3, last_head,
- addr_str, len);
- gimple_seq_add_stmt_without_update (&stmts, repl);
+ /* Now cast it to whatever the parameter of utoa or itoa
+ expects. */
+ if (!useless_type_conversion_p (fn_arg_type, dirtype))
+ {
+ tree larg = make_temp_ssa_name (fn_arg_type, NULL, "");
+ gassign *conv = gimple_build_assign (larg, NOP_EXPR,
+ arg);
+ gimple_seq_add_stmt_without_update (&stmts, conv);
+ arg = larg;
+ }
+
+ /* Emit the call to itoa or utoa. */
+ len = make_temp_ssa_name (size_type_node, NULL, "");
+ gcall *repl = gimple_build_call (fn, 2, last_head, arg);
+ gimple_set_lhs (repl, len);
+ gimple_seq_add_stmt_without_update (&stmts, repl);
+ }
break;
}
@@ -4689,6 +4776,370 @@ get_user_idx_format (tree fndecl, unsigned *idx_args)
return tree_to_uhwi (fmtarg) - 1;
}
+/* Build the decl of a function NAME with signature
+ size_t NAME (char *str, VAL_TYPE val), as used by the integer to string
+ conversion functions below. */
+
+static tree
+build_conversion_fn_decl (const char *name, tree val_type)
+{
+ /* Build and setup the function decl. */
+ tree str_type = build_pointer_type (char_type_node);
+ tree fn_type = build_function_type_list (size_type_node, str_type,
+ val_type, NULL_TREE);
+ tree fn_decl = build_decl (UNKNOWN_LOCATION, FUNCTION_DECL,
+ clone_identifier (get_identifier (name),
+ "gcc_strlen"),
+ fn_type);
+
+ TREE_STATIC (fn_decl) = 1;
+ TREE_USED (fn_decl) = 1;
+ DECL_ARTIFICIAL (fn_decl) = 1;
+ DECL_IGNORED_P (fn_decl) = 1;
+ DECL_DECLARED_INLINE_P (fn_decl) = 1;
+
+ /* Every translation unit using the function emits its own copy. To avoid
+ code bloat, make sure all those copies get linked into a single
+ instance. */
+ gcc_checking_assert (supports_one_only ());
+ make_decl_one_only (fn_decl, DECL_ASSEMBLER_NAME (fn_decl));
+
+ DECL_VISIBILITY (fn_decl) = VISIBILITY_HIDDEN;
+ DECL_VISIBILITY_SPECIFIED (fn_decl) = 1;
+
+ /* Build parameter and result value decls and connect them to the function
+ decl tree. */
+ tree result_decl = build_decl (UNKNOWN_LOCATION, RESULT_DECL, NULL_TREE,
+ size_type_node);
+ DECL_ARTIFICIAL (result_decl) = 1;
+ DECL_IGNORED_P (result_decl) = 1;
+ DECL_CONTEXT (result_decl) = fn_decl;
+ DECL_RESULT (fn_decl) = result_decl;
+
+ tree str_param_decl = build_decl (UNKNOWN_LOCATION, PARM_DECL,
+ get_identifier ("str"), str_type);
+ DECL_ARTIFICIAL (str_param_decl) = 1;
+ DECL_NAMELESS (str_param_decl) = 1;
+ DECL_ARG_TYPE (str_param_decl) = str_type;
+ DECL_CONTEXT (str_param_decl) = fn_decl;
+ TREE_USED (str_param_decl) = 1;
+
+ tree val_param_decl = build_decl (UNKNOWN_LOCATION, PARM_DECL,
+ get_identifier ("val"), val_type);
+ DECL_ARTIFICIAL (val_param_decl) = 1;
+ DECL_NAMELESS (val_param_decl) = 1;
+ DECL_ARG_TYPE (val_param_decl) = val_type;
+ DECL_CONTEXT (val_param_decl) = fn_decl;
+ TREE_USED (val_param_decl) = 1;
+
+ DECL_CHAIN (str_param_decl) = val_param_decl;
+ DECL_ARGUMENTS (fn_decl) = str_param_decl;
+
+ return fn_decl;
+}
+
+/* Emit an 'itoa' (SIGN true) or 'utoa' (SIGN false) function for the
+ target.
+
+ Given an unsigned long number and a string buffer, the 'utoa' function
+ fills out the buffer with the decimal string representation of that number.
+ Analogously for 'itoa' and signed longs.
+
+ 'itoa' has an extra bb2-bb4 prologue that writes a sign and computes the
+ absolute value; bb5-bb8 are shared between both. */
+
+static tree
+build_itoa_utoa_fn (bool sign)
+{
+ tree val_type = sign ? long_integer_type_node : long_unsigned_type_node;
+ tree fn_decl = build_conversion_fn_decl (sign ? "itoa" : "utoa", val_type);
+ tree str_param_decl = DECL_ARGUMENTS (fn_decl);
+ tree str_type = TREE_TYPE (str_param_decl);
+ tree val_param_decl = DECL_CHAIN (str_param_decl);
+
+ profile_count cfg_count = profile_count::uninitialized ();
+
+ /* 'init_lowered_empty_function()' changes cfun and decl to the new function.
+ We cannot simply restore them by 'pop_cfun()', thus we save them
+ manually. */
+ struct function *saved_cfun = cfun;
+ tree saved_function_decl = current_function_decl;
+ basic_block bb = init_lowered_empty_function (fn_decl, true, cfg_count);
+
+ /* Build CFG. bb2-bb4 only exist for itoa (SIGN true):
+
+ bb1 (ENTRY) bb1 (ENTRY)
+ | |
+ | bb2
+ | t f
+ | | \
+ | bb3 |
+ | | /
+ | bb4
+ | /-\ | /-\
+ bb5 | bb5 |
+ f t | f t |
+ | \-/ | \-/
+ | |
+ bb6 bb6
+ | |
+ | /-\ | /-\
+ bb7 | bb7 |
+ f t | f t |
+ | \-/ | \-/
+ bb8 bb8
+ | |
+ bb9 (EXIT) bb9 (EXIT) */
+ basic_block bb2 = NULL, bb3 = NULL, bb4 = NULL, bb5;
+ if (sign)
+ {
+ bb2 = bb;
+ bb3 = split_block_after_labels (bb2)->dest;
+ bb4 = split_block_after_labels (bb3)->dest;
+ bb5 = split_block_after_labels (bb4)->dest;
+ }
+ else
+ bb5 = bb;
+ basic_block bb6 = split_block_after_labels (bb5)->dest;
+ basic_block bb7 = split_block_after_labels (bb6)->dest;
+ basic_block bb8 = split_block_after_labels (bb7)->dest;
+
+ edge e24 = NULL;
+ edge e45;
+ if (sign)
+ {
+ edge e23 = single_succ_edge (bb2);
+ e23->flags ^= EDGE_TRUE_VALUE | EDGE_FALLTHRU;
+ e24 = make_edge (bb2, bb4, EDGE_FALSE_VALUE);
+ e23->probability = profile_probability::unlikely ();
+ e24->probability = profile_probability::likely ();
+ e45 = single_succ_edge (bb4);
+ }
+ else
+ e45 = single_pred_edge (bb5);
+
+ edge e56 = single_succ_edge (bb5);
+ e56->flags ^= EDGE_FALSE_VALUE | EDGE_FALLTHRU;
+ edge e55 = make_edge (bb5, bb5, EDGE_TRUE_VALUE);
+
+ edge e78 = single_succ_edge (bb7);
+ e78->flags ^= EDGE_FALSE_VALUE | EDGE_FALLTHRU;
+ edge e77 = make_edge (bb7, bb7, EDGE_TRUE_VALUE);
+
+ /* Fill out profile information. */
+ e55->probability = profile_probability::likely ();
+ e56->probability = profile_probability::unlikely ();
+ e77->probability = profile_probability::likely ();
+ e78->probability = profile_probability::unlikely ();
+
+ /* Fill out dominator and loop info. */
+ calculate_dominance_info (CDI_DOMINATORS);
+ class loop *bb5_loop = alloc_loop ();
+ bb5_loop->header = bb5;
+ bb5_loop->latch = bb5;
+ add_loop (bb5_loop, bb5->loop_father);
+ class loop *bb7_loop = alloc_loop ();
+ bb7_loop->header = bb7;
+ bb7_loop->latch = bb7;
+ add_loop (bb7_loop, bb7->loop_father);
+
+ /* Insert GIMPLE statements. */
+ gimple_stmt_iterator gsi;
+ gimple_seq seq;
+ gphi *phi_val, *phi_str;
+
+ /* str_3_1 only exists for itoa. str_4/val_4 are set up differently by each
+ branch below, but once set, bb5/bb7/bb8 work with them the same way
+ regardless of SIGN. */
+ tree str_3_1 = NULL_TREE;
+ tree str_4, val_4;
+
+ if (sign)
+ {
+ /* bb2 (sign test):
+ if (val_2 < 0)
+ goto <bb 3>; [unlikely]
+ else
+ goto <bb 4>; [likely]
+ */
+ gsi = gsi_start_bb (bb2);
+ tree val_2 = get_or_create_ssa_default_def (cfun, val_param_decl);
+ gcond *bb2_cond
+ = gimple_build_cond (LT_EXPR, val_2,
+ build_zero_cst (long_integer_type_node), NULL,
+ NULL);
+ gsi_insert_after (&gsi, bb2_cond, GSI_NEW_STMT);
+
+ /* bb3 (write sign):
+ *str_3_1 = '-';
+ str_3_2 = str_3_1 + 1;
+ */
+ gsi = gsi_start_bb (bb3);
+ str_3_1 = get_or_create_ssa_default_def (cfun, str_param_decl);
+ tree str_3_1_deref = build_simple_mem_ref (str_3_1);
+ gassign *minus_write
+ = gimple_build_assign (str_3_1_deref,
+ build_int_cst (char_type_node,
+ lang_hooks.to_target_charset ('-')));
+ tree str_3_2
+ = gimple_build (&gsi, false, GSI_NEW_STMT, UNKNOWN_LOCATION,
+ POINTER_PLUS_EXPR, str_type, str_3_1,
+ build_one_cst (size_type_node));
+ gsi_insert_after (&gsi, minus_write, GSI_NEW_STMT);
+
+ /* bb4 (apply absolute value):
+ # str_4 = PHI <str_3_1(bb2), str_3_2(bb3)>
+ val_4 = ABSU_EXPR (val_2);
+ */
+ str_4 = make_ssa_name (str_param_decl);
+ phi_str = create_phi_node (str_4, bb4);
+ add_phi_arg (phi_str, str_3_1, e24, UNKNOWN_LOCATION);
+ add_phi_arg (phi_str, str_3_2, single_succ_edge (bb3), UNKNOWN_LOCATION);
+
+ gsi = gsi_start_bb (bb4);
+ val_4
+ = gimple_build (&gsi, false, GSI_NEW_STMT, UNKNOWN_LOCATION, ABSU_EXPR,
+ long_unsigned_type_node, val_2);
+ }
+ else
+ {
+ str_4 = get_or_create_ssa_default_def (cfun, str_param_decl);
+ val_4 = get_or_create_ssa_default_def (cfun, val_param_decl);
+ }
+
+ /* bb5 (count digits):
+ # str_5_1 = PHI <str_4(bb4), str_5_2(bb5)>
+ # val_5_1 = PHI <val_4(bb4), val_5_2(bb5)>
+ val_5_2 = val_5_1 / 10;
+ str_5_2 = str_5_1 + 1;
+ if (val_5_1 > 9)
+ goto <bb 5>; [likely]
+ else
+ goto <bb 6>; [unlikely]
+ */
+ tree str_5_1 = make_ssa_name (str_param_decl);
+ tree val_5_1 = make_ssa_name (long_unsigned_type_node);
+ phi_str = create_phi_node (str_5_1, bb5);
+ phi_val = create_phi_node (val_5_1, bb5);
+
+ /* We have to work on a gimple sequence ("freestanding" statements) instead
+ of directly on the basic block. Since the basic block forms a loop, we'll
+ be working with statements referencing SSA names that lack definitions or
+ referencing incomplete PHIs. Thus we want to limit the folding that the
+ 'gimple_build' API does. It shouldn't inspect these "invalid references".
+ We achieve this using gimple sequences.
+
+ FIXME According to the comment at 'gimple-fold.cc:gimple_build()', this
+ approach should work. However, I've seen this approach fail when I built
+ slightly different gimple statements. The gimple_build API can end up
+ calling 'tree_single_nonnegative_p()' which can end up inspecting an
+ incomplete PHI and segfaulting. I'm making this note here for two
+ reasons: 1. To warn people taking inspiration from this code. 2. To
+ document this bug in case it starts happening on this code -- which I
+ guess is possible if there are changes to the gimple folding
+ infrastructure. */
+ seq = NULL;
+ tree val_5_2
+ = gimple_build (&seq, TRUNC_DIV_EXPR, long_unsigned_type_node, val_5_1,
+ build_int_cst (long_unsigned_type_node, 10));
+ tree str_5_2
+ = gimple_build (&seq, POINTER_PLUS_EXPR, str_type, str_5_1,
+ build_one_cst (size_type_node));
+ gcond *bb5_cond
+ = gimple_build_cond (GT_EXPR, val_5_1,
+ build_int_cst (long_unsigned_type_node, 9), NULL,
+ NULL);
+ gimple_seq_add_stmt (&seq, bb5_cond);
+ gsi = gsi_start_bb (bb5);
+ gsi_insert_seq_after (&gsi, seq, GSI_LAST_NEW_STMT);
+
+ add_phi_arg (phi_str, str_4, e45, UNKNOWN_LOCATION);
+ add_phi_arg (phi_str, str_5_2, e55, UNKNOWN_LOCATION);
+ add_phi_arg (phi_val, val_4, e45, UNKNOWN_LOCATION);
+ add_phi_arg (phi_val, val_5_2, e55, UNKNOWN_LOCATION);
+
+ /* bb6 (compute length):
+ len_6_1 = str_5_2 - whatever is the most recent str;
+ len_6_2 = (size_t) len_6_1;
+ */
+ gsi = gsi_start_bb (bb6);
+ tree len_6_1
+ = gimple_build (&gsi, false, GSI_NEW_STMT, UNKNOWN_LOCATION,
+ POINTER_DIFF_EXPR, ptrdiff_type_node, str_5_2,
+ sign ? str_3_1 : str_4);
+ tree len_6_2
+ = gimple_convert (&gsi, false, GSI_NEW_STMT, UNKNOWN_LOCATION,
+ size_type_node, len_6_1);
+
+ /* bb7 (write digits):
+ # str_7_1 = PHI <str_5_2(bb6), str_7_2(bb7)>
+ # val_7_1 = PHI <val_4(bb6), val_7_2(bb7)>
+ val_7_2 = val_7_1 / 10;
+ val_7_3 = val_7_1 % 10;
+ val_7_4 = val_7_3 + '0';
+ val_7_5 = (char) val_7_4;
+ str_7_2 = str_7_1 - 1;
+ *str_7_2 = val_7_5;
+ if (val_7_1 > 9)
+ goto <bb 7>; [likely]
+ else
+ goto <bb 8>; [unlikely]
+ */
+ /* Just build PHIs. Add arguments after the gimple_build(...) API gives them
+ to us. */
+ tree str_7_1 = make_ssa_name (str_param_decl);
+ tree val_7_1 = make_ssa_name (long_unsigned_type_node);
+ phi_str = create_phi_node (str_7_1, bb7);
+ phi_val = create_phi_node (val_7_1, bb7);
+
+ seq = NULL;
+ tree val_7_2
+ = gimple_build (&seq, TRUNC_DIV_EXPR, long_unsigned_type_node, val_7_1,
+ build_int_cst (long_unsigned_type_node, 10));
+ tree val_7_3
+ = gimple_build (&seq, TRUNC_MOD_EXPR, long_unsigned_type_node, val_7_1,
+ build_int_cst (long_unsigned_type_node, 10));
+ tree val_7_4
+ = gimple_build (&seq, PLUS_EXPR, long_unsigned_type_node, val_7_3,
+ build_int_cst (long_unsigned_type_node,
+ lang_hooks.to_target_charset ('0')));
+ tree val_7_5 = gimple_convert (&seq, char_type_node, val_7_4);
+ tree str_7_2
+ = gimple_build (&seq, POINTER_PLUS_EXPR, str_type, str_7_1, size_int (-1));
+ tree str_7_2_deref = build_simple_mem_ref (str_7_2);
+ gassign *char_write = gimple_build_assign (str_7_2_deref, val_7_5);
+ gimple_seq_add_stmt (&seq, char_write);
+ gcond *bb7_cond
+ = gimple_build_cond (GT_EXPR, val_7_1,
+ build_int_cst (long_unsigned_type_node, 9), NULL,
+ NULL);
+ gimple_seq_add_stmt (&seq, bb7_cond);
+ gsi = gsi_start_bb (bb7);
+ gsi_insert_seq_after (&gsi, seq, GSI_LAST_NEW_STMT);
+
+ add_phi_arg (phi_str, str_5_2, single_succ_edge (bb6), UNKNOWN_LOCATION);
+ add_phi_arg (phi_str, str_7_2, e77, UNKNOWN_LOCATION);
+ add_phi_arg (phi_val, val_4, single_succ_edge (bb6), UNKNOWN_LOCATION);
+ add_phi_arg (phi_val, val_7_2, e77, UNKNOWN_LOCATION);
+
+ /* bb8:
+ return len_6_2;
+ */
+ gsi = gsi_start_bb (bb8);
+ greturn *return_stmt = gimple_build_return (len_6_2);
+ gsi_insert_after (&gsi, return_stmt, GSI_NEW_STMT);
+
+ /* Finish building the function body. */
+ update_ssa (TODO_update_ssa_only_virtuals);
+ set_cfun (saved_cfun);
+ current_function_decl = saved_function_decl;
+
+ /* Update call graph. */
+ cgraph_node::add_new_function (fn_decl, true);
+
+ return fn_decl;
+}
+
} /* Unnamed namespace. */
/* Determine if a GIMPLE call at *GSI is to one of the sprintf-like built-in
@@ -5107,3 +5558,5 @@ handle_printf_call (gimple_stmt_iterator *gsi,
pointer_query &ptr_qry)
return call_removed;
}
+
+#include "gt-gimple-ssa-sprintf.h"
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
index b35a6c0d951..ed0b2299465 100644
--- a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
@@ -1,8 +1,8 @@
/* Verify that sprintf calls broken into sequences of memcpy calls produce
the same output and the same return value as the library sprintf.
-fno-printf-return-value prevents the return value from being replaced
- by a constant computed by the sprintf pass so that the value computed
- by the folded sequence is the one being checked.
+ by a constant computed by the sprintf optimizations so that the value
+ computed by the folded sequence is the one being checked.
{ dg-do run }
{ dg-options "-O2 -Wno-format -Wno-format-zero-length
-fno-printf-return-value" } */
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
index 3a4dbf2a090..f9109155b0e 100644
--- a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
@@ -1,5 +1,7 @@
/* Verify which sprintf calls are folded into sequences of memcpy calls
- and which are left alone.
+ and which are left alone. Integer directives whose arguments are not
+ known at compile time are tested in builtin-sprintf-35.c and
+ builtin-sprintf-36.c.
{ dg-do compile }
{ dg-options "-O2 -Wno-format -fno-printf-return-value
-fdump-tree-optimized" } */
@@ -74,11 +76,6 @@ void f_mixed (char *d, const char *s)
/* Calls expected not to be folded because we don't support these formats so
far. */
-void g_d_var (char *d, int i)
-{
- sprintf (d, "%d", i);
-}
-
void g_width (char *d, const char *s)
{
sprintf (d, "%5s", s);
@@ -129,11 +126,6 @@ void g_percent (char *d)
sprintf (d, "100%%");
}
-void g_mixed_var (char *d, const char *s, int i)
-{
- sprintf (d, "%s%d", s, i);
-}
-
/* The length of S is unknown and so is the return value. */
int g_s_ret (char *d, const char *s)
@@ -141,4 +133,4 @@ int g_s_ret (char *d, const char *s)
return sprintf (d, "%s", s);
}
-/* { dg-final { scan-tree-dump-times "sprintf \\(" 13 "optimized" } } */
+/* { dg-final { scan-tree-dump-times "sprintf \\(" 11 "optimized" } } */
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-33.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-33.c
new file mode 100644
index 00000000000..e9c026acb64
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-33.c
@@ -0,0 +1,253 @@
+/* Verify that sprintf calls with integer directives whose arguments are not
+ known at compile time, which are folded into calls to the itoa and utoa
+ functions emitted by the sprintf optimizations, produce the same output and
+ the same return value as the library sprintf. -fno-printf-return-value
+ prevents the return value from being replaced by a constant computed by the
+ sprintf optimizations so that the value computed by the folded sequence is
+ the one being checked.
+ { dg-do run }
+ { dg-options "-O2 -Wno-format -fno-printf-return-value" } */
+
+typedef __SIZE_TYPE__ size_t;
+
+#define sprintf(...) __builtin_sprintf (__VA_ARGS__)
+#define putchar(...) __builtin_putchar (__VA_ARGS__)
+#define puts(...) __builtin_puts (__VA_ARGS__)
+
+/* Larger than any output below. */
+#define BUFSIZE 80
+
+const char *volatile vhello = "hello";
+
+unsigned nfails;
+
+/* Return the argument in a way the compiler cannot see through, so that the
+ sprintf calls below are not folded as if it were a constant. */
+#define IDENT(name, type) \
+ static type __attribute__ ((noipa)) \
+ name (type x) \
+ { \
+ return x; \
+ }
+
+IDENT (vi, int)
+IDENT (vu, unsigned)
+IDENT (vl, long)
+IDENT (vul, unsigned long)
+IDENT (vll, long long)
+IDENT (vull, unsigned long long)
+IDENT (vz, size_t)
+IDENT (vt, __PTRDIFF_TYPE__)
+IDENT (vj, __INTMAX_TYPE__)
+IDENT (vuj, __UINTMAX_TYPE__)
+
+static void __attribute__ ((noipa))
+print_buffer (int n, const char *buf)
+{
+ for (int i = 0; i < n; ++i)
+ if (buf[i] == '\0')
+ putchar('$');
+ else
+ putchar(buf[i]);
+ putchar('\n');
+}
+
+/* Check that BUF contains the string EXPECT and that the byte past its
+ terminating nul has not been clobbered. Unless N is negative, also
+ check that N, the value returned by sprintf, equals the length of
+ EXPECT. */
+
+static void __attribute__ ((noipa))
+check (int line, const char *buf, int n, const char *expect)
+{
+ size_t len = __builtin_strlen (expect);
+
+ if ((n >= 0 && (size_t) n != len)
+ || __builtin_memcmp (buf, expect, len + 1) != 0
+ || buf[len + 1] != 'X')
+ {
+ __builtin_printf ("line %i: sprintf returned %i, wrote \"%s\"; "
+ "expected %i, \"%s\"\n",
+ line, n, buf, (int) len, expect);
+ puts("Written buffer: ");
+ print_buffer(BUFSIZE, buf);
+ ++nfails;
+ }
+}
+
+/* Call sprintf and check both its output and its return value. */
+#define T(expect, ...) \
+ do { \
+ char buf[BUFSIZE]; \
+ __builtin_memset (buf, 'X', sizeof buf); \
+ buf[sizeof buf - 1] = '\0'; \
+ int n = sprintf (buf, __VA_ARGS__); \
+ check (__LINE__, buf, n, expect); \
+ } while (0)
+
+/* Call sprintf ignoring its return value and check its output. */
+#define V(expect, ...) \
+ do { \
+ char buf[BUFSIZE]; \
+ __builtin_memset (buf, 'X', sizeof buf); \
+ buf[sizeof buf - 1] = '\0'; \
+ sprintf (buf, __VA_ARGS__); \
+ check (__LINE__, buf, -1, expect); \
+ } while (0)
+
+/* Do both of the above. */
+#define TV(expect, ...) \
+ do { \
+ T (expect, __VA_ARGS__); \
+ V (expect, __VA_ARGS__); \
+ } while (0)
+
+/* Signed directives, handled by itoa. */
+
+static void __attribute__ ((noipa))
+test_itoa (void)
+{
+ TV ("0", "%d", vi (0));
+ TV ("1", "%d", vi (1));
+ TV ("-1", "%d", vi (-1));
+ TV ("9", "%d", vi (9));
+ TV ("10", "%d", vi (10));
+ TV ("-9", "%d", vi (-9));
+ TV ("-10", "%d", vi (-10));
+ TV ("99", "%i", vi (99));
+ TV ("100", "%i", vi (100));
+ TV ("-123456", "%i", vi (-123456));
+
+ /* The argument is converted to the type of the directive. */
+ TV ("-128", "%hhd", vi (-128));
+ TV ("127", "%hhd", vi (127));
+ TV ("-56", "%hhd", vi (200));
+ TV ("-32768", "%hd", vi (-32768));
+ TV ("-25536", "%hd", vi (40000));
+
+ TV ("-123", "%ld", vl (-123));
+ TV ("-123", "%td", vt (-123));
+ TV ("-123", "%jd", vj (-123));
+ TV ("-123", "%lld", vll (-123));
+
+#if __INT_MAX__ == 2147483647
+ TV ("2147483647", "%d", vi (__INT_MAX__));
+ TV ("-2147483648", "%d", vi (-__INT_MAX__ - 1));
+#endif
+
+#if __LONG_MAX__ == 9223372036854775807L
+ TV ("9223372036854775807", "%ld", vl (__LONG_MAX__));
+ TV ("-9223372036854775808", "%ld", vl (-__LONG_MAX__ - 1));
+#elif __LONG_MAX__ == 2147483647L
+ TV ("2147483647", "%ld", vl (__LONG_MAX__));
+ TV ("-2147483648", "%ld", vl (-__LONG_MAX__ - 1));
+#endif
+
+#if __LONG_LONG_MAX__ == 9223372036854775807LL
+ TV ("9223372036854775807", "%lld", vll (__LONG_LONG_MAX__));
+ TV ("-9223372036854775808", "%lld", vll (-__LONG_LONG_MAX__ - 1));
+#endif
+}
+
+/* Unsigned directives, handled by utoa. */
+
+static void __attribute__ ((noipa))
+test_utoa (void)
+{
+ TV ("0", "%u", vu (0));
+ TV ("1", "%u", vu (1));
+ TV ("9", "%u", vu (9));
+ TV ("10", "%u", vu (10));
+ TV ("123456", "%u", vu (123456));
+
+ /* The argument is converted to the type of the directive. */
+ TV ("255", "%hhu", vi (255));
+ TV ("5", "%hhu", vi (261));
+ TV ("255", "%hhu", vi (-1));
+ TV ("65535", "%hu", vi (65535));
+ TV ("4464", "%hu", vi (70000));
+
+ TV ("123", "%lu", vul (123));
+ TV ("123", "%zu", vz (123));
+ TV ("123", "%ju", vuj (123));
+ TV ("123", "%llu", vull (123));
+
+#if __INT_MAX__ == 2147483647
+ TV ("2147483647", "%u", vu (__INT_MAX__));
+ TV ("2147483648", "%u", vu (__INT_MAX__ + 1U));
+ TV ("3000000000", "%u", vu (3000000000U));
+ TV ("4294967295", "%u", vu (-1U));
+#endif
+
+#if __LONG_MAX__ == 9223372036854775807L
+ TV ("9223372036854775808", "%lu", vul (__LONG_MAX__ + 1LU));
+ TV ("18446744073709551615", "%lu", vul (-1LU));
+#elif __LONG_MAX__ == 2147483647L
+ TV ("2147483648", "%lu", vul (__LONG_MAX__ + 1LU));
+ TV ("4294967295", "%lu", vul (-1LU));
+#endif
+
+#if __LONG_LONG_MAX__ == 9223372036854775807LL
+ TV ("18446744073709551615", "%llu", vull (-1LLU));
+#endif
+}
+
+/* Unknown integers mixed with other directives, so that itoa and utoa
+ write at an offset into the buffer and their result is used to compute
+ where the next directive starts. */
+
+static void __attribute__ ((noipa))
+test_mixed (void)
+{
+ TV ("x=-7, s=abc, u=7.", "x=%d, s=%s, u=%u.", vi (-7), "abc", vu (7));
+ TV ("-7abc", "%d%s", vi (-7), "abc");
+ TV ("abc-7", "%s%d", "abc", vi (-7));
+ TV ("1 2 3", "%d %i %u", vi (1), vi (2), vu (3));
+ TV ("123", "%d%d%d", vi (1), vi (2), vi (3));
+ TV ("-1-2-3", "%d%d%d", vi (-1), vi (-2), vi (-3));
+ TV ("10-100", "%u%d", vu (10), vi (-100));
+ TV ("he42", "%.2s%d", "hello", vi (42));
+ TV ("42he", "%d%.2s", vi (42), "hello");
+ TV ("[42:-42]", "[%d:%d]", 42, vi (-42));
+ TV ("[-42:42]", "[%d:%u]", vi (-42), 42U);
+
+ V ("hello-42", "%s%d", vhello, vi (-42));
+ V ("-42hello", "%d%s", vi (-42), vhello);
+ V ("-42hel", "%d%.3s", vi (-42), vhello);
+ V ("hel42", "%.3s%u", vhello, vu (42));
+}
+
+/* Directives the folding does not handle for unknown integers must still
+ work. */
+
+static void __attribute__ ((noipa))
+test_unhandled (void)
+{
+ TV ("ff", "%x", vi (255));
+ TV ("17", "%o", vi (15));
+ TV ("+5", "%+d", vi (5));
+ TV (" 5", "% d", vi (5));
+ TV ("00042", "%05d", vi (42));
+ TV (" 42", "%5d", vi (42));
+ TV ("007", "%.3d", vi (7));
+ TV ("007", "%.3u", vu (7));
+}
+
+int
+main (void)
+{
+ test_itoa ();
+ test_utoa ();
+ test_mixed ();
+ test_unhandled ();
+
+ /* Return failure rather than calling abort so that the output
+ describing the failures is flushed. */
+ if (nfails)
+ {
+ __builtin_printf ("%u failures\n", nfails);
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-34.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-34.c
new file mode 100644
index 00000000000..77ae619a2fd
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-34.c
@@ -0,0 +1,5 @@
+/* Same as builtin-sprintf-33.c but with -fprintf-return-value enabled.
+ { dg-do run }
+ { dg-options "-O2 -Wno-format -fprintf-return-value" } */
+
+#include "builtin-sprintf-33.c"
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-35.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-35.c
new file mode 100644
index 00000000000..1cf35a3fc23
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-35.c
@@ -0,0 +1,97 @@
+/* Verify that sprintf calls with integer directives whose arguments are
+ not known at compile time are folded into calls to the itoa and utoa
+ functions emitted by the sprintf optimizations. Every translation unit
+ emits its own copy of these functions, so they are only emitted on targets
+ that can merge the copies at link time using weak symbols (such targets also
+ often support COMDAT which the sprintf optimizations also can take advantage
+ of). Calls left alone on all targets are in builtin-sprintf-36.c.
+ { dg-do compile }
+ { dg-require-weak "" }
+ { dg-options "-O2 -Wno-format -fno-printf-return-value
-fdump-tree-optimized" } */
+
+#define sprintf(...) __builtin_sprintf (__VA_ARGS__)
+
+/* Calls expected to be folded. Signed directives use itoa and unsigned
+ ones utoa. */
+
+void f_d (char *d, int i)
+{
+ sprintf (d, "%d", i);
+}
+
+int f_d_ret (char *d, int i)
+{
+ return sprintf (d, "%d", i);
+}
+
+void f_i (char *d, int i)
+{
+ sprintf (d, "%i", i);
+}
+
+void f_hhd (char *d, int i)
+{
+ sprintf (d, "%hhd", i);
+}
+
+void f_hd (char *d, int i)
+{
+ sprintf (d, "%hd", i);
+}
+
+void f_ld (char *d, long i)
+{
+ sprintf (d, "%ld", i);
+}
+
+void f_u (char *d, unsigned u)
+{
+ sprintf (d, "%u", u);
+}
+
+int f_u_ret (char *d, unsigned u)
+{
+ return sprintf (d, "%u", u);
+}
+
+void f_hhu (char *d, int u)
+{
+ sprintf (d, "%hhu", u);
+}
+
+void f_hu (char *d, int u)
+{
+ sprintf (d, "%hu", u);
+}
+
+void f_lu (char *d, unsigned long u)
+{
+ sprintf (d, "%lu", u);
+}
+
+void f_zu (char *d, __SIZE_TYPE__ u)
+{
+ sprintf (d, "%zu", u);
+}
+
+void f_mixed (char *d, const char *s, int i, unsigned u)
+{
+ sprintf (d, "%d:%s:%u", i, s, u);
+}
+
+int f_mixed_ret (char *d, int i, unsigned u)
+{
+ return sprintf (d, "<%d|%u>", i, u);
+}
+
+void f_s_d (char *d, const char *s, int i)
+{
+ sprintf (d, "%s%d", s, i);
+}
+
+void f_d_d (char *d, int i, int j)
+{
+ sprintf (d, "%d%d", i, j);
+}
+
+/* { dg-final { scan-tree-dump-not "sprintf \\(" "optimized" } } */
--
2.55.0