]> git.ipfire.org Git - thirdparty/gcc.git/commit
c: Warn when returning nested functions that require a non-local context.
authorMartin Uecker <uecker@tugraz.at>
Mon, 28 Jul 2025 23:05:00 +0000 (01:05 +0200)
committerMartin Uecker <uecker@gcc.gnu.org>
Wed, 10 Sep 2025 13:48:24 +0000 (15:48 +0200)
commitafa74d37e8170d696f97424da7ab0f71883aac70
treee74a10556e42ffcd7139de5630982229987d76ba
parente18285867ec41f96078a02fd7049ca693bb15ecd
c: Warn when returning nested functions that require a non-local context.

This patch adds a mechanism to keep track whether nested functions require
non-local context because they reference a variable of an enclosing
scope.  This is used for extending the existing -Wreturn-address warning
to also warn for such nested functions.  Certain exceptions are implemented
for functions that do not requite a non-local context, because they reference
only static variables, named constants, non-local variables in unevaluated
sizeof, typeof or countof operators, or typedef.  The logic is based on the
existing infrastructure for determining use of undeclared static functions.
Finally, To make sure that no trampolines are generated even when not using
optimization, we mark the exempt functions with TREE_NO_TRAMPOLINE.

gcc/c/ChangeLog:
* c-tree.h: Add new macro C_DECL_NONLOCAL_CONTEXT and prototype
for mark_decl_used.
* c-typeck.cc (mark_decl_used): New function.
(function_to_pointer_conversion): Mark exempt functions.
(record_maybe_used_decl): Add `address' parameter.
(build_external_ref): Change to mark_decl_used.
(pop_maybe_used): Call mark_decl_used.
(c_mark_addressable): Ditto.
(c_finish_goto_label): Ditto.
(c_finish_return): Add warning.
* c-decl.cc (declspecs_add_type): Ditto.
(grokdeclarator): Don't set C_DECL_REGISTER on function
declarators.

gcc/testsuite/ChangeLog:
* gcc.dg/Wreturn-nested-1.c: New test.
* gcc.dg/Wreturn-nested-2.c: New test.
* gcc.dg/Wtrampolines-2.c: New test.
* gcc.dg/Wtrampolines-3.c: New test.
gcc/c/c-decl.cc
gcc/c/c-tree.h
gcc/c/c-typeck.cc
gcc/testsuite/gcc.dg/Wreturn-nested-1.c [new file with mode: 0644]
gcc/testsuite/gcc.dg/Wreturn-nested-2.c [new file with mode: 0644]
gcc/testsuite/gcc.dg/Wtrampolines-2.c [new file with mode: 0644]
gcc/testsuite/gcc.dg/Wtrampolines-3.c [new file with mode: 0644]