Hi!

We emit a bogus warning on the following testcase, suggesting that the
operator should return *this even when it does that already.
The problem is that normally cp_build_indirect_ref_1 ensures that *this
is folded as current_class_ref, but in templates (if return type is
non-dependent, otherwise check_return_expr doesn't check it) it didn't
go through cp_build_indirect_ref_1, but just built another INDIRECT_REF.
Which means it then doesn't compare pointer-equal to current_class_ref.

The following patch just checks if it is the same thing like
cp_build_indirect_ref_1 would check if it would be called.

Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?

2021-01-27  Jakub Jelinek  <ja...@redhat.com>

        PR c++/98841
        * typeck.c (check_return_expr): If processing_template_decl, don't
        rely on *this expression being always pointer-equal to
        current_class_ref.

        * g++.dg/warn/effc5.C: New test.

--- gcc/cp/typeck.c.jj  2021-01-25 10:02:28.380126847 +0100
+++ gcc/cp/typeck.c     2021-01-27 11:21:13.117875551 +0100
@@ -10188,6 +10188,19 @@ check_return_expr (tree retval, bool *no
          /* Returning '*this' is obviously OK.  */
          if (retval == current_class_ref)
            warn = false;
+         /* In templates, '*this' might not compare pointer equal to
+            current_class_ref.  */
+         else if (processing_template_decl
+                  && retval
+                  && TREE_CODE (retval) == INDIRECT_REF
+                  && (TREE_OPERAND (retval, 0) == current_class_ptr
+                      || (TREE_CODE (TREE_OPERAND (retval, 0)) == NOP_EXPR
+                          && (TREE_OPERAND (TREE_OPERAND (retval, 0), 0)
+                              == current_class_ptr)
+                          && (same_type_ignoring_top_level_qualifiers_p
+                                (TREE_TYPE (TREE_OPERAND (retval, 0)),
+                                 TREE_TYPE (current_class_ptr))))))
+           warn = false;
          /* If we are calling a function whose return type is the same of
             the current class reference, it is ok.  */
          else if (INDIRECT_REF_P (retval)
--- gcc/testsuite/g++.dg/warn/effc5.C.jj        2021-01-27 11:24:34.451565246 
+0100
+++ gcc/testsuite/g++.dg/warn/effc5.C   2021-01-27 11:23:23.836375556 +0100
@@ -0,0 +1,17 @@
+// PR c++/98841
+// { dg-do compile }
+// { dg-options "-Weffc++" }
+
+struct S {
+  template <typename T>
+  S& operator=(const T&) { return *this; }     // { dg-bogus "should return a 
reference to" }
+  S& operator=(const S&) { return *this; }
+};
+
+void
+foo ()
+{
+  S s, t;
+  s = 1;
+  s = t;
+}

        Jakub

Reply via email to