]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
c++: NRV and goto [PR92407]
authorJason Merrill <jason@redhat.com>
Sun, 4 Jun 2023 16:00:55 +0000 (12:00 -0400)
committerJason Merrill <jason@redhat.com>
Wed, 24 Jan 2024 10:18:29 +0000 (05:18 -0500)
Here our named return value optimization was breaking the required
destructor when the goto takes 'a' out of scope.  A simple fix for the
release branches is to disable the optimization in the presence of backward
goto.

We could do better by disabling the optimization only if there is a backward
goto across the variable declaration, but we don't track that, and in GCC 14
we instead make the goto work with NRV.

PR c++/92407

gcc/cp/ChangeLog:

* cp-tree.h (struct language_function): Add backward_goto.
* decl.cc (check_goto): Set it.
* typeck.cc (check_return_expr): Prevent NRV if set.

gcc/testsuite/ChangeLog:

* g++.dg/opt/nrv22.C: New test.

(cherry picked from commit a645347c19b07cc7abd7bf276c6769fc41afc932)

gcc/cp/cp-tree.h
gcc/cp/decl.cc
gcc/cp/typeck.cc
gcc/testsuite/g++.dg/opt/nrv22.C [new file with mode: 0644]

index 5b3836422d6ed19a26defab61f257b32a5013a2c..132929375ea0deb3eedaf5308a19feb199bdca62 100644 (file)
@@ -2077,6 +2077,7 @@ struct GTY(()) language_function {
 
   BOOL_BITFIELD invalid_constexpr : 1;
   BOOL_BITFIELD throwing_cleanup : 1;
+  BOOL_BITFIELD backward_goto : 1;
 
   hash_table<named_label_hash> *x_named_labels;
 
index 22060b11176a5c395e01c1b7934f3495938de11b..878b14fe771d01b538fb21d964385947f2e9af32 100644 (file)
@@ -3650,6 +3650,8 @@ check_goto (tree decl)
       return;
     }
 
+  cp_function_chain->backward_goto = true;
+
   bool saw_catch = false, complained = false;
   int identified = 0;
   tree bad;
index 3be59f471791f2868d3f03566a3b1f4d51bec6b0..6ca240fe40a7d5c54c3b30109f35b67e10609f19 100644 (file)
@@ -10678,6 +10678,9 @@ check_return_expr (tree retval, bool *no_warning)
   if (fn_returns_value_p && flag_elide_constructors)
     {
       if (named_return_value_okay_p
+         /* The current NRV implementation breaks if a backward goto needs to
+            destroy the object (PR92407).  */
+         && !cp_function_chain->backward_goto
           && (current_function_return_value == NULL_TREE
              || current_function_return_value == bare_retval))
        current_function_return_value = bare_retval;
diff --git a/gcc/testsuite/g++.dg/opt/nrv22.C b/gcc/testsuite/g++.dg/opt/nrv22.C
new file mode 100644 (file)
index 0000000..eb889fa
--- /dev/null
@@ -0,0 +1,30 @@
+// PR c++/92407
+// { dg-do run }
+
+struct A
+{
+  A () { a++; }
+  A (const A &) { a++; }
+  ~A () { a--; }
+  static int a;
+};
+int A::a = 0;
+
+A
+foo ()
+{
+  int cnt = 10;
+lab:
+  A a;
+  if (cnt--)
+    goto lab;
+  return a;
+}
+
+int
+main ()
+{
+  foo ();
+  if (A::a)
+    __builtin_abort ();
+}