public inbox for gcc-patches@gcc.gnu.org
 help / color / mirror / Atom feed
* [PATCH] c++: -Wdangling-reference with reference wrapper [PR107532]
@ 2023-01-18 17:52 Marek Polacek
  2023-01-18 21:07 ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-01-18 17:52 UTC (permalink / raw)
  To: Jason Merrill, GCC Patches

Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

So I figured that perhaps we want to look at the object we're invoking
the member function(s) on and see if that is a temporary, as in, don't
warn about

  const Plane & meta = fm.planes().inner();

but do warn about

  const Plane & meta = FrameMetadata().planes().inner();

It's ugly, but better than asking users to add #pragmas into their code.

Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (do_warn_dangling_reference): Don't warn when the
	object member functions are invoked on is not a temporary.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
---
 gcc/cp/call.cc                                | 33 +++++++-
 .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
 2 files changed, 109 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index 0780b5840a3..43e65c3dffb 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13850,7 +13850,38 @@ do_warn_dangling_reference (tree expr)
 	    if (TREE_CODE (arg) == ADDR_EXPR)
 	      arg = TREE_OPERAND (arg, 0);
 	    if (expr_represents_temporary_p (arg))
-	      return expr;
+	      {
+		/* An ugly attempt to reduce the number of -Wdangling-reference
+		   false positives concerning reference wrappers (c++/107532).
+		   Don't warn about s.a().b() but do warn about S().a().b(),
+		   supposing that the member function is returning a reference
+		   to a subobject of the (non-temporary) object.  */
+		if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
+		    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
+		    && i == 0)
+		  {
+		    tree t = arg;
+		    while (handled_component_p (t))
+		      t = TREE_OPERAND (t, 0);
+		    t = TARGET_EXPR_INITIAL (arg);
+		    /* Quite likely we don't have a chain of member functions
+		       (like a().b().c()).  */
+		    if (TREE_CODE (t) != CALL_EXPR)
+		      return expr;
+		    /* Walk the call chain to the original object and see if
+		       it was a temporary.  */
+		    do
+		      t = tree_strip_nop_conversions (CALL_EXPR_ARG (t, 0));
+		    while (TREE_CODE (t) == CALL_EXPR);
+		    /* If the object argument is &TARGET_EXPR<>, we've started
+		       off the chain with a temporary and we want to warn.  */
+		    if (TREE_CODE (t) == ADDR_EXPR)
+		      t = TREE_OPERAND (t, 0);
+		    if (!expr_represents_temporary_p (t))
+		      break;
+		  }
+		return expr;
+	      }
 	  /* Don't warn about member function like:
 	      std::any a(...);
 	      S& s = a.emplace<S>({0}, 0);
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..32280f3e282
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner(); // { dg-warning "dangling reference" }
+  (void) d8;
+}

base-commit: c6a011119bfa038ccbfc9f123ede14a3d6237fab
-- 
2.39.0


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-18 17:52 [PATCH] c++: -Wdangling-reference with reference wrapper [PR107532] Marek Polacek
@ 2023-01-18 21:07 ` Jason Merrill
  2023-01-19  1:13   ` [PATCH v2] " Marek Polacek
  0 siblings, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-01-18 21:07 UTC (permalink / raw)
  To: Marek Polacek, GCC Patches

On 1/18/23 12:52, Marek Polacek wrote:
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> So I figured that perhaps we want to look at the object we're invoking
> the member function(s) on and see if that is a temporary, as in, don't
> warn about
> 
>    const Plane & meta = fm.planes().inner();
> 
> but do warn about
> 
>    const Plane & meta = FrameMetadata().planes().inner();
> 
> It's ugly, but better than asking users to add #pragmas into their code.

Hmm, that doesn't seem right; the former is only OK because Ref is in 
fact a reference-like type.  If planes() returned a class that held 
data, we would want to warn.

In this case, we might recognize the reference-like class because it has 
a reference member and a constructor taking the same reference type.

That wouldn't help with std::reference_wrapper or std::ref_view because 
they have pointer members instead of references, but perhaps loosening 
the check to include that case would make sense?

Jason

> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (do_warn_dangling_reference): Don't warn when the
> 	object member functions are invoked on is not a temporary.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> ---
>   gcc/cp/call.cc                                | 33 +++++++-
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
>   2 files changed, 109 insertions(+), 1 deletion(-)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index 0780b5840a3..43e65c3dffb 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13850,7 +13850,38 @@ do_warn_dangling_reference (tree expr)
>   	    if (TREE_CODE (arg) == ADDR_EXPR)
>   	      arg = TREE_OPERAND (arg, 0);
>   	    if (expr_represents_temporary_p (arg))
> -	      return expr;
> +	      {
> +		/* An ugly attempt to reduce the number of -Wdangling-reference
> +		   false positives concerning reference wrappers (c++/107532).
> +		   Don't warn about s.a().b() but do warn about S().a().b(),
> +		   supposing that the member function is returning a reference
> +		   to a subobject of the (non-temporary) object.  */
> +		if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> +		    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
> +		    && i == 0)
> +		  {
> +		    tree t = arg;
> +		    while (handled_component_p (t))
> +		      t = TREE_OPERAND (t, 0);
> +		    t = TARGET_EXPR_INITIAL (arg);
> +		    /* Quite likely we don't have a chain of member functions
> +		       (like a().b().c()).  */
> +		    if (TREE_CODE (t) != CALL_EXPR)
> +		      return expr;
> +		    /* Walk the call chain to the original object and see if
> +		       it was a temporary.  */
> +		    do
> +		      t = tree_strip_nop_conversions (CALL_EXPR_ARG (t, 0));
> +		    while (TREE_CODE (t) == CALL_EXPR);
> +		    /* If the object argument is &TARGET_EXPR<>, we've started
> +		       off the chain with a temporary and we want to warn.  */
> +		    if (TREE_CODE (t) == ADDR_EXPR)
> +		      t = TREE_OPERAND (t, 0);
> +		    if (!expr_represents_temporary_p (t))
> +		      break;
> +		  }
> +		return expr;
> +	      }
>   	  /* Don't warn about member function like:
>   	      std::any a(...);
>   	      S& s = a.emplace<S>({0}, 0);
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..32280f3e282
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner(); // { dg-warning "dangling reference" }
> +  (void) d8;
> +}
> 
> base-commit: c6a011119bfa038ccbfc9f123ede14a3d6237fab


^ permalink raw reply	[flat|nested] 17+ messages in thread

* [PATCH v2] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-18 21:07 ` Jason Merrill
@ 2023-01-19  1:13   ` Marek Polacek
  2023-01-19 18:02     ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-01-19  1:13 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
> On 1/18/23 12:52, Marek Polacek wrote:
> > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > some grief.  The code in question uses a reference wrapper with a member
> > function returning a reference to a subobject of a non-temporary object:
> > 
> >    const Plane & meta = fm.planes().inner();
> > 
> > I've tried a few approaches, e.g., checking that the member function's
> > return type is the same as the type of the enclosing class (which is
> > the case for member functions returning *this), but that then breaks
> > Wdangling-reference4.C with std::optional<std::string>.
> > 
> > So I figured that perhaps we want to look at the object we're invoking
> > the member function(s) on and see if that is a temporary, as in, don't
> > warn about
> > 
> >    const Plane & meta = fm.planes().inner();
> > 
> > but do warn about
> > 
> >    const Plane & meta = FrameMetadata().planes().inner();
> > 
> > It's ugly, but better than asking users to add #pragmas into their code.
> 
> Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
> reference-like type.  If planes() returned a class that held data, we would
> want to warn.

Sure, it's always some kind of tradeoff with warnings :/.
 
> In this case, we might recognize the reference-like class because it has a
> reference member and a constructor taking the same reference type.

That occurred to me too, but then I found out that std::reference_wrapper
actually uses T*, not T&, as you say.  But here's a patch to do that
(I hope).
 
> That wouldn't help with std::reference_wrapper or std::ref_view because they
> have pointer members instead of references, but perhaps loosening the check
> to include that case would make sense?

Sorry, I don't understand what you mean by loosening the check.  I could
hardcode std::reference_wrapper and std::ref_view but I don't think that's
what you meant.  Surely I cannot _not_ warn for any class that contains a
T*.

Here's the patch so that we have some actual code to discuss...  Thanks.

-- >8 --
Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

Perhaps we want to look at the member function's enclosing class
to see if it's a reference wrapper class (meaning, has a reference
member and a constructor taking the same reference type) and don't
warn if so, supposing that the member function returns a reference
to a non-temporary object.

It's ugly, but better than asking users to add #pragmas into their code.

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (do_warn_dangling_reference): Don't warn when the
	member function comes from a reference wrapper class.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
---
 gcc/cp/call.cc                                | 32 ++++++++
 .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
 2 files changed, 109 insertions(+)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index 0780b5840a3..b0670a21240 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13832,6 +13832,38 @@ do_warn_dangling_reference (tree expr)
 	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
 	  return NULL_TREE;
 
+	/* An attempt to reduce the number of -Wdangling-reference
+	   false positives concerning reference wrappers (c++/107532).
+	   If the enclosing class is a reference-like class, that is, has
+	   a reference member and a constructor taking the same reference type,
+	   we suppose that the member function is returning a reference
+	   to a non-temporary object.  */
+	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
+	    && !DECL_OVERLOADED_OPERATOR_P (fndecl))
+	  {
+	    tree ctx = CP_DECL_CONTEXT (fndecl);
+	    for (tree fields = TYPE_FIELDS (ctx);
+		 fields;
+		 fields = DECL_CHAIN (fields))
+	      {
+		if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
+		  continue;
+		tree type = TREE_TYPE (fields);
+		if (!TYPE_REF_P (type))
+		  continue;
+		/* OK, the field is a reference member.  Do we have
+		   a constructor taking its type?  */
+		for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctx)))
+		  {
+		    tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
+		    if (args
+			&& same_type_p (TREE_VALUE (args), type)
+			&& TREE_CHAIN (args) == void_list_node)
+		      return NULL_TREE;
+		  }
+	      }
+	  }
+
 	/* Here we're looking to see if any of the arguments is a temporary
 	   initializing a reference parameter.  */
 	for (int i = 0; i < call_expr_nargs (expr); ++i)
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..4d585891fae
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner();
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner();
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner();
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner();
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner();
+  (void) d8;
+}

base-commit: 8e2c6e7b426b6c9c13076208b2e176d4aa1432f1
-- 
2.39.0


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v2] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-19  1:13   ` [PATCH v2] " Marek Polacek
@ 2023-01-19 18:02     ` Jason Merrill
  2023-01-20  2:03       ` [PATCH v3] " Marek Polacek
  0 siblings, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-01-19 18:02 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 1/18/23 20:13, Marek Polacek wrote:
> On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
>> On 1/18/23 12:52, Marek Polacek wrote:
>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>> some grief.  The code in question uses a reference wrapper with a member
>>> function returning a reference to a subobject of a non-temporary object:
>>>
>>>     const Plane & meta = fm.planes().inner();
>>>
>>> I've tried a few approaches, e.g., checking that the member function's
>>> return type is the same as the type of the enclosing class (which is
>>> the case for member functions returning *this), but that then breaks
>>> Wdangling-reference4.C with std::optional<std::string>.
>>>
>>> So I figured that perhaps we want to look at the object we're invoking
>>> the member function(s) on and see if that is a temporary, as in, don't
>>> warn about
>>>
>>>     const Plane & meta = fm.planes().inner();
>>>
>>> but do warn about
>>>
>>>     const Plane & meta = FrameMetadata().planes().inner();
>>>
>>> It's ugly, but better than asking users to add #pragmas into their code.
>>
>> Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
>> reference-like type.  If planes() returned a class that held data, we would
>> want to warn.
> 
> Sure, it's always some kind of tradeoff with warnings :/.
>   
>> In this case, we might recognize the reference-like class because it has a
>> reference member and a constructor taking the same reference type.
> 
> That occurred to me too, but then I found out that std::reference_wrapper
> actually uses T*, not T&, as you say.  But here's a patch to do that
> (I hope).
>   
>> That wouldn't help with std::reference_wrapper or std::ref_view because they
>> have pointer members instead of references, but perhaps loosening the check
>> to include that case would make sense?
> 
> Sorry, I don't understand what you mean by loosening the check.  I could
> hardcode std::reference_wrapper and std::ref_view but I don't think that's
> what you meant.

Indeed that's not what I meant, but as I was saying in our meeting I 
think it's worth doing; the compiler has various tweaks to handle 
specific standard-library classes better.

> Surely I cannot _not_ warn for any class that contains a T*.

I was thinking if a constructor takes a T& and the class has a T* that 
would be close enough, though this also wouldn't handle the standard 
library classes so the benefit is questionable.

> Here's the patch so that we have some actual code to discuss...  Thanks.
> 
> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> Perhaps we want to look at the member function's enclosing class
> to see if it's a reference wrapper class (meaning, has a reference
> member and a constructor taking the same reference type) and don't
> warn if so, supposing that the member function returns a reference
> to a non-temporary object.
> 
> It's ugly, but better than asking users to add #pragmas into their code.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (do_warn_dangling_reference): Don't warn when the
> 	member function comes from a reference wrapper class.

Let's factor the new code out into e.g. reference_like_class_p

> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> ---
>   gcc/cp/call.cc                                | 32 ++++++++
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
>   2 files changed, 109 insertions(+)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index 0780b5840a3..b0670a21240 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13832,6 +13832,38 @@ do_warn_dangling_reference (tree expr)
>   	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
>   	  return NULL_TREE;
>   
> +	/* An attempt to reduce the number of -Wdangling-reference
> +	   false positives concerning reference wrappers (c++/107532).
> +	   If the enclosing class is a reference-like class, that is, has
> +	   a reference member and a constructor taking the same reference type,
> +	   we suppose that the member function is returning a reference
> +	   to a non-temporary object.  */
> +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl))
> +	  {
> +	    tree ctx = CP_DECL_CONTEXT (fndecl);
> +	    for (tree fields = TYPE_FIELDS (ctx);
> +		 fields;
> +		 fields = DECL_CHAIN (fields))
> +	      {
> +		if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +		  continue;
> +		tree type = TREE_TYPE (fields);
> +		if (!TYPE_REF_P (type))
> +		  continue;
> +		/* OK, the field is a reference member.  Do we have
> +		   a constructor taking its type?  */
> +		for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctx)))
> +		  {
> +		    tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +		    if (args
> +			&& same_type_p (TREE_VALUE (args), type)
> +			&& TREE_CHAIN (args) == void_list_node)
> +		      return NULL_TREE;
> +		  }
> +	      }
> +	  }
> +
>   	/* Here we're looking to see if any of the arguments is a temporary
>   	   initializing a reference parameter.  */
>   	for (int i = 0; i < call_expr_nargs (expr); ++i)
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..4d585891fae
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner();
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner();
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner();
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner();
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> 
> base-commit: 8e2c6e7b426b6c9c13076208b2e176d4aa1432f1


^ permalink raw reply	[flat|nested] 17+ messages in thread

* [PATCH v3] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-19 18:02     ` Jason Merrill
@ 2023-01-20  2:03       ` Marek Polacek
  2023-01-20 20:19         ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-01-20  2:03 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
> On 1/18/23 20:13, Marek Polacek wrote:
> > On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
> > > On 1/18/23 12:52, Marek Polacek wrote:
> > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > some grief.  The code in question uses a reference wrapper with a member
> > > > function returning a reference to a subobject of a non-temporary object:
> > > > 
> > > >     const Plane & meta = fm.planes().inner();
> > > > 
> > > > I've tried a few approaches, e.g., checking that the member function's
> > > > return type is the same as the type of the enclosing class (which is
> > > > the case for member functions returning *this), but that then breaks
> > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > 
> > > > So I figured that perhaps we want to look at the object we're invoking
> > > > the member function(s) on and see if that is a temporary, as in, don't
> > > > warn about
> > > > 
> > > >     const Plane & meta = fm.planes().inner();
> > > > 
> > > > but do warn about
> > > > 
> > > >     const Plane & meta = FrameMetadata().planes().inner();
> > > > 
> > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > 
> > > Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
> > > reference-like type.  If planes() returned a class that held data, we would
> > > want to warn.
> > 
> > Sure, it's always some kind of tradeoff with warnings :/.
> > > In this case, we might recognize the reference-like class because it has a
> > > reference member and a constructor taking the same reference type.
> > 
> > That occurred to me too, but then I found out that std::reference_wrapper
> > actually uses T*, not T&, as you say.  But here's a patch to do that
> > (I hope).
> > > That wouldn't help with std::reference_wrapper or std::ref_view because they
> > > have pointer members instead of references, but perhaps loosening the check
> > > to include that case would make sense?
> > 
> > Sorry, I don't understand what you mean by loosening the check.  I could
> > hardcode std::reference_wrapper and std::ref_view but I don't think that's
> > what you meant.
> 
> Indeed that's not what I meant, but as I was saying in our meeting I think
> it's worth doing; the compiler has various tweaks to handle specific
> standard-library classes better.
 
Okay, done in the patch below.  Except that I'm not including a test for
std::ranges::ref_view because I don't really know how that works.

> > Surely I cannot _not_ warn for any class that contains a T*.
> 
> I was thinking if a constructor takes a T& and the class has a T* that would
> be close enough, though this also wouldn't handle the standard library
> classes so the benefit is questionable.
> 
> > Here's the patch so that we have some actual code to discuss...  Thanks.
> > 
> > -- >8 --
> > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > some grief.  The code in question uses a reference wrapper with a member
> > function returning a reference to a subobject of a non-temporary object:
> > 
> >    const Plane & meta = fm.planes().inner();
> > 
> > I've tried a few approaches, e.g., checking that the member function's
> > return type is the same as the type of the enclosing class (which is
> > the case for member functions returning *this), but that then breaks
> > Wdangling-reference4.C with std::optional<std::string>.
> > 
> > Perhaps we want to look at the member function's enclosing class
> > to see if it's a reference wrapper class (meaning, has a reference
> > member and a constructor taking the same reference type) and don't
> > warn if so, supposing that the member function returns a reference
> > to a non-temporary object.
> > 
> > It's ugly, but better than asking users to add #pragmas into their code.
> > 
> > 	PR c++/107532
> > 
> > gcc/cp/ChangeLog:
> > 
> > 	* call.cc (do_warn_dangling_reference): Don't warn when the
> > 	member function comes from a reference wrapper class.
> 
> Let's factor the new code out into e.g. reference_like_class_p

Done.  Thanks,

Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?

-- >8 --
Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

Perhaps we want to look at the member function's enclosing class
to see if it's a reference wrapper class (meaning, has a reference
member and a constructor taking the same reference type, or is
std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
supposing that the member function returns a reference to a non-temporary
object.

It's ugly, but better than asking users to add #pragmas into their code.

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (reference_like_class_p): New.
	(do_warn_dangling_reference): Don't warn when the member function comes
	from a reference_like_class_p.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
	* g++.dg/warn/Wdangling-reference9.C: New test.
---
 gcc/cp/call.cc                                | 48 ++++++++++++
 .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
 .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
 3 files changed, 146 insertions(+)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index 991730713e6..672722998ee 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
   return true;
 }
 
+/* Return true if a class CTYPE is either std::reference_wrapper or
+   std::ref_view, or a reference wrapper class.  We consider a class
+   a reference wrapper class if it has a reference member and a
+   constructor taking the same reference type.  */
+
+static bool
+reference_like_class_p (tree ctype)
+{
+  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
+  if (decl_in_std_namespace_p (tdecl))
+    {
+      tree name = DECL_NAME (tdecl);
+      return (name
+	      && (id_equal (name, "reference_wrapper")
+		  || id_equal (name, "ref_view")));
+    }
+  for (tree fields = TYPE_FIELDS (ctype);
+       fields;
+       fields = DECL_CHAIN (fields))
+    {
+      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
+	continue;
+      tree type = TREE_TYPE (fields);
+      if (!TYPE_REF_P (type))
+	continue;
+      /* OK, the field is a reference member.  Do we have a constructor
+	 taking its type?  */
+      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
+	{
+	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
+	  if (args
+	      && same_type_p (TREE_VALUE (args), type)
+	      && TREE_CHAIN (args) == void_list_node)
+	    return true;
+	}
+    }
+  return false;
+}
+
 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
    that initializes the LHS (and at least one of its arguments represents
    a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
@@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
 	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
 	  return NULL_TREE;
 
+	/* An attempt to reduce the number of -Wdangling-reference
+	   false positives concerning reference wrappers (c++/107532).
+	   Here we suppose that a member function of such a reference
+	   wrapper class returns a reference to a non-temporary object.  */
+	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
+	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
+	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
+	  return NULL_TREE;
+
 	/* Here we're looking to see if any of the arguments is a temporary
 	   initializing a reference parameter.  */
 	for (int i = 0; i < call_expr_nargs (expr); ++i)
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..4d585891fae
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner();
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner();
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner();
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner();
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner();
+  (void) d8;
+}
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
new file mode 100644
index 00000000000..15c1f6b9dd2
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
@@ -0,0 +1,21 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+#include <functional>
+
+struct X { int n; };
+
+struct S {
+  std::reference_wrapper<const X> wrapit() const { return x; }
+  X x;
+};
+
+void
+g (const S& s)
+{
+  const auto& a1 = s.wrapit().get();
+  (void) a1;
+  const auto& a2 = S().wrapit().get();
+  (void) a2;
+}

base-commit: 0846336de56119777861e02bf68f92a6af466000
-- 
2.39.0


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v3] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-20  2:03       ` [PATCH v3] " Marek Polacek
@ 2023-01-20 20:19         ` Jason Merrill
  2023-01-24 22:49           ` Marek Polacek
  0 siblings, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-01-20 20:19 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 1/19/23 21:03, Marek Polacek wrote:
> On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
>> On 1/18/23 20:13, Marek Polacek wrote:
>>> On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
>>>> On 1/18/23 12:52, Marek Polacek wrote:
>>>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>>>> some grief.  The code in question uses a reference wrapper with a member
>>>>> function returning a reference to a subobject of a non-temporary object:
>>>>>
>>>>>      const Plane & meta = fm.planes().inner();
>>>>>
>>>>> I've tried a few approaches, e.g., checking that the member function's
>>>>> return type is the same as the type of the enclosing class (which is
>>>>> the case for member functions returning *this), but that then breaks
>>>>> Wdangling-reference4.C with std::optional<std::string>.
>>>>>
>>>>> So I figured that perhaps we want to look at the object we're invoking
>>>>> the member function(s) on and see if that is a temporary, as in, don't
>>>>> warn about
>>>>>
>>>>>      const Plane & meta = fm.planes().inner();
>>>>>
>>>>> but do warn about
>>>>>
>>>>>      const Plane & meta = FrameMetadata().planes().inner();
>>>>>
>>>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>>
>>>> Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
>>>> reference-like type.  If planes() returned a class that held data, we would
>>>> want to warn.
>>>
>>> Sure, it's always some kind of tradeoff with warnings :/.
>>>> In this case, we might recognize the reference-like class because it has a
>>>> reference member and a constructor taking the same reference type.
>>>
>>> That occurred to me too, but then I found out that std::reference_wrapper
>>> actually uses T*, not T&, as you say.  But here's a patch to do that
>>> (I hope).
>>>> That wouldn't help with std::reference_wrapper or std::ref_view because they
>>>> have pointer members instead of references, but perhaps loosening the check
>>>> to include that case would make sense?
>>>
>>> Sorry, I don't understand what you mean by loosening the check.  I could
>>> hardcode std::reference_wrapper and std::ref_view but I don't think that's
>>> what you meant.
>>
>> Indeed that's not what I meant, but as I was saying in our meeting I think
>> it's worth doing; the compiler has various tweaks to handle specific
>> standard-library classes better.
>   
> Okay, done in the patch below.  Except that I'm not including a test for
> std::ranges::ref_view because I don't really know how that works.
> 
>>> Surely I cannot _not_ warn for any class that contains a T*.
>>
>> I was thinking if a constructor takes a T& and the class has a T* that would
>> be close enough, though this also wouldn't handle the standard library
>> classes so the benefit is questionable.
>>
>>> Here's the patch so that we have some actual code to discuss...  Thanks.
>>>
>>> -- >8 --
>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>> some grief.  The code in question uses a reference wrapper with a member
>>> function returning a reference to a subobject of a non-temporary object:
>>>
>>>     const Plane & meta = fm.planes().inner();
>>>
>>> I've tried a few approaches, e.g., checking that the member function's
>>> return type is the same as the type of the enclosing class (which is
>>> the case for member functions returning *this), but that then breaks
>>> Wdangling-reference4.C with std::optional<std::string>.
>>>
>>> Perhaps we want to look at the member function's enclosing class
>>> to see if it's a reference wrapper class (meaning, has a reference
>>> member and a constructor taking the same reference type) and don't
>>> warn if so, supposing that the member function returns a reference
>>> to a non-temporary object.
>>>
>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>
>>> 	PR c++/107532
>>>
>>> gcc/cp/ChangeLog:
>>>
>>> 	* call.cc (do_warn_dangling_reference): Don't warn when the
>>> 	member function comes from a reference wrapper class.
>>
>> Let's factor the new code out into e.g. reference_like_class_p
> 
> Done.  Thanks,
> 
> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> 
> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> Perhaps we want to look at the member function's enclosing class
> to see if it's a reference wrapper class (meaning, has a reference
> member and a constructor taking the same reference type, or is
> std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
> supposing that the member function returns a reference to a non-temporary
> object.
> 
> It's ugly, but better than asking users to add #pragmas into their code.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (reference_like_class_p): New.
> 	(do_warn_dangling_reference): Don't warn when the member function comes
> 	from a reference_like_class_p.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> 	* g++.dg/warn/Wdangling-reference9.C: New test.
> ---
>   gcc/cp/call.cc                                | 48 ++++++++++++
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
>   .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
>   3 files changed, 146 insertions(+)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index 991730713e6..672722998ee 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
>     return true;
>   }
>   
> +/* Return true if a class CTYPE is either std::reference_wrapper or
> +   std::ref_view, or a reference wrapper class.  We consider a class
> +   a reference wrapper class if it has a reference member and a
> +   constructor taking the same reference type.  */
> +
> +static bool
> +reference_like_class_p (tree ctype)
> +{
> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> +  if (decl_in_std_namespace_p (tdecl))
> +    {
> +      tree name = DECL_NAME (tdecl);
> +      return (name
> +	      && (id_equal (name, "reference_wrapper")
> +		  || id_equal (name, "ref_view")));
> +    }
> +  for (tree fields = TYPE_FIELDS (ctype);
> +       fields;
> +       fields = DECL_CHAIN (fields))
> +    {
> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +	continue;
> +      tree type = TREE_TYPE (fields);
> +      if (!TYPE_REF_P (type))
> +	continue;
> +      /* OK, the field is a reference member.  Do we have a constructor
> +	 taking its type?  */
> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> +	{
> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +	  if (args
> +	      && same_type_p (TREE_VALUE (args), type)
> +	      && TREE_CHAIN (args) == void_list_node)
> +	    return true;
> +	}
> +    }
> +  return false;
> +}
> +
>   /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>      that initializes the LHS (and at least one of its arguments represents
>      a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> @@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
>   	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
>   	  return NULL_TREE;
>   
> +	/* An attempt to reduce the number of -Wdangling-reference
> +	   false positives concerning reference wrappers (c++/107532).
> +	   Here we suppose that a member function of such a reference
> +	   wrapper class returns a reference to a non-temporary object.  */
> +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
> +	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))

Ah, in this case I was thinking rather than return we would want to look 
through to the initializer of the reference wrapper, and warn if that's 
a temporary, so we can catch the *2 cases in your tests.

So, treating ref-like classes as much like references as we can.  Some 
of your v1 patch ought to be useful in implementing this, but only 
looking through one call at a time, not all of them like that patch.

> +	  return NULL_TREE;
> +
>   	/* Here we're looking to see if any of the arguments is a temporary
>   	   initializing a reference parameter.  */
>   	for (int i = 0; i < call_expr_nargs (expr); ++i)
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..4d585891fae
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner();
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner();
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner();
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner();
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> new file mode 100644
> index 00000000000..15c1f6b9dd2
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> @@ -0,0 +1,21 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +#include <functional>
> +
> +struct X { int n; };
> +
> +struct S {
> +  std::reference_wrapper<const X> wrapit() const { return x; }
> +  X x;
> +};
> +
> +void
> +g (const S& s)
> +{
> +  const auto& a1 = s.wrapit().get();
> +  (void) a1;
> +  const auto& a2 = S().wrapit().get();
> +  (void) a2;
> +}
> 
> base-commit: 0846336de56119777861e02bf68f92a6af466000


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v3] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-20 20:19         ` Jason Merrill
@ 2023-01-24 22:49           ` Marek Polacek
  2023-02-06  1:25             ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-01-24 22:49 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Fri, Jan 20, 2023 at 03:19:54PM -0500, Jason Merrill wrote:
> On 1/19/23 21:03, Marek Polacek wrote:
> > On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
> > > On 1/18/23 20:13, Marek Polacek wrote:
> > > > On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
> > > > > On 1/18/23 12:52, Marek Polacek wrote:
> > > > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > > > some grief.  The code in question uses a reference wrapper with a member
> > > > > > function returning a reference to a subobject of a non-temporary object:
> > > > > > 
> > > > > >      const Plane & meta = fm.planes().inner();
> > > > > > 
> > > > > > I've tried a few approaches, e.g., checking that the member function's
> > > > > > return type is the same as the type of the enclosing class (which is
> > > > > > the case for member functions returning *this), but that then breaks
> > > > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > > > 
> > > > > > So I figured that perhaps we want to look at the object we're invoking
> > > > > > the member function(s) on and see if that is a temporary, as in, don't
> > > > > > warn about
> > > > > > 
> > > > > >      const Plane & meta = fm.planes().inner();
> > > > > > 
> > > > > > but do warn about
> > > > > > 
> > > > > >      const Plane & meta = FrameMetadata().planes().inner();
> > > > > > 
> > > > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > > 
> > > > > Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
> > > > > reference-like type.  If planes() returned a class that held data, we would
> > > > > want to warn.
> > > > 
> > > > Sure, it's always some kind of tradeoff with warnings :/.
> > > > > In this case, we might recognize the reference-like class because it has a
> > > > > reference member and a constructor taking the same reference type.
> > > > 
> > > > That occurred to me too, but then I found out that std::reference_wrapper
> > > > actually uses T*, not T&, as you say.  But here's a patch to do that
> > > > (I hope).
> > > > > That wouldn't help with std::reference_wrapper or std::ref_view because they
> > > > > have pointer members instead of references, but perhaps loosening the check
> > > > > to include that case would make sense?
> > > > 
> > > > Sorry, I don't understand what you mean by loosening the check.  I could
> > > > hardcode std::reference_wrapper and std::ref_view but I don't think that's
> > > > what you meant.
> > > 
> > > Indeed that's not what I meant, but as I was saying in our meeting I think
> > > it's worth doing; the compiler has various tweaks to handle specific
> > > standard-library classes better.
> > Okay, done in the patch below.  Except that I'm not including a test for
> > std::ranges::ref_view because I don't really know how that works.
> > 
> > > > Surely I cannot _not_ warn for any class that contains a T*.
> > > 
> > > I was thinking if a constructor takes a T& and the class has a T* that would
> > > be close enough, though this also wouldn't handle the standard library
> > > classes so the benefit is questionable.
> > > 
> > > > Here's the patch so that we have some actual code to discuss...  Thanks.
> > > > 
> > > > -- >8 --
> > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > some grief.  The code in question uses a reference wrapper with a member
> > > > function returning a reference to a subobject of a non-temporary object:
> > > > 
> > > >     const Plane & meta = fm.planes().inner();
> > > > 
> > > > I've tried a few approaches, e.g., checking that the member function's
> > > > return type is the same as the type of the enclosing class (which is
> > > > the case for member functions returning *this), but that then breaks
> > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > 
> > > > Perhaps we want to look at the member function's enclosing class
> > > > to see if it's a reference wrapper class (meaning, has a reference
> > > > member and a constructor taking the same reference type) and don't
> > > > warn if so, supposing that the member function returns a reference
> > > > to a non-temporary object.
> > > > 
> > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > 
> > > > 	PR c++/107532
> > > > 
> > > > gcc/cp/ChangeLog:
> > > > 
> > > > 	* call.cc (do_warn_dangling_reference): Don't warn when the
> > > > 	member function comes from a reference wrapper class.
> > > 
> > > Let's factor the new code out into e.g. reference_like_class_p
> > 
> > Done.  Thanks,
> > 
> > Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> > 
> > -- >8 --
> > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > some grief.  The code in question uses a reference wrapper with a member
> > function returning a reference to a subobject of a non-temporary object:
> > 
> >    const Plane & meta = fm.planes().inner();
> > 
> > I've tried a few approaches, e.g., checking that the member function's
> > return type is the same as the type of the enclosing class (which is
> > the case for member functions returning *this), but that then breaks
> > Wdangling-reference4.C with std::optional<std::string>.
> > 
> > Perhaps we want to look at the member function's enclosing class
> > to see if it's a reference wrapper class (meaning, has a reference
> > member and a constructor taking the same reference type, or is
> > std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
> > supposing that the member function returns a reference to a non-temporary
> > object.
> > 
> > It's ugly, but better than asking users to add #pragmas into their code.
> > 
> > 	PR c++/107532
> > 
> > gcc/cp/ChangeLog:
> > 
> > 	* call.cc (reference_like_class_p): New.
> > 	(do_warn_dangling_reference): Don't warn when the member function comes
> > 	from a reference_like_class_p.
> > 
> > gcc/testsuite/ChangeLog:
> > 
> > 	* g++.dg/warn/Wdangling-reference8.C: New test.
> > 	* g++.dg/warn/Wdangling-reference9.C: New test.
> > ---
> >   gcc/cp/call.cc                                | 48 ++++++++++++
> >   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
> >   .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
> >   3 files changed, 146 insertions(+)
> >   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> >   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> > 
> > diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> > index 991730713e6..672722998ee 100644
> > --- a/gcc/cp/call.cc
> > +++ b/gcc/cp/call.cc
> > @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
> >     return true;
> >   }
> > +/* Return true if a class CTYPE is either std::reference_wrapper or
> > +   std::ref_view, or a reference wrapper class.  We consider a class
> > +   a reference wrapper class if it has a reference member and a
> > +   constructor taking the same reference type.  */
> > +
> > +static bool
> > +reference_like_class_p (tree ctype)
> > +{
> > +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> > +  if (decl_in_std_namespace_p (tdecl))
> > +    {
> > +      tree name = DECL_NAME (tdecl);
> > +      return (name
> > +	      && (id_equal (name, "reference_wrapper")
> > +		  || id_equal (name, "ref_view")));
> > +    }
> > +  for (tree fields = TYPE_FIELDS (ctype);
> > +       fields;
> > +       fields = DECL_CHAIN (fields))
> > +    {
> > +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> > +	continue;
> > +      tree type = TREE_TYPE (fields);
> > +      if (!TYPE_REF_P (type))
> > +	continue;
> > +      /* OK, the field is a reference member.  Do we have a constructor
> > +	 taking its type?  */
> > +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> > +	{
> > +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> > +	  if (args
> > +	      && same_type_p (TREE_VALUE (args), type)
> > +	      && TREE_CHAIN (args) == void_list_node)
> > +	    return true;
> > +	}
> > +    }
> > +  return false;
> > +}
> > +
> >   /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
> >      that initializes the LHS (and at least one of its arguments represents
> >      a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> > @@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
> >   	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> >   	  return NULL_TREE;
> > +	/* An attempt to reduce the number of -Wdangling-reference
> > +	   false positives concerning reference wrappers (c++/107532).
> > +	   Here we suppose that a member function of such a reference
> > +	   wrapper class returns a reference to a non-temporary object.  */
> > +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> > +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
> > +	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
> 
> Ah, in this case I was thinking rather than return we would want to look
> through to the initializer of the reference wrapper, and warn if that's a
> temporary, so we can catch the *2 cases in your tests.
> 
> So, treating ref-like classes as much like references as we can.  Some of
> your v1 patch ought to be useful in implementing this, but only looking
> through one call at a time, not all of them like that patch.

Maybe this one, then?  I still have to loop through the calls though; EXPR in
do_warn_dangling_reference can be e.g.

Ref<const Plane>::inner (&TARGET_EXPR <D.2839, FrameMetadata::planes ((const struct FrameMetadata *) fm)>)

or

Ref<const Plane>::inner (&TARGET_EXPR <D.2908, FrameMetadata::planes (&TARGET_EXPR <D.2898, {.p_={.bytesused=0}}>)>)

and we want to warn only about the latter, but that means that I need to
look into the nested call 'planes' to see if the initializer was a temporary.

With this, we warn for the *2 cases too.

Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?

-- >8 --
Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

Perhaps we want to look at the member function's enclosing class
to see if it's a reference wrapper class (meaning, has a reference
member and a constructor taking the same reference type, or is
std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
supposing that the member function returns a reference to a non-temporary
object.

It's ugly, but better than asking users to add #pragmas into their code.

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (reference_like_class_p): New.
	(do_warn_dangling_reference): Don't warn when the member function comes
	from a reference_like_class_p.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
	* g++.dg/warn/Wdangling-reference9.C: New test.
---
 gcc/cp/call.cc                                | 70 ++++++++++++++++-
 .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
 .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
 3 files changed, 167 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index 5715a7cd1de..137870670e7 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
   return true;
 }
 
+/* Return true if a class CTYPE is either std::reference_wrapper or
+   std::ref_view, or a reference wrapper class.  We consider a class
+   a reference wrapper class if it has a reference member and a
+   constructor taking the same reference type.  */
+
+static bool
+reference_like_class_p (tree ctype)
+{
+  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
+  if (decl_in_std_namespace_p (tdecl))
+    {
+      tree name = DECL_NAME (tdecl);
+      return (name
+	      && (id_equal (name, "reference_wrapper")
+		  || id_equal (name, "ref_view")));
+    }
+  for (tree fields = TYPE_FIELDS (ctype);
+       fields;
+       fields = DECL_CHAIN (fields))
+    {
+      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
+	continue;
+      tree type = TREE_TYPE (fields);
+      if (!TYPE_REF_P (type))
+	continue;
+      /* OK, the field is a reference member.  Do we have a constructor
+	 taking its type?  */
+      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
+	{
+	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
+	  if (args
+	      && same_type_p (TREE_VALUE (args), type)
+	      && TREE_CHAIN (args) == void_list_node)
+	    return true;
+	}
+    }
+  return false;
+}
+
 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
    that initializes the LHS (and at least one of its arguments represents
    a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
@@ -13850,7 +13889,36 @@ do_warn_dangling_reference (tree expr)
 	    if (TREE_CODE (arg) == ADDR_EXPR)
 	      arg = TREE_OPERAND (arg, 0);
 	    if (expr_represents_temporary_p (arg))
-	      return expr;
+	      {
+		/* An attempt to reduce the number of -Wdangling-reference
+		   false positives concerning reference wrappers (c++/107532).
+		   Here we suppose that a member function of such a reference
+		   wrapper class returns a reference to a non-temporary object.  */
+		if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
+		    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
+		    && i == 0
+		    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
+		  {
+		    /* Let's see what the class object was initialized with.
+		       ARG is the TARGET_EXPR initializer; it may look like
+			 TARGET_EXPR <D.2839, A::foo (decl)>
+		       or
+			 TARGET_EXPR <D.2839, A::foo (&TARGET_EXPR <...>)>
+		       We should only warn for the second case.  */
+		    while (handled_component_p (arg))
+		      arg = TREE_OPERAND (arg, 0);
+		    arg = TARGET_EXPR_INITIAL (arg);
+		    /* Walk the call chain to the original object and see if
+		       it was a temporary.  */
+		    while (TREE_CODE (arg) == CALL_EXPR)
+		      arg = tree_strip_nop_conversions (CALL_EXPR_ARG (arg, 0));
+		    if (TREE_CODE (arg) == ADDR_EXPR)
+		      arg = TREE_OPERAND (arg, 0);
+		    if (!expr_represents_temporary_p (arg))
+		      break;
+		  }
+		return expr;
+	      }
 	  /* Don't warn about member function like:
 	      std::any a(...);
 	      S& s = a.emplace<S>({0}, 0);
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..330de1fd05d
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner();
+  (void) d8;
+}
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
new file mode 100644
index 00000000000..9ad83f7365e
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
@@ -0,0 +1,21 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+#include <functional>
+
+struct X { int n; };
+
+struct S {
+  std::reference_wrapper<const X> wrapit() const { return x; }
+  X x;
+};
+
+void
+g (const S& s)
+{
+  const auto& a1 = s.wrapit().get();
+  (void) a1;
+  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
+  (void) a2;
+}

base-commit: 327d45c57ebd2655a7599df0f01b8b5e2f82eda7
-- 
2.39.1


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v3] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-01-24 22:49           ` Marek Polacek
@ 2023-02-06  1:25             ` Jason Merrill
  2023-02-07 16:46               ` [PATCH v4] " Marek Polacek
  0 siblings, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-02-06  1:25 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 1/24/23 17:49, Marek Polacek wrote:
> On Fri, Jan 20, 2023 at 03:19:54PM -0500, Jason Merrill wrote:
>> On 1/19/23 21:03, Marek Polacek wrote:
>>> On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
>>>> On 1/18/23 20:13, Marek Polacek wrote:
>>>>> On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
>>>>>> On 1/18/23 12:52, Marek Polacek wrote:
>>>>>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>>>>>> some grief.  The code in question uses a reference wrapper with a member
>>>>>>> function returning a reference to a subobject of a non-temporary object:
>>>>>>>
>>>>>>>       const Plane & meta = fm.planes().inner();
>>>>>>>
>>>>>>> I've tried a few approaches, e.g., checking that the member function's
>>>>>>> return type is the same as the type of the enclosing class (which is
>>>>>>> the case for member functions returning *this), but that then breaks
>>>>>>> Wdangling-reference4.C with std::optional<std::string>.
>>>>>>>
>>>>>>> So I figured that perhaps we want to look at the object we're invoking
>>>>>>> the member function(s) on and see if that is a temporary, as in, don't
>>>>>>> warn about
>>>>>>>
>>>>>>>       const Plane & meta = fm.planes().inner();
>>>>>>>
>>>>>>> but do warn about
>>>>>>>
>>>>>>>       const Plane & meta = FrameMetadata().planes().inner();
>>>>>>>
>>>>>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>>>>
>>>>>> Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
>>>>>> reference-like type.  If planes() returned a class that held data, we would
>>>>>> want to warn.
>>>>>
>>>>> Sure, it's always some kind of tradeoff with warnings :/.
>>>>>> In this case, we might recognize the reference-like class because it has a
>>>>>> reference member and a constructor taking the same reference type.
>>>>>
>>>>> That occurred to me too, but then I found out that std::reference_wrapper
>>>>> actually uses T*, not T&, as you say.  But here's a patch to do that
>>>>> (I hope).
>>>>>> That wouldn't help with std::reference_wrapper or std::ref_view because they
>>>>>> have pointer members instead of references, but perhaps loosening the check
>>>>>> to include that case would make sense?
>>>>>
>>>>> Sorry, I don't understand what you mean by loosening the check.  I could
>>>>> hardcode std::reference_wrapper and std::ref_view but I don't think that's
>>>>> what you meant.
>>>>
>>>> Indeed that's not what I meant, but as I was saying in our meeting I think
>>>> it's worth doing; the compiler has various tweaks to handle specific
>>>> standard-library classes better.
>>> Okay, done in the patch below.  Except that I'm not including a test for
>>> std::ranges::ref_view because I don't really know how that works.
>>>
>>>>> Surely I cannot _not_ warn for any class that contains a T*.
>>>>
>>>> I was thinking if a constructor takes a T& and the class has a T* that would
>>>> be close enough, though this also wouldn't handle the standard library
>>>> classes so the benefit is questionable.
>>>>
>>>>> Here's the patch so that we have some actual code to discuss...  Thanks.
>>>>>
>>>>> -- >8 --
>>>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>>>> some grief.  The code in question uses a reference wrapper with a member
>>>>> function returning a reference to a subobject of a non-temporary object:
>>>>>
>>>>>      const Plane & meta = fm.planes().inner();
>>>>>
>>>>> I've tried a few approaches, e.g., checking that the member function's
>>>>> return type is the same as the type of the enclosing class (which is
>>>>> the case for member functions returning *this), but that then breaks
>>>>> Wdangling-reference4.C with std::optional<std::string>.
>>>>>
>>>>> Perhaps we want to look at the member function's enclosing class
>>>>> to see if it's a reference wrapper class (meaning, has a reference
>>>>> member and a constructor taking the same reference type) and don't
>>>>> warn if so, supposing that the member function returns a reference
>>>>> to a non-temporary object.
>>>>>
>>>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>>>
>>>>> 	PR c++/107532
>>>>>
>>>>> gcc/cp/ChangeLog:
>>>>>
>>>>> 	* call.cc (do_warn_dangling_reference): Don't warn when the
>>>>> 	member function comes from a reference wrapper class.
>>>>
>>>> Let's factor the new code out into e.g. reference_like_class_p
>>>
>>> Done.  Thanks,
>>>
>>> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
>>>
>>> -- >8 --
>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>> some grief.  The code in question uses a reference wrapper with a member
>>> function returning a reference to a subobject of a non-temporary object:
>>>
>>>     const Plane & meta = fm.planes().inner();
>>>
>>> I've tried a few approaches, e.g., checking that the member function's
>>> return type is the same as the type of the enclosing class (which is
>>> the case for member functions returning *this), but that then breaks
>>> Wdangling-reference4.C with std::optional<std::string>.
>>>
>>> Perhaps we want to look at the member function's enclosing class
>>> to see if it's a reference wrapper class (meaning, has a reference
>>> member and a constructor taking the same reference type, or is
>>> std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
>>> supposing that the member function returns a reference to a non-temporary
>>> object.
>>>
>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>
>>> 	PR c++/107532
>>>
>>> gcc/cp/ChangeLog:
>>>
>>> 	* call.cc (reference_like_class_p): New.
>>> 	(do_warn_dangling_reference): Don't warn when the member function comes
>>> 	from a reference_like_class_p.
>>>
>>> gcc/testsuite/ChangeLog:
>>>
>>> 	* g++.dg/warn/Wdangling-reference8.C: New test.
>>> 	* g++.dg/warn/Wdangling-reference9.C: New test.
>>> ---
>>>    gcc/cp/call.cc                                | 48 ++++++++++++
>>>    .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
>>>    .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
>>>    3 files changed, 146 insertions(+)
>>>    create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>>>    create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
>>>
>>> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
>>> index 991730713e6..672722998ee 100644
>>> --- a/gcc/cp/call.cc
>>> +++ b/gcc/cp/call.cc
>>> @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
>>>      return true;
>>>    }
>>> +/* Return true if a class CTYPE is either std::reference_wrapper or
>>> +   std::ref_view, or a reference wrapper class.  We consider a class
>>> +   a reference wrapper class if it has a reference member and a
>>> +   constructor taking the same reference type.  */
>>> +
>>> +static bool
>>> +reference_like_class_p (tree ctype)
>>> +{
>>> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
>>> +  if (decl_in_std_namespace_p (tdecl))
>>> +    {
>>> +      tree name = DECL_NAME (tdecl);
>>> +      return (name
>>> +	      && (id_equal (name, "reference_wrapper")
>>> +		  || id_equal (name, "ref_view")));
>>> +    }
>>> +  for (tree fields = TYPE_FIELDS (ctype);
>>> +       fields;
>>> +       fields = DECL_CHAIN (fields))
>>> +    {
>>> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
>>> +	continue;
>>> +      tree type = TREE_TYPE (fields);
>>> +      if (!TYPE_REF_P (type))
>>> +	continue;
>>> +      /* OK, the field is a reference member.  Do we have a constructor
>>> +	 taking its type?  */
>>> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
>>> +	{
>>> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
>>> +	  if (args
>>> +	      && same_type_p (TREE_VALUE (args), type)
>>> +	      && TREE_CHAIN (args) == void_list_node)
>>> +	    return true;
>>> +	}
>>> +    }
>>> +  return false;
>>> +}
>>> +
>>>    /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>>>       that initializes the LHS (and at least one of its arguments represents
>>>       a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
>>> @@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
>>>    	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
>>>    	  return NULL_TREE;
>>> +	/* An attempt to reduce the number of -Wdangling-reference
>>> +	   false positives concerning reference wrappers (c++/107532).
>>> +	   Here we suppose that a member function of such a reference
>>> +	   wrapper class returns a reference to a non-temporary object.  */
>>> +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>>> +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
>>> +	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
>>
>> Ah, in this case I was thinking rather than return we would want to look
>> through to the initializer of the reference wrapper, and warn if that's a
>> temporary, so we can catch the *2 cases in your tests.
>>
>> So, treating ref-like classes as much like references as we can.  Some of
>> your v1 patch ought to be useful in implementing this, but only looking
>> through one call at a time, not all of them like that patch.
> 
> Maybe this one, then?  I still have to loop through the calls though; EXPR in
> do_warn_dangling_reference can be e.g.
> 
> Ref<const Plane>::inner (&TARGET_EXPR <D.2839, FrameMetadata::planes ((const struct FrameMetadata *) fm)>)
> 
> or
> 
> Ref<const Plane>::inner (&TARGET_EXPR <D.2908, FrameMetadata::planes (&TARGET_EXPR <D.2898, {.p_={.bytesused=0}}>)>)
> 
> and we want to warn only about the latter, but that means that I need to
> look into the nested call 'planes' to see if the initializer was a temporary.

Right, but I was thinking we want to recurse like a few lines above, 
rather than loop.

> With this, we warn for the *2 cases too.
> 
> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> 
> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> Perhaps we want to look at the member function's enclosing class
> to see if it's a reference wrapper class (meaning, has a reference
> member and a constructor taking the same reference type, or is
> std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
> supposing that the member function returns a reference to a non-temporary
> object.
> 
> It's ugly, but better than asking users to add #pragmas into their code.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (reference_like_class_p): New.
> 	(do_warn_dangling_reference): Don't warn when the member function comes
> 	from a reference_like_class_p.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> 	* g++.dg/warn/Wdangling-reference9.C: New test.
> ---
>   gcc/cp/call.cc                                | 70 ++++++++++++++++-
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
>   .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
>   3 files changed, 167 insertions(+), 1 deletion(-)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index 5715a7cd1de..137870670e7 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
>     return true;
>   }
>   
> +/* Return true if a class CTYPE is either std::reference_wrapper or
> +   std::ref_view, or a reference wrapper class.  We consider a class
> +   a reference wrapper class if it has a reference member and a
> +   constructor taking the same reference type.  */
> +
> +static bool
> +reference_like_class_p (tree ctype)
> +{
> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> +  if (decl_in_std_namespace_p (tdecl))
> +    {
> +      tree name = DECL_NAME (tdecl);
> +      return (name
> +	      && (id_equal (name, "reference_wrapper")
> +		  || id_equal (name, "ref_view")));
> +    }
> +  for (tree fields = TYPE_FIELDS (ctype);
> +       fields;
> +       fields = DECL_CHAIN (fields))
> +    {
> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +	continue;
> +      tree type = TREE_TYPE (fields);
> +      if (!TYPE_REF_P (type))
> +	continue;
> +      /* OK, the field is a reference member.  Do we have a constructor
> +	 taking its type?  */
> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> +	{
> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +	  if (args
> +	      && same_type_p (TREE_VALUE (args), type)
> +	      && TREE_CHAIN (args) == void_list_node)
> +	    return true;
> +	}
> +    }
> +  return false;
> +}
> +
>   /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>      that initializes the LHS (and at least one of its arguments represents
>      a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> @@ -13850,7 +13889,36 @@ do_warn_dangling_reference (tree expr)
>   	    if (TREE_CODE (arg) == ADDR_EXPR)
>   	      arg = TREE_OPERAND (arg, 0);
>   	    if (expr_represents_temporary_p (arg))
> -	      return expr;
> +	      {
> +		/* An attempt to reduce the number of -Wdangling-reference
> +		   false positives concerning reference wrappers (c++/107532).
> +		   Here we suppose that a member function of such a reference
> +		   wrapper class returns a reference to a non-temporary object.  */
> +		if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> +		    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
> +		    && i == 0
> +		    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
> +		  {
> +		    /* Let's see what the class object was initialized with.
> +		       ARG is the TARGET_EXPR initializer; it may look like
> +			 TARGET_EXPR <D.2839, A::foo (decl)>
> +		       or
> +			 TARGET_EXPR <D.2839, A::foo (&TARGET_EXPR <...>)>
> +		       We should only warn for the second case.  */
> +		    while (handled_component_p (arg))
> +		      arg = TREE_OPERAND (arg, 0);
> +		    arg = TARGET_EXPR_INITIAL (arg);
> +		    /* Walk the call chain to the original object and see if
> +		       it was a temporary.  */
> +		    while (TREE_CODE (arg) == CALL_EXPR)
> +		      arg = tree_strip_nop_conversions (CALL_EXPR_ARG (arg, 0));
> +		    if (TREE_CODE (arg) == ADDR_EXPR)
> +		      arg = TREE_OPERAND (arg, 0);
> +		    if (!expr_represents_temporary_p (arg))
> +		      break;
> +		  }
> +		return expr;
> +	      }
>   	  /* Don't warn about member function like:
>   	      std::any a(...);
>   	      S& s = a.emplace<S>({0}, 0);
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..330de1fd05d
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> new file mode 100644
> index 00000000000..9ad83f7365e
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> @@ -0,0 +1,21 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +#include <functional>
> +
> +struct X { int n; };
> +
> +struct S {
> +  std::reference_wrapper<const X> wrapit() const { return x; }
> +  X x;
> +};
> +
> +void
> +g (const S& s)
> +{
> +  const auto& a1 = s.wrapit().get();
> +  (void) a1;
> +  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
> +  (void) a2;
> +}
> 
> base-commit: 327d45c57ebd2655a7599df0f01b8b5e2f82eda7


^ permalink raw reply	[flat|nested] 17+ messages in thread

* [PATCH v4] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-02-06  1:25             ` Jason Merrill
@ 2023-02-07 16:46               ` Marek Polacek
  2023-03-01 20:34                 ` Marek Polacek
  2023-03-01 21:53                 ` Jason Merrill
  0 siblings, 2 replies; 17+ messages in thread
From: Marek Polacek @ 2023-02-07 16:46 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Sun, Feb 05, 2023 at 05:25:25PM -0800, Jason Merrill wrote:
> On 1/24/23 17:49, Marek Polacek wrote:
> > On Fri, Jan 20, 2023 at 03:19:54PM -0500, Jason Merrill wrote:
> > > On 1/19/23 21:03, Marek Polacek wrote:
> > > > On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
> > > > > On 1/18/23 20:13, Marek Polacek wrote:
> > > > > > On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
> > > > > > > On 1/18/23 12:52, Marek Polacek wrote:
> > > > > > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > > > > > some grief.  The code in question uses a reference wrapper with a member
> > > > > > > > function returning a reference to a subobject of a non-temporary object:
> > > > > > > > 
> > > > > > > >       const Plane & meta = fm.planes().inner();
> > > > > > > > 
> > > > > > > > I've tried a few approaches, e.g., checking that the member function's
> > > > > > > > return type is the same as the type of the enclosing class (which is
> > > > > > > > the case for member functions returning *this), but that then breaks
> > > > > > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > > > > > 
> > > > > > > > So I figured that perhaps we want to look at the object we're invoking
> > > > > > > > the member function(s) on and see if that is a temporary, as in, don't
> > > > > > > > warn about
> > > > > > > > 
> > > > > > > >       const Plane & meta = fm.planes().inner();
> > > > > > > > 
> > > > > > > > but do warn about
> > > > > > > > 
> > > > > > > >       const Plane & meta = FrameMetadata().planes().inner();
> > > > > > > > 
> > > > > > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > > > > 
> > > > > > > Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
> > > > > > > reference-like type.  If planes() returned a class that held data, we would
> > > > > > > want to warn.
> > > > > > 
> > > > > > Sure, it's always some kind of tradeoff with warnings :/.
> > > > > > > In this case, we might recognize the reference-like class because it has a
> > > > > > > reference member and a constructor taking the same reference type.
> > > > > > 
> > > > > > That occurred to me too, but then I found out that std::reference_wrapper
> > > > > > actually uses T*, not T&, as you say.  But here's a patch to do that
> > > > > > (I hope).
> > > > > > > That wouldn't help with std::reference_wrapper or std::ref_view because they
> > > > > > > have pointer members instead of references, but perhaps loosening the check
> > > > > > > to include that case would make sense?
> > > > > > 
> > > > > > Sorry, I don't understand what you mean by loosening the check.  I could
> > > > > > hardcode std::reference_wrapper and std::ref_view but I don't think that's
> > > > > > what you meant.
> > > > > 
> > > > > Indeed that's not what I meant, but as I was saying in our meeting I think
> > > > > it's worth doing; the compiler has various tweaks to handle specific
> > > > > standard-library classes better.
> > > > Okay, done in the patch below.  Except that I'm not including a test for
> > > > std::ranges::ref_view because I don't really know how that works.
> > > > 
> > > > > > Surely I cannot _not_ warn for any class that contains a T*.
> > > > > 
> > > > > I was thinking if a constructor takes a T& and the class has a T* that would
> > > > > be close enough, though this also wouldn't handle the standard library
> > > > > classes so the benefit is questionable.
> > > > > 
> > > > > > Here's the patch so that we have some actual code to discuss...  Thanks.
> > > > > > 
> > > > > > -- >8 --
> > > > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > > > some grief.  The code in question uses a reference wrapper with a member
> > > > > > function returning a reference to a subobject of a non-temporary object:
> > > > > > 
> > > > > >      const Plane & meta = fm.planes().inner();
> > > > > > 
> > > > > > I've tried a few approaches, e.g., checking that the member function's
> > > > > > return type is the same as the type of the enclosing class (which is
> > > > > > the case for member functions returning *this), but that then breaks
> > > > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > > > 
> > > > > > Perhaps we want to look at the member function's enclosing class
> > > > > > to see if it's a reference wrapper class (meaning, has a reference
> > > > > > member and a constructor taking the same reference type) and don't
> > > > > > warn if so, supposing that the member function returns a reference
> > > > > > to a non-temporary object.
> > > > > > 
> > > > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > > > 
> > > > > > 	PR c++/107532
> > > > > > 
> > > > > > gcc/cp/ChangeLog:
> > > > > > 
> > > > > > 	* call.cc (do_warn_dangling_reference): Don't warn when the
> > > > > > 	member function comes from a reference wrapper class.
> > > > > 
> > > > > Let's factor the new code out into e.g. reference_like_class_p
> > > > 
> > > > Done.  Thanks,
> > > > 
> > > > Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> > > > 
> > > > -- >8 --
> > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > some grief.  The code in question uses a reference wrapper with a member
> > > > function returning a reference to a subobject of a non-temporary object:
> > > > 
> > > >     const Plane & meta = fm.planes().inner();
> > > > 
> > > > I've tried a few approaches, e.g., checking that the member function's
> > > > return type is the same as the type of the enclosing class (which is
> > > > the case for member functions returning *this), but that then breaks
> > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > 
> > > > Perhaps we want to look at the member function's enclosing class
> > > > to see if it's a reference wrapper class (meaning, has a reference
> > > > member and a constructor taking the same reference type, or is
> > > > std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
> > > > supposing that the member function returns a reference to a non-temporary
> > > > object.
> > > > 
> > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > 
> > > > 	PR c++/107532
> > > > 
> > > > gcc/cp/ChangeLog:
> > > > 
> > > > 	* call.cc (reference_like_class_p): New.
> > > > 	(do_warn_dangling_reference): Don't warn when the member function comes
> > > > 	from a reference_like_class_p.
> > > > 
> > > > gcc/testsuite/ChangeLog:
> > > > 
> > > > 	* g++.dg/warn/Wdangling-reference8.C: New test.
> > > > 	* g++.dg/warn/Wdangling-reference9.C: New test.
> > > > ---
> > > >    gcc/cp/call.cc                                | 48 ++++++++++++
> > > >    .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
> > > >    .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
> > > >    3 files changed, 146 insertions(+)
> > > >    create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> > > >    create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> > > > 
> > > > diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> > > > index 991730713e6..672722998ee 100644
> > > > --- a/gcc/cp/call.cc
> > > > +++ b/gcc/cp/call.cc
> > > > @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
> > > >      return true;
> > > >    }
> > > > +/* Return true if a class CTYPE is either std::reference_wrapper or
> > > > +   std::ref_view, or a reference wrapper class.  We consider a class
> > > > +   a reference wrapper class if it has a reference member and a
> > > > +   constructor taking the same reference type.  */
> > > > +
> > > > +static bool
> > > > +reference_like_class_p (tree ctype)
> > > > +{
> > > > +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> > > > +  if (decl_in_std_namespace_p (tdecl))
> > > > +    {
> > > > +      tree name = DECL_NAME (tdecl);
> > > > +      return (name
> > > > +	      && (id_equal (name, "reference_wrapper")
> > > > +		  || id_equal (name, "ref_view")));
> > > > +    }
> > > > +  for (tree fields = TYPE_FIELDS (ctype);
> > > > +       fields;
> > > > +       fields = DECL_CHAIN (fields))
> > > > +    {
> > > > +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> > > > +	continue;
> > > > +      tree type = TREE_TYPE (fields);
> > > > +      if (!TYPE_REF_P (type))
> > > > +	continue;
> > > > +      /* OK, the field is a reference member.  Do we have a constructor
> > > > +	 taking its type?  */
> > > > +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> > > > +	{
> > > > +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> > > > +	  if (args
> > > > +	      && same_type_p (TREE_VALUE (args), type)
> > > > +	      && TREE_CHAIN (args) == void_list_node)
> > > > +	    return true;
> > > > +	}
> > > > +    }
> > > > +  return false;
> > > > +}
> > > > +
> > > >    /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
> > > >       that initializes the LHS (and at least one of its arguments represents
> > > >       a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> > > > @@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
> > > >    	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> > > >    	  return NULL_TREE;
> > > > +	/* An attempt to reduce the number of -Wdangling-reference
> > > > +	   false positives concerning reference wrappers (c++/107532).
> > > > +	   Here we suppose that a member function of such a reference
> > > > +	   wrapper class returns a reference to a non-temporary object.  */
> > > > +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> > > > +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
> > > > +	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
> > > 
> > > Ah, in this case I was thinking rather than return we would want to look
> > > through to the initializer of the reference wrapper, and warn if that's a
> > > temporary, so we can catch the *2 cases in your tests.
> > > 
> > > So, treating ref-like classes as much like references as we can.  Some of
> > > your v1 patch ought to be useful in implementing this, but only looking
> > > through one call at a time, not all of them like that patch.
> > 
> > Maybe this one, then?  I still have to loop through the calls though; EXPR in
> > do_warn_dangling_reference can be e.g.
> > 
> > Ref<const Plane>::inner (&TARGET_EXPR <D.2839, FrameMetadata::planes ((const struct FrameMetadata *) fm)>)
> > 
> > or
> > 
> > Ref<const Plane>::inner (&TARGET_EXPR <D.2908, FrameMetadata::planes (&TARGET_EXPR <D.2898, {.p_={.bytesused=0}}>)>)
> > 
> > and we want to warn only about the latter, but that means that I need to
> > look into the nested call 'planes' to see if the initializer was a temporary.
> 
> Right, but I was thinking we want to recurse like a few lines above, rather
> than loop.

Ah yes, I can do that if I introduce a parameter that tells us
if we're processing an argument or not.  I think I'm finally
more or less satisfied with the patch, thanks.

Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?

-- >8 --
Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

This patch adjusts do_warn_dangling_reference so that we look through
reference wrapper classes (meaning, has a reference member and a
constructor taking the same reference type, or is std::reference_wrapper
or std::ranges::ref_view) and don't warn for them, supposing that the
member function returns a reference to a non-temporary object.

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (reference_like_class_p): New.
	(do_warn_dangling_reference): Add new bool parameter.  See through
	reference_like_class_p.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
	* g++.dg/warn/Wdangling-reference9.C: New test.
---
 gcc/cp/call.cc                                | 97 +++++++++++++++----
 .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++
 .../g++.dg/warn/Wdangling-reference9.C        | 21 ++++
 3 files changed, 178 insertions(+), 17 deletions(-)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index f7c5d9da94b..2a8edc2e7e2 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
   return true;
 }
 
+/* Return true if a class CTYPE is either std::reference_wrapper or
+   std::ref_view, or a reference wrapper class.  We consider a class
+   a reference wrapper class if it has a reference member and a
+   constructor taking the same reference type.  */
+
+static bool
+reference_like_class_p (tree ctype)
+{
+  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
+  if (decl_in_std_namespace_p (tdecl))
+    {
+      tree name = DECL_NAME (tdecl);
+      return (name
+	      && (id_equal (name, "reference_wrapper")
+		  || id_equal (name, "ref_view")));
+    }
+  for (tree fields = TYPE_FIELDS (ctype);
+       fields;
+       fields = DECL_CHAIN (fields))
+    {
+      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
+	continue;
+      tree type = TREE_TYPE (fields);
+      if (!TYPE_REF_P (type))
+	continue;
+      /* OK, the field is a reference member.  Do we have a constructor
+	 taking its type?  */
+      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
+	{
+	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
+	  if (args
+	      && same_type_p (TREE_VALUE (args), type)
+	      && TREE_CHAIN (args) == void_list_node)
+	    return true;
+	}
+    }
+  return false;
+}
+
 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
    that initializes the LHS (and at least one of its arguments represents
    a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
@@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
      const int& y = (f(1), 42); // NULL_TREE
      const int& z = f(f(1)); // f(f(1))
 
-   EXPR is the initializer.  */
+   EXPR is the initializer.  If ARG_P is true, we're processing an argument
+   to a function; the point is to distinguish between, for example,
+
+     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
+
+   where we shouldn't warn, and
+
+     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
+
+   where we should warn (Ref is a reference_like_class_p so we see through
+   it.  */
 
 static tree
-do_warn_dangling_reference (tree expr)
+do_warn_dangling_reference (tree expr, bool arg_p)
 {
   STRIP_NOPS (expr);
+  if (TREE_CODE (expr) == ADDR_EXPR)
+    expr = TREE_OPERAND (expr, 0);
+
+  if (arg_p && expr_represents_temporary_p (expr))
+    {
+      /* An attempt to reduce the number of -Wdangling-reference
+	 false positives concerning reference wrappers (c++/107532).
+	 Here we suppose that a member function of such a reference
+	 wrapper class returns a reference to a non-temporary object.  */
+      tree e = expr;
+      while (handled_component_p (e))
+	e = TREE_OPERAND (e, 0);
+      e = TREE_TYPE (e);
+      if (!CLASS_TYPE_P (e) || !reference_like_class_p (e))
+	return expr;
+    }
+
   switch (TREE_CODE (expr))
     {
     case CALL_EXPR:
@@ -13829,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
 	     std::pair<const int&, const int&> v = std::minmax(1, 2);
 	   which also creates a dangling reference, because std::minmax
 	   returns std::pair<const T&, const T&>(b, a).  */
-	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
+	if (!arg_p
+	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))
 	  return NULL_TREE;
 
 	/* Here we're looking to see if any of the arguments is a temporary
@@ -13842,14 +13909,10 @@ do_warn_dangling_reference (tree expr)
 	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
 		&& !TYPE_REF_P (TREE_TYPE (arg)))
 	      continue;
-	    /* It could also be another call taking a temporary and returning
-	       it and initializing this reference parameter.  */
-	    if (do_warn_dangling_reference (arg))
-	      return expr;
-	    STRIP_NOPS (arg);
-	    if (TREE_CODE (arg) == ADDR_EXPR)
-	      arg = TREE_OPERAND (arg, 0);
-	    if (expr_represents_temporary_p (arg))
+	    /* Recurse to see if the argument is a temporary.  It could also
+	       be another call taking a temporary and returning it and
+	       initializing this reference parameter.  */
+	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
 	      return expr;
 	  /* Don't warn about member function like:
 	      std::any a(...);
@@ -13866,15 +13929,15 @@ do_warn_dangling_reference (tree expr)
 	return NULL_TREE;
       }
     case COMPOUND_EXPR:
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
     case COND_EXPR:
-      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
+      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
 	return t;
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
     case PAREN_EXPR:
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
     case TARGET_EXPR:
-      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
+      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
     default:
       return NULL_TREE;
     }
@@ -13917,7 +13980,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
     = make_temp_override (global_dc->dc_warn_system_headers,
 			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
 			   || global_dc->dc_warn_system_headers));
-  if (tree call = do_warn_dangling_reference (init))
+  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
     {
       auto_diagnostic_group d;
       if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..330de1fd05d
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner();
+  (void) d8;
+}
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
new file mode 100644
index 00000000000..9ad83f7365e
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
@@ -0,0 +1,21 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+#include <functional>
+
+struct X { int n; };
+
+struct S {
+  std::reference_wrapper<const X> wrapit() const { return x; }
+  X x;
+};
+
+void
+g (const S& s)
+{
+  const auto& a1 = s.wrapit().get();
+  (void) a1;
+  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
+  (void) a2;
+}

base-commit: f661c0bb6371f355966a67b5ce71398e80792948
-- 
2.39.1


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v4] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-02-07 16:46               ` [PATCH v4] " Marek Polacek
@ 2023-03-01 20:34                 ` Marek Polacek
  2023-03-01 21:53                 ` Jason Merrill
  1 sibling, 0 replies; 17+ messages in thread
From: Marek Polacek @ 2023-03-01 20:34 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

Ping.

On Tue, Feb 07, 2023 at 11:46:10AM -0500, Marek Polacek wrote:
> On Sun, Feb 05, 2023 at 05:25:25PM -0800, Jason Merrill wrote:
> > On 1/24/23 17:49, Marek Polacek wrote:
> > > On Fri, Jan 20, 2023 at 03:19:54PM -0500, Jason Merrill wrote:
> > > > On 1/19/23 21:03, Marek Polacek wrote:
> > > > > On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
> > > > > > On 1/18/23 20:13, Marek Polacek wrote:
> > > > > > > On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
> > > > > > > > On 1/18/23 12:52, Marek Polacek wrote:
> > > > > > > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > > > > > > some grief.  The code in question uses a reference wrapper with a member
> > > > > > > > > function returning a reference to a subobject of a non-temporary object:
> > > > > > > > > 
> > > > > > > > >       const Plane & meta = fm.planes().inner();
> > > > > > > > > 
> > > > > > > > > I've tried a few approaches, e.g., checking that the member function's
> > > > > > > > > return type is the same as the type of the enclosing class (which is
> > > > > > > > > the case for member functions returning *this), but that then breaks
> > > > > > > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > > > > > > 
> > > > > > > > > So I figured that perhaps we want to look at the object we're invoking
> > > > > > > > > the member function(s) on and see if that is a temporary, as in, don't
> > > > > > > > > warn about
> > > > > > > > > 
> > > > > > > > >       const Plane & meta = fm.planes().inner();
> > > > > > > > > 
> > > > > > > > > but do warn about
> > > > > > > > > 
> > > > > > > > >       const Plane & meta = FrameMetadata().planes().inner();
> > > > > > > > > 
> > > > > > > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > > > > > 
> > > > > > > > Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
> > > > > > > > reference-like type.  If planes() returned a class that held data, we would
> > > > > > > > want to warn.
> > > > > > > 
> > > > > > > Sure, it's always some kind of tradeoff with warnings :/.
> > > > > > > > In this case, we might recognize the reference-like class because it has a
> > > > > > > > reference member and a constructor taking the same reference type.
> > > > > > > 
> > > > > > > That occurred to me too, but then I found out that std::reference_wrapper
> > > > > > > actually uses T*, not T&, as you say.  But here's a patch to do that
> > > > > > > (I hope).
> > > > > > > > That wouldn't help with std::reference_wrapper or std::ref_view because they
> > > > > > > > have pointer members instead of references, but perhaps loosening the check
> > > > > > > > to include that case would make sense?
> > > > > > > 
> > > > > > > Sorry, I don't understand what you mean by loosening the check.  I could
> > > > > > > hardcode std::reference_wrapper and std::ref_view but I don't think that's
> > > > > > > what you meant.
> > > > > > 
> > > > > > Indeed that's not what I meant, but as I was saying in our meeting I think
> > > > > > it's worth doing; the compiler has various tweaks to handle specific
> > > > > > standard-library classes better.
> > > > > Okay, done in the patch below.  Except that I'm not including a test for
> > > > > std::ranges::ref_view because I don't really know how that works.
> > > > > 
> > > > > > > Surely I cannot _not_ warn for any class that contains a T*.
> > > > > > 
> > > > > > I was thinking if a constructor takes a T& and the class has a T* that would
> > > > > > be close enough, though this also wouldn't handle the standard library
> > > > > > classes so the benefit is questionable.
> > > > > > 
> > > > > > > Here's the patch so that we have some actual code to discuss...  Thanks.
> > > > > > > 
> > > > > > > -- >8 --
> > > > > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > > > > some grief.  The code in question uses a reference wrapper with a member
> > > > > > > function returning a reference to a subobject of a non-temporary object:
> > > > > > > 
> > > > > > >      const Plane & meta = fm.planes().inner();
> > > > > > > 
> > > > > > > I've tried a few approaches, e.g., checking that the member function's
> > > > > > > return type is the same as the type of the enclosing class (which is
> > > > > > > the case for member functions returning *this), but that then breaks
> > > > > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > > > > 
> > > > > > > Perhaps we want to look at the member function's enclosing class
> > > > > > > to see if it's a reference wrapper class (meaning, has a reference
> > > > > > > member and a constructor taking the same reference type) and don't
> > > > > > > warn if so, supposing that the member function returns a reference
> > > > > > > to a non-temporary object.
> > > > > > > 
> > > > > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > > > > 
> > > > > > > 	PR c++/107532
> > > > > > > 
> > > > > > > gcc/cp/ChangeLog:
> > > > > > > 
> > > > > > > 	* call.cc (do_warn_dangling_reference): Don't warn when the
> > > > > > > 	member function comes from a reference wrapper class.
> > > > > > 
> > > > > > Let's factor the new code out into e.g. reference_like_class_p
> > > > > 
> > > > > Done.  Thanks,
> > > > > 
> > > > > Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> > > > > 
> > > > > -- >8 --
> > > > > Here, -Wdangling-reference triggers where it probably shouldn't, causing
> > > > > some grief.  The code in question uses a reference wrapper with a member
> > > > > function returning a reference to a subobject of a non-temporary object:
> > > > > 
> > > > >     const Plane & meta = fm.planes().inner();
> > > > > 
> > > > > I've tried a few approaches, e.g., checking that the member function's
> > > > > return type is the same as the type of the enclosing class (which is
> > > > > the case for member functions returning *this), but that then breaks
> > > > > Wdangling-reference4.C with std::optional<std::string>.
> > > > > 
> > > > > Perhaps we want to look at the member function's enclosing class
> > > > > to see if it's a reference wrapper class (meaning, has a reference
> > > > > member and a constructor taking the same reference type, or is
> > > > > std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
> > > > > supposing that the member function returns a reference to a non-temporary
> > > > > object.
> > > > > 
> > > > > It's ugly, but better than asking users to add #pragmas into their code.
> > > > > 
> > > > > 	PR c++/107532
> > > > > 
> > > > > gcc/cp/ChangeLog:
> > > > > 
> > > > > 	* call.cc (reference_like_class_p): New.
> > > > > 	(do_warn_dangling_reference): Don't warn when the member function comes
> > > > > 	from a reference_like_class_p.
> > > > > 
> > > > > gcc/testsuite/ChangeLog:
> > > > > 
> > > > > 	* g++.dg/warn/Wdangling-reference8.C: New test.
> > > > > 	* g++.dg/warn/Wdangling-reference9.C: New test.
> > > > > ---
> > > > >    gcc/cp/call.cc                                | 48 ++++++++++++
> > > > >    .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
> > > > >    .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
> > > > >    3 files changed, 146 insertions(+)
> > > > >    create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> > > > >    create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> > > > > 
> > > > > diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> > > > > index 991730713e6..672722998ee 100644
> > > > > --- a/gcc/cp/call.cc
> > > > > +++ b/gcc/cp/call.cc
> > > > > @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
> > > > >      return true;
> > > > >    }
> > > > > +/* Return true if a class CTYPE is either std::reference_wrapper or
> > > > > +   std::ref_view, or a reference wrapper class.  We consider a class
> > > > > +   a reference wrapper class if it has a reference member and a
> > > > > +   constructor taking the same reference type.  */
> > > > > +
> > > > > +static bool
> > > > > +reference_like_class_p (tree ctype)
> > > > > +{
> > > > > +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> > > > > +  if (decl_in_std_namespace_p (tdecl))
> > > > > +    {
> > > > > +      tree name = DECL_NAME (tdecl);
> > > > > +      return (name
> > > > > +	      && (id_equal (name, "reference_wrapper")
> > > > > +		  || id_equal (name, "ref_view")));
> > > > > +    }
> > > > > +  for (tree fields = TYPE_FIELDS (ctype);
> > > > > +       fields;
> > > > > +       fields = DECL_CHAIN (fields))
> > > > > +    {
> > > > > +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> > > > > +	continue;
> > > > > +      tree type = TREE_TYPE (fields);
> > > > > +      if (!TYPE_REF_P (type))
> > > > > +	continue;
> > > > > +      /* OK, the field is a reference member.  Do we have a constructor
> > > > > +	 taking its type?  */
> > > > > +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> > > > > +	{
> > > > > +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> > > > > +	  if (args
> > > > > +	      && same_type_p (TREE_VALUE (args), type)
> > > > > +	      && TREE_CHAIN (args) == void_list_node)
> > > > > +	    return true;
> > > > > +	}
> > > > > +    }
> > > > > +  return false;
> > > > > +}
> > > > > +
> > > > >    /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
> > > > >       that initializes the LHS (and at least one of its arguments represents
> > > > >       a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> > > > > @@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
> > > > >    	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> > > > >    	  return NULL_TREE;
> > > > > +	/* An attempt to reduce the number of -Wdangling-reference
> > > > > +	   false positives concerning reference wrappers (c++/107532).
> > > > > +	   Here we suppose that a member function of such a reference
> > > > > +	   wrapper class returns a reference to a non-temporary object.  */
> > > > > +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> > > > > +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
> > > > > +	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
> > > > 
> > > > Ah, in this case I was thinking rather than return we would want to look
> > > > through to the initializer of the reference wrapper, and warn if that's a
> > > > temporary, so we can catch the *2 cases in your tests.
> > > > 
> > > > So, treating ref-like classes as much like references as we can.  Some of
> > > > your v1 patch ought to be useful in implementing this, but only looking
> > > > through one call at a time, not all of them like that patch.
> > > 
> > > Maybe this one, then?  I still have to loop through the calls though; EXPR in
> > > do_warn_dangling_reference can be e.g.
> > > 
> > > Ref<const Plane>::inner (&TARGET_EXPR <D.2839, FrameMetadata::planes ((const struct FrameMetadata *) fm)>)
> > > 
> > > or
> > > 
> > > Ref<const Plane>::inner (&TARGET_EXPR <D.2908, FrameMetadata::planes (&TARGET_EXPR <D.2898, {.p_={.bytesused=0}}>)>)
> > > 
> > > and we want to warn only about the latter, but that means that I need to
> > > look into the nested call 'planes' to see if the initializer was a temporary.
> > 
> > Right, but I was thinking we want to recurse like a few lines above, rather
> > than loop.
> 
> Ah yes, I can do that if I introduce a parameter that tells us
> if we're processing an argument or not.  I think I'm finally
> more or less satisfied with the patch, thanks.
> 
> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> 
> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>   const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> This patch adjusts do_warn_dangling_reference so that we look through
> reference wrapper classes (meaning, has a reference member and a
> constructor taking the same reference type, or is std::reference_wrapper
> or std::ranges::ref_view) and don't warn for them, supposing that the
> member function returns a reference to a non-temporary object.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (reference_like_class_p): New.
> 	(do_warn_dangling_reference): Add new bool parameter.  See through
> 	reference_like_class_p.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> 	* g++.dg/warn/Wdangling-reference9.C: New test.
> ---
>  gcc/cp/call.cc                                | 97 +++++++++++++++----
>  .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++
>  .../g++.dg/warn/Wdangling-reference9.C        | 21 ++++
>  3 files changed, 178 insertions(+), 17 deletions(-)
>  create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>  create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index f7c5d9da94b..2a8edc2e7e2 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
>    return true;
>  }
>  
> +/* Return true if a class CTYPE is either std::reference_wrapper or
> +   std::ref_view, or a reference wrapper class.  We consider a class
> +   a reference wrapper class if it has a reference member and a
> +   constructor taking the same reference type.  */
> +
> +static bool
> +reference_like_class_p (tree ctype)
> +{
> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> +  if (decl_in_std_namespace_p (tdecl))
> +    {
> +      tree name = DECL_NAME (tdecl);
> +      return (name
> +	      && (id_equal (name, "reference_wrapper")
> +		  || id_equal (name, "ref_view")));
> +    }
> +  for (tree fields = TYPE_FIELDS (ctype);
> +       fields;
> +       fields = DECL_CHAIN (fields))
> +    {
> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +	continue;
> +      tree type = TREE_TYPE (fields);
> +      if (!TYPE_REF_P (type))
> +	continue;
> +      /* OK, the field is a reference member.  Do we have a constructor
> +	 taking its type?  */
> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> +	{
> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +	  if (args
> +	      && same_type_p (TREE_VALUE (args), type)
> +	      && TREE_CHAIN (args) == void_list_node)
> +	    return true;
> +	}
> +    }
> +  return false;
> +}
> +
>  /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>     that initializes the LHS (and at least one of its arguments represents
>     a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> @@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
>       const int& y = (f(1), 42); // NULL_TREE
>       const int& z = f(f(1)); // f(f(1))
>  
> -   EXPR is the initializer.  */
> +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
> +   to a function; the point is to distinguish between, for example,
> +
> +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
> +
> +   where we shouldn't warn, and
> +
> +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
> +
> +   where we should warn (Ref is a reference_like_class_p so we see through
> +   it.  */
>  
>  static tree
> -do_warn_dangling_reference (tree expr)
> +do_warn_dangling_reference (tree expr, bool arg_p)
>  {
>    STRIP_NOPS (expr);
> +  if (TREE_CODE (expr) == ADDR_EXPR)
> +    expr = TREE_OPERAND (expr, 0);
> +
> +  if (arg_p && expr_represents_temporary_p (expr))
> +    {
> +      /* An attempt to reduce the number of -Wdangling-reference
> +	 false positives concerning reference wrappers (c++/107532).
> +	 Here we suppose that a member function of such a reference
> +	 wrapper class returns a reference to a non-temporary object.  */
> +      tree e = expr;
> +      while (handled_component_p (e))
> +	e = TREE_OPERAND (e, 0);
> +      e = TREE_TYPE (e);
> +      if (!CLASS_TYPE_P (e) || !reference_like_class_p (e))
> +	return expr;
> +    }
> +
>    switch (TREE_CODE (expr))
>      {
>      case CALL_EXPR:
> @@ -13829,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
>  	     std::pair<const int&, const int&> v = std::minmax(1, 2);
>  	   which also creates a dangling reference, because std::minmax
>  	   returns std::pair<const T&, const T&>(b, a).  */
> -	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> +	if (!arg_p
> +	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))
>  	  return NULL_TREE;
>  
>  	/* Here we're looking to see if any of the arguments is a temporary
> @@ -13842,14 +13909,10 @@ do_warn_dangling_reference (tree expr)
>  	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>  		&& !TYPE_REF_P (TREE_TYPE (arg)))
>  	      continue;
> -	    /* It could also be another call taking a temporary and returning
> -	       it and initializing this reference parameter.  */
> -	    if (do_warn_dangling_reference (arg))
> -	      return expr;
> -	    STRIP_NOPS (arg);
> -	    if (TREE_CODE (arg) == ADDR_EXPR)
> -	      arg = TREE_OPERAND (arg, 0);
> -	    if (expr_represents_temporary_p (arg))
> +	    /* Recurse to see if the argument is a temporary.  It could also
> +	       be another call taking a temporary and returning it and
> +	       initializing this reference parameter.  */
> +	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
>  	      return expr;
>  	  /* Don't warn about member function like:
>  	      std::any a(...);
> @@ -13866,15 +13929,15 @@ do_warn_dangling_reference (tree expr)
>  	return NULL_TREE;
>        }
>      case COMPOUND_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
>      case COND_EXPR:
> -      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
> +      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
>  	return t;
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
>      case PAREN_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
>      case TARGET_EXPR:
> -      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
> +      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
>      default:
>        return NULL_TREE;
>      }
> @@ -13917,7 +13980,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
>      = make_temp_override (global_dc->dc_warn_system_headers,
>  			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
>  			   || global_dc->dc_warn_system_headers));
> -  if (tree call = do_warn_dangling_reference (init))
> +  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
>      {
>        auto_diagnostic_group d;
>        if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..330de1fd05d
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> new file mode 100644
> index 00000000000..9ad83f7365e
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> @@ -0,0 +1,21 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +#include <functional>
> +
> +struct X { int n; };
> +
> +struct S {
> +  std::reference_wrapper<const X> wrapit() const { return x; }
> +  X x;
> +};
> +
> +void
> +g (const S& s)
> +{
> +  const auto& a1 = s.wrapit().get();
> +  (void) a1;
> +  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
> +  (void) a2;
> +}
> 
> base-commit: f661c0bb6371f355966a67b5ce71398e80792948
> -- 
> 2.39.1
> 

Marek


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v4] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-02-07 16:46               ` [PATCH v4] " Marek Polacek
  2023-03-01 20:34                 ` Marek Polacek
@ 2023-03-01 21:53                 ` Jason Merrill
  2023-03-02 21:24                   ` Marek Polacek
  1 sibling, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-03-01 21:53 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 2/7/23 11:46, Marek Polacek wrote:
> On Sun, Feb 05, 2023 at 05:25:25PM -0800, Jason Merrill wrote:
>> On 1/24/23 17:49, Marek Polacek wrote:
>>> On Fri, Jan 20, 2023 at 03:19:54PM -0500, Jason Merrill wrote:
>>>> On 1/19/23 21:03, Marek Polacek wrote:
>>>>> On Thu, Jan 19, 2023 at 01:02:02PM -0500, Jason Merrill wrote:
>>>>>> On 1/18/23 20:13, Marek Polacek wrote:
>>>>>>> On Wed, Jan 18, 2023 at 04:07:59PM -0500, Jason Merrill wrote:
>>>>>>>> On 1/18/23 12:52, Marek Polacek wrote:
>>>>>>>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>>>>>>>> some grief.  The code in question uses a reference wrapper with a member
>>>>>>>>> function returning a reference to a subobject of a non-temporary object:
>>>>>>>>>
>>>>>>>>>        const Plane & meta = fm.planes().inner();
>>>>>>>>>
>>>>>>>>> I've tried a few approaches, e.g., checking that the member function's
>>>>>>>>> return type is the same as the type of the enclosing class (which is
>>>>>>>>> the case for member functions returning *this), but that then breaks
>>>>>>>>> Wdangling-reference4.C with std::optional<std::string>.
>>>>>>>>>
>>>>>>>>> So I figured that perhaps we want to look at the object we're invoking
>>>>>>>>> the member function(s) on and see if that is a temporary, as in, don't
>>>>>>>>> warn about
>>>>>>>>>
>>>>>>>>>        const Plane & meta = fm.planes().inner();
>>>>>>>>>
>>>>>>>>> but do warn about
>>>>>>>>>
>>>>>>>>>        const Plane & meta = FrameMetadata().planes().inner();
>>>>>>>>>
>>>>>>>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>>>>>>
>>>>>>>> Hmm, that doesn't seem right; the former is only OK because Ref is in fact a
>>>>>>>> reference-like type.  If planes() returned a class that held data, we would
>>>>>>>> want to warn.
>>>>>>>
>>>>>>> Sure, it's always some kind of tradeoff with warnings :/.
>>>>>>>> In this case, we might recognize the reference-like class because it has a
>>>>>>>> reference member and a constructor taking the same reference type.
>>>>>>>
>>>>>>> That occurred to me too, but then I found out that std::reference_wrapper
>>>>>>> actually uses T*, not T&, as you say.  But here's a patch to do that
>>>>>>> (I hope).
>>>>>>>> That wouldn't help with std::reference_wrapper or std::ref_view because they
>>>>>>>> have pointer members instead of references, but perhaps loosening the check
>>>>>>>> to include that case would make sense?
>>>>>>>
>>>>>>> Sorry, I don't understand what you mean by loosening the check.  I could
>>>>>>> hardcode std::reference_wrapper and std::ref_view but I don't think that's
>>>>>>> what you meant.
>>>>>>
>>>>>> Indeed that's not what I meant, but as I was saying in our meeting I think
>>>>>> it's worth doing; the compiler has various tweaks to handle specific
>>>>>> standard-library classes better.
>>>>> Okay, done in the patch below.  Except that I'm not including a test for
>>>>> std::ranges::ref_view because I don't really know how that works.
>>>>>
>>>>>>> Surely I cannot _not_ warn for any class that contains a T*.
>>>>>>
>>>>>> I was thinking if a constructor takes a T& and the class has a T* that would
>>>>>> be close enough, though this also wouldn't handle the standard library
>>>>>> classes so the benefit is questionable.
>>>>>>
>>>>>>> Here's the patch so that we have some actual code to discuss...  Thanks.
>>>>>>>
>>>>>>> -- >8 --
>>>>>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>>>>>> some grief.  The code in question uses a reference wrapper with a member
>>>>>>> function returning a reference to a subobject of a non-temporary object:
>>>>>>>
>>>>>>>       const Plane & meta = fm.planes().inner();
>>>>>>>
>>>>>>> I've tried a few approaches, e.g., checking that the member function's
>>>>>>> return type is the same as the type of the enclosing class (which is
>>>>>>> the case for member functions returning *this), but that then breaks
>>>>>>> Wdangling-reference4.C with std::optional<std::string>.
>>>>>>>
>>>>>>> Perhaps we want to look at the member function's enclosing class
>>>>>>> to see if it's a reference wrapper class (meaning, has a reference
>>>>>>> member and a constructor taking the same reference type) and don't
>>>>>>> warn if so, supposing that the member function returns a reference
>>>>>>> to a non-temporary object.
>>>>>>>
>>>>>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>>>>>
>>>>>>> 	PR c++/107532
>>>>>>>
>>>>>>> gcc/cp/ChangeLog:
>>>>>>>
>>>>>>> 	* call.cc (do_warn_dangling_reference): Don't warn when the
>>>>>>> 	member function comes from a reference wrapper class.
>>>>>>
>>>>>> Let's factor the new code out into e.g. reference_like_class_p
>>>>>
>>>>> Done.  Thanks,
>>>>>
>>>>> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
>>>>>
>>>>> -- >8 --
>>>>> Here, -Wdangling-reference triggers where it probably shouldn't, causing
>>>>> some grief.  The code in question uses a reference wrapper with a member
>>>>> function returning a reference to a subobject of a non-temporary object:
>>>>>
>>>>>      const Plane & meta = fm.planes().inner();
>>>>>
>>>>> I've tried a few approaches, e.g., checking that the member function's
>>>>> return type is the same as the type of the enclosing class (which is
>>>>> the case for member functions returning *this), but that then breaks
>>>>> Wdangling-reference4.C with std::optional<std::string>.
>>>>>
>>>>> Perhaps we want to look at the member function's enclosing class
>>>>> to see if it's a reference wrapper class (meaning, has a reference
>>>>> member and a constructor taking the same reference type, or is
>>>>> std::reference_wrapper or std::ranges::ref_view) and don't warn if so,
>>>>> supposing that the member function returns a reference to a non-temporary
>>>>> object.
>>>>>
>>>>> It's ugly, but better than asking users to add #pragmas into their code.
>>>>>
>>>>> 	PR c++/107532
>>>>>
>>>>> gcc/cp/ChangeLog:
>>>>>
>>>>> 	* call.cc (reference_like_class_p): New.
>>>>> 	(do_warn_dangling_reference): Don't warn when the member function comes
>>>>> 	from a reference_like_class_p.
>>>>>
>>>>> gcc/testsuite/ChangeLog:
>>>>>
>>>>> 	* g++.dg/warn/Wdangling-reference8.C: New test.
>>>>> 	* g++.dg/warn/Wdangling-reference9.C: New test.
>>>>> ---
>>>>>     gcc/cp/call.cc                                | 48 ++++++++++++
>>>>>     .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++++++
>>>>>     .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
>>>>>     3 files changed, 146 insertions(+)
>>>>>     create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>>>>>     create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
>>>>>
>>>>> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
>>>>> index 991730713e6..672722998ee 100644
>>>>> --- a/gcc/cp/call.cc
>>>>> +++ b/gcc/cp/call.cc
>>>>> @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
>>>>>       return true;
>>>>>     }
>>>>> +/* Return true if a class CTYPE is either std::reference_wrapper or
>>>>> +   std::ref_view, or a reference wrapper class.  We consider a class
>>>>> +   a reference wrapper class if it has a reference member and a
>>>>> +   constructor taking the same reference type.  */
>>>>> +
>>>>> +static bool
>>>>> +reference_like_class_p (tree ctype)
>>>>> +{
>>>>> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
>>>>> +  if (decl_in_std_namespace_p (tdecl))
>>>>> +    {
>>>>> +      tree name = DECL_NAME (tdecl);
>>>>> +      return (name
>>>>> +	      && (id_equal (name, "reference_wrapper")
>>>>> +		  || id_equal (name, "ref_view")));
>>>>> +    }
>>>>> +  for (tree fields = TYPE_FIELDS (ctype);
>>>>> +       fields;
>>>>> +       fields = DECL_CHAIN (fields))
>>>>> +    {
>>>>> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
>>>>> +	continue;
>>>>> +      tree type = TREE_TYPE (fields);
>>>>> +      if (!TYPE_REF_P (type))
>>>>> +	continue;
>>>>> +      /* OK, the field is a reference member.  Do we have a constructor
>>>>> +	 taking its type?  */
>>>>> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
>>>>> +	{
>>>>> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
>>>>> +	  if (args
>>>>> +	      && same_type_p (TREE_VALUE (args), type)
>>>>> +	      && TREE_CHAIN (args) == void_list_node)
>>>>> +	    return true;
>>>>> +	}
>>>>> +    }
>>>>> +  return false;
>>>>> +}
>>>>> +
>>>>>     /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>>>>>        that initializes the LHS (and at least one of its arguments represents
>>>>>        a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
>>>>> @@ -13832,6 +13871,15 @@ do_warn_dangling_reference (tree expr)
>>>>>     	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
>>>>>     	  return NULL_TREE;
>>>>> +	/* An attempt to reduce the number of -Wdangling-reference
>>>>> +	   false positives concerning reference wrappers (c++/107532).
>>>>> +	   Here we suppose that a member function of such a reference
>>>>> +	   wrapper class returns a reference to a non-temporary object.  */
>>>>> +	if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>>>>> +	    && !DECL_OVERLOADED_OPERATOR_P (fndecl)
>>>>> +	    && reference_like_class_p (CP_DECL_CONTEXT (fndecl)))
>>>>
>>>> Ah, in this case I was thinking rather than return we would want to look
>>>> through to the initializer of the reference wrapper, and warn if that's a
>>>> temporary, so we can catch the *2 cases in your tests.
>>>>
>>>> So, treating ref-like classes as much like references as we can.  Some of
>>>> your v1 patch ought to be useful in implementing this, but only looking
>>>> through one call at a time, not all of them like that patch.
>>>
>>> Maybe this one, then?  I still have to loop through the calls though; EXPR in
>>> do_warn_dangling_reference can be e.g.
>>>
>>> Ref<const Plane>::inner (&TARGET_EXPR <D.2839, FrameMetadata::planes ((const struct FrameMetadata *) fm)>)
>>>
>>> or
>>>
>>> Ref<const Plane>::inner (&TARGET_EXPR <D.2908, FrameMetadata::planes (&TARGET_EXPR <D.2898, {.p_={.bytesused=0}}>)>)
>>>
>>> and we want to warn only about the latter, but that means that I need to
>>> look into the nested call 'planes' to see if the initializer was a temporary.
>>
>> Right, but I was thinking we want to recurse like a few lines above, rather
>> than loop.
> 
> Ah yes, I can do that if I introduce a parameter that tells us
> if we're processing an argument or not.  I think I'm finally
> more or less satisfied with the patch, thanks.
> 
> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> 
> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> This patch adjusts do_warn_dangling_reference so that we look through
> reference wrapper classes (meaning, has a reference member and a
> constructor taking the same reference type, or is std::reference_wrapper
> or std::ranges::ref_view) and don't warn for them, supposing that the
> member function returns a reference to a non-temporary object.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (reference_like_class_p): New.
> 	(do_warn_dangling_reference): Add new bool parameter.  See through
> 	reference_like_class_p.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> 	* g++.dg/warn/Wdangling-reference9.C: New test.
> ---
>   gcc/cp/call.cc                                | 97 +++++++++++++++----
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++
>   .../g++.dg/warn/Wdangling-reference9.C        | 21 ++++
>   3 files changed, 178 insertions(+), 17 deletions(-)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index f7c5d9da94b..2a8edc2e7e2 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13777,6 +13777,45 @@ std_pair_ref_ref_p (tree t)
>     return true;
>   }
>   
> +/* Return true if a class CTYPE is either std::reference_wrapper or
> +   std::ref_view, or a reference wrapper class.  We consider a class
> +   a reference wrapper class if it has a reference member and a
> +   constructor taking the same reference type.  */
> +
> +static bool
> +reference_like_class_p (tree ctype)
> +{
> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> +  if (decl_in_std_namespace_p (tdecl))
> +    {
> +      tree name = DECL_NAME (tdecl);
> +      return (name
> +	      && (id_equal (name, "reference_wrapper")
> +		  || id_equal (name, "ref_view")));
> +    }
> +  for (tree fields = TYPE_FIELDS (ctype);
> +       fields;
> +       fields = DECL_CHAIN (fields))
> +    {
> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +	continue;
> +      tree type = TREE_TYPE (fields);
> +      if (!TYPE_REF_P (type))
> +	continue;
> +      /* OK, the field is a reference member.  Do we have a constructor
> +	 taking its type?  */
> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> +	{
> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +	  if (args
> +	      && same_type_p (TREE_VALUE (args), type)
> +	      && TREE_CHAIN (args) == void_list_node)
> +	    return true;
> +	}
> +    }
> +  return false;
> +}
> +
>   /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>      that initializes the LHS (and at least one of its arguments represents
>      a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> @@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
>        const int& y = (f(1), 42); // NULL_TREE
>        const int& z = f(f(1)); // f(f(1))
>   
> -   EXPR is the initializer.  */
> +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
> +   to a function; the point is to distinguish between, for example,
> +
> +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
> +
> +   where we shouldn't warn, and
> +
> +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
> +
> +   where we should warn (Ref is a reference_like_class_p so we see through
> +   it.  */
>   
>   static tree
> -do_warn_dangling_reference (tree expr)
> +do_warn_dangling_reference (tree expr, bool arg_p)
>   {
>     STRIP_NOPS (expr);
> +  if (TREE_CODE (expr) == ADDR_EXPR)
> +    expr = TREE_OPERAND (expr, 0);

I think if we move this here, we also need to check that expr before 
STRIP_NOPS had REFERENCE_TYPE.  OK with that change.

> +  if (arg_p && expr_represents_temporary_p (expr))
> +    {
> +      /* An attempt to reduce the number of -Wdangling-reference
> +	 false positives concerning reference wrappers (c++/107532).
> +	 Here we suppose that a member function of such a reference
> +	 wrapper class returns a reference to a non-temporary object.  */
> +      tree e = expr;
> +      while (handled_component_p (e))
> +	e = TREE_OPERAND (e, 0);
> +      e = TREE_TYPE (e);
> +      if (!CLASS_TYPE_P (e) || !reference_like_class_p (e))
> +	return expr;
> +    }
> +
>     switch (TREE_CODE (expr))
>       {
>       case CALL_EXPR:
> @@ -13829,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
>   	     std::pair<const int&, const int&> v = std::minmax(1, 2);
>   	   which also creates a dangling reference, because std::minmax
>   	   returns std::pair<const T&, const T&>(b, a).  */
> -	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> +	if (!arg_p
> +	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))
>   	  return NULL_TREE;
>   
>   	/* Here we're looking to see if any of the arguments is a temporary
> @@ -13842,14 +13909,10 @@ do_warn_dangling_reference (tree expr)
>   	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>   		&& !TYPE_REF_P (TREE_TYPE (arg)))
>   	      continue;
> -	    /* It could also be another call taking a temporary and returning
> -	       it and initializing this reference parameter.  */
> -	    if (do_warn_dangling_reference (arg))
> -	      return expr;
> -	    STRIP_NOPS (arg);
> -	    if (TREE_CODE (arg) == ADDR_EXPR)
> -	      arg = TREE_OPERAND (arg, 0);
> -	    if (expr_represents_temporary_p (arg))
> +	    /* Recurse to see if the argument is a temporary.  It could also
> +	       be another call taking a temporary and returning it and
> +	       initializing this reference parameter.  */
> +	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
>   	      return expr;
>   	  /* Don't warn about member function like:
>   	      std::any a(...);
> @@ -13866,15 +13929,15 @@ do_warn_dangling_reference (tree expr)
>   	return NULL_TREE;
>         }
>       case COMPOUND_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
>       case COND_EXPR:
> -      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
> +      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
>   	return t;
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
>       case PAREN_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
>       case TARGET_EXPR:
> -      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
> +      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
>       default:
>         return NULL_TREE;
>       }
> @@ -13917,7 +13980,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
>       = make_temp_override (global_dc->dc_warn_system_headers,
>   			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
>   			   || global_dc->dc_warn_system_headers));
> -  if (tree call = do_warn_dangling_reference (init))
> +  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
>       {
>         auto_diagnostic_group d;
>         if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..330de1fd05d
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> new file mode 100644
> index 00000000000..9ad83f7365e
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> @@ -0,0 +1,21 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +#include <functional>
> +
> +struct X { int n; };
> +
> +struct S {
> +  std::reference_wrapper<const X> wrapit() const { return x; }
> +  X x;
> +};
> +
> +void
> +g (const S& s)
> +{
> +  const auto& a1 = s.wrapit().get();
> +  (void) a1;
> +  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
> +  (void) a2;
> +}
> 
> base-commit: f661c0bb6371f355966a67b5ce71398e80792948


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v4] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-03-01 21:53                 ` Jason Merrill
@ 2023-03-02 21:24                   ` Marek Polacek
  2023-03-03 16:25                     ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-03-02 21:24 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Wed, Mar 01, 2023 at 04:53:23PM -0500, Jason Merrill wrote:
> > @@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
> >        const int& y = (f(1), 42); // NULL_TREE
> >        const int& z = f(f(1)); // f(f(1))
> > -   EXPR is the initializer.  */
> > +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
> > +   to a function; the point is to distinguish between, for example,
> > +
> > +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
> > +
> > +   where we shouldn't warn, and
> > +
> > +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
> > +
> > +   where we should warn (Ref is a reference_like_class_p so we see through
> > +   it.  */
> >   static tree
> > -do_warn_dangling_reference (tree expr)
> > +do_warn_dangling_reference (tree expr, bool arg_p)
> >   {
> >     STRIP_NOPS (expr);
> > +  if (TREE_CODE (expr) == ADDR_EXPR)
> > +    expr = TREE_OPERAND (expr, 0);
> 
> I think if we move this here, we also need to check that expr before
> STRIP_NOPS had REFERENCE_TYPE.  OK with that change.

Sorry but I don't think I can do that.  There can be CONVERT_EXPRs
that need to be stripped, whether arg_p or !arg_p.  For example, we can get
(const int *) f ((const int &) &TARGET_EXPR <D.2765, NON_LVALUE_EXPR <10>>)
for
const int& r5 = (42, f(10));

Is the patch OK as-is then?

Marek


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v4] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-03-02 21:24                   ` Marek Polacek
@ 2023-03-03 16:25                     ` Jason Merrill
  2023-03-03 17:50                       ` [PATCH v5] " Marek Polacek
  0 siblings, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-03-03 16:25 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 3/2/23 16:24, Marek Polacek wrote:
> On Wed, Mar 01, 2023 at 04:53:23PM -0500, Jason Merrill wrote:
>>> @@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
>>>         const int& y = (f(1), 42); // NULL_TREE
>>>         const int& z = f(f(1)); // f(f(1))
>>> -   EXPR is the initializer.  */
>>> +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
>>> +   to a function; the point is to distinguish between, for example,
>>> +
>>> +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
>>> +
>>> +   where we shouldn't warn, and
>>> +
>>> +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
>>> +
>>> +   where we should warn (Ref is a reference_like_class_p so we see through
>>> +   it.  */
>>>    static tree
>>> -do_warn_dangling_reference (tree expr)
>>> +do_warn_dangling_reference (tree expr, bool arg_p)
>>>    {
>>>      STRIP_NOPS (expr);
>>> +  if (TREE_CODE (expr) == ADDR_EXPR)
>>> +    expr = TREE_OPERAND (expr, 0);
>>
>> I think if we move this here, we also need to check that expr before
>> STRIP_NOPS had REFERENCE_TYPE.  OK with that change.
> 
> Sorry but I don't think I can do that.  There can be CONVERT_EXPRs
> that need to be stripped, whether arg_p or !arg_p.  For example, we can get
> (const int *) f ((const int &) &TARGET_EXPR <D.2765, NON_LVALUE_EXPR <10>>)
> for
> const int& r5 = (42, f(10));

I meant that we only want to strip ADDR_EXPR if 'expr' at the start of 
the function had REFERENCE_TYPE, corresponding to

>             /* Check that this argument initializes a reference, except for                                                         
>                the argument initializing the object of a member function.  */
>             if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>                 && !TYPE_REF_P (TREE_TYPE (arg)))
>               continue;

above the code for stripping an ADDR_EXPR from an argument that your 
patch removes.

If the original expr is a pointer rather than a reference, we don't want 
to complain about it pointing to a temporary.

Jason


^ permalink raw reply	[flat|nested] 17+ messages in thread

* [PATCH v5] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-03-03 16:25                     ` Jason Merrill
@ 2023-03-03 17:50                       ` Marek Polacek
  2023-03-04  2:30                         ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-03-03 17:50 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Fri, Mar 03, 2023 at 11:25:06AM -0500, Jason Merrill wrote:
> On 3/2/23 16:24, Marek Polacek wrote:
> > On Wed, Mar 01, 2023 at 04:53:23PM -0500, Jason Merrill wrote:
> > > > @@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
> > > >         const int& y = (f(1), 42); // NULL_TREE
> > > >         const int& z = f(f(1)); // f(f(1))
> > > > -   EXPR is the initializer.  */
> > > > +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
> > > > +   to a function; the point is to distinguish between, for example,
> > > > +
> > > > +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
> > > > +
> > > > +   where we shouldn't warn, and
> > > > +
> > > > +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
> > > > +
> > > > +   where we should warn (Ref is a reference_like_class_p so we see through
> > > > +   it.  */
> > > >    static tree
> > > > -do_warn_dangling_reference (tree expr)
> > > > +do_warn_dangling_reference (tree expr, bool arg_p)
> > > >    {
> > > >      STRIP_NOPS (expr);
> > > > +  if (TREE_CODE (expr) == ADDR_EXPR)
> > > > +    expr = TREE_OPERAND (expr, 0);
> > > 
> > > I think if we move this here, we also need to check that expr before
> > > STRIP_NOPS had REFERENCE_TYPE.  OK with that change.
> > 
> > Sorry but I don't think I can do that.  There can be CONVERT_EXPRs
> > that need to be stripped, whether arg_p or !arg_p.  For example, we can get
> > (const int *) f ((const int &) &TARGET_EXPR <D.2765, NON_LVALUE_EXPR <10>>)
> > for
> > const int& r5 = (42, f(10));
> 
> I meant that we only want to strip ADDR_EXPR if 'expr' at the start of the
> function had REFERENCE_TYPE, corresponding to
> 
> >             /* Check that this argument initializes a reference, except
> > for
> > the argument initializing the object of a member function.  */
> >             if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
> >                 && !TYPE_REF_P (TREE_TYPE (arg)))
> >               continue;
> 
> above the code for stripping an ADDR_EXPR from an argument that your patch
> removes.

I see.

> If the original expr is a pointer rather than a reference, we don't want to
> complain about it pointing to a temporary.

Ug, I can't make it work.  When we recurse, I can no longer check
fndecl.  How about just moving the stripping back where it was?

-- >8 --
Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

This patch adjusts do_warn_dangling_reference so that we look through
reference wrapper classes (meaning, has a reference member and a
constructor taking the same reference type, or is std::reference_wrapper
or std::ranges::ref_view) and don't warn for them, supposing that the
member function returns a reference to a non-temporary object.

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (reference_like_class_p): New.
	(do_warn_dangling_reference): Add new bool parameter.  See through
	reference_like_class_p.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
	* g++.dg/warn/Wdangling-reference9.C: New test.
---
 gcc/cp/call.cc                                | 92 ++++++++++++++++---
 .../g++.dg/warn/Wdangling-reference8.C        | 77 ++++++++++++++++
 .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
 3 files changed, 176 insertions(+), 14 deletions(-)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index 048b2b052f8..62536573633 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13779,6 +13779,45 @@ std_pair_ref_ref_p (tree t)
   return true;
 }
 
+/* Return true if a class CTYPE is either std::reference_wrapper or
+   std::ref_view, or a reference wrapper class.  We consider a class
+   a reference wrapper class if it has a reference member and a
+   constructor taking the same reference type.  */
+
+static bool
+reference_like_class_p (tree ctype)
+{
+  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
+  if (decl_in_std_namespace_p (tdecl))
+    {
+      tree name = DECL_NAME (tdecl);
+      return (name
+	      && (id_equal (name, "reference_wrapper")
+		  || id_equal (name, "ref_view")));
+    }
+  for (tree fields = TYPE_FIELDS (ctype);
+       fields;
+       fields = DECL_CHAIN (fields))
+    {
+      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
+	continue;
+      tree type = TREE_TYPE (fields);
+      if (!TYPE_REF_P (type))
+	continue;
+      /* OK, the field is a reference member.  Do we have a constructor
+	 taking its type?  */
+      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
+	{
+	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
+	  if (args
+	      && same_type_p (TREE_VALUE (args), type)
+	      && TREE_CHAIN (args) == void_list_node)
+	    return true;
+	}
+    }
+  return false;
+}
+
 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
    that initializes the LHS (and at least one of its arguments represents
    a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
@@ -13793,12 +13832,37 @@ std_pair_ref_ref_p (tree t)
      const int& y = (f(1), 42); // NULL_TREE
      const int& z = f(f(1)); // f(f(1))
 
-   EXPR is the initializer.  */
+   EXPR is the initializer.  If ARG_P is true, we're processing an argument
+   to a function; the point is to distinguish between, for example,
+
+     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
+
+   where we shouldn't warn, and
+
+     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
+
+   where we should warn (Ref is a reference_like_class_p so we see through
+   it.  */
 
 static tree
-do_warn_dangling_reference (tree expr)
+do_warn_dangling_reference (tree expr, bool arg_p)
 {
   STRIP_NOPS (expr);
+
+  if (arg_p && expr_represents_temporary_p (expr))
+    {
+      /* An attempt to reduce the number of -Wdangling-reference
+	 false positives concerning reference wrappers (c++/107532).
+	 Here we suppose that a member function of such a reference
+	 wrapper class returns a reference to a non-temporary object.  */
+      tree e = expr;
+      while (handled_component_p (e))
+	e = TREE_OPERAND (e, 0);
+      e = TREE_TYPE (e);
+      if (!CLASS_TYPE_P (e) || !reference_like_class_p (e))
+	return expr;
+    }
+
   switch (TREE_CODE (expr))
     {
     case CALL_EXPR:
@@ -13831,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
 	     std::pair<const int&, const int&> v = std::minmax(1, 2);
 	   which also creates a dangling reference, because std::minmax
 	   returns std::pair<const T&, const T&>(b, a).  */
-	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
+	if (!arg_p
+	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))
 	  return NULL_TREE;
 
 	/* Here we're looking to see if any of the arguments is a temporary
@@ -13844,14 +13909,13 @@ do_warn_dangling_reference (tree expr)
 	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
 		&& !TYPE_REF_P (TREE_TYPE (arg)))
 	      continue;
-	    /* It could also be another call taking a temporary and returning
-	       it and initializing this reference parameter.  */
-	    if (do_warn_dangling_reference (arg))
-	      return expr;
 	    STRIP_NOPS (arg);
 	    if (TREE_CODE (arg) == ADDR_EXPR)
 	      arg = TREE_OPERAND (arg, 0);
-	    if (expr_represents_temporary_p (arg))
+	    /* Recurse to see if the argument is a temporary.  It could also
+	       be another call taking a temporary and returning it and
+	       initializing this reference parameter.  */
+	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
 	      return expr;
 	  /* Don't warn about member function like:
 	      std::any a(...);
@@ -13868,15 +13932,15 @@ do_warn_dangling_reference (tree expr)
 	return NULL_TREE;
       }
     case COMPOUND_EXPR:
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
     case COND_EXPR:
-      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
+      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
 	return t;
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
     case PAREN_EXPR:
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
     case TARGET_EXPR:
-      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
+      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
     default:
       return NULL_TREE;
     }
@@ -13919,7 +13983,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
     = make_temp_override (global_dc->dc_warn_system_headers,
 			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
 			   || global_dc->dc_warn_system_headers));
-  if (tree call = do_warn_dangling_reference (init))
+  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
     {
       auto_diagnostic_group d;
       if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..330de1fd05d
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner();
+  (void) d8;
+}
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
new file mode 100644
index 00000000000..9ad83f7365e
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
@@ -0,0 +1,21 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+#include <functional>
+
+struct X { int n; };
+
+struct S {
+  std::reference_wrapper<const X> wrapit() const { return x; }
+  X x;
+};
+
+void
+g (const S& s)
+{
+  const auto& a1 = s.wrapit().get();
+  (void) a1;
+  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
+  (void) a2;
+}

base-commit: ce1c99f1ccd7b1229a4f8531d6b6de6cf571a9ef
-- 
2.39.2


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v5] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-03-03 17:50                       ` [PATCH v5] " Marek Polacek
@ 2023-03-04  2:30                         ` Jason Merrill
  2023-03-06 21:54                           ` [PATCH v6] " Marek Polacek
  0 siblings, 1 reply; 17+ messages in thread
From: Jason Merrill @ 2023-03-04  2:30 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 3/3/23 12:50, Marek Polacek wrote:
> On Fri, Mar 03, 2023 at 11:25:06AM -0500, Jason Merrill wrote:
>> On 3/2/23 16:24, Marek Polacek wrote:
>>> On Wed, Mar 01, 2023 at 04:53:23PM -0500, Jason Merrill wrote:
>>>>> @@ -13791,12 +13830,39 @@ std_pair_ref_ref_p (tree t)
>>>>>          const int& y = (f(1), 42); // NULL_TREE
>>>>>          const int& z = f(f(1)); // f(f(1))
>>>>> -   EXPR is the initializer.  */
>>>>> +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
>>>>> +   to a function; the point is to distinguish between, for example,
>>>>> +
>>>>> +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
>>>>> +
>>>>> +   where we shouldn't warn, and
>>>>> +
>>>>> +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
>>>>> +
>>>>> +   where we should warn (Ref is a reference_like_class_p so we see through
>>>>> +   it.  */
>>>>>     static tree
>>>>> -do_warn_dangling_reference (tree expr)
>>>>> +do_warn_dangling_reference (tree expr, bool arg_p)
>>>>>     {
>>>>>       STRIP_NOPS (expr);
>>>>> +  if (TREE_CODE (expr) == ADDR_EXPR)
>>>>> +    expr = TREE_OPERAND (expr, 0);
>>>>
>>>> I think if we move this here, we also need to check that expr before
>>>> STRIP_NOPS had REFERENCE_TYPE.  OK with that change.
>>>
>>> Sorry but I don't think I can do that.  There can be CONVERT_EXPRs
>>> that need to be stripped, whether arg_p or !arg_p.  For example, we can get
>>> (const int *) f ((const int &) &TARGET_EXPR <D.2765, NON_LVALUE_EXPR <10>>)
>>> for
>>> const int& r5 = (42, f(10));
>>
>> I meant that we only want to strip ADDR_EXPR if 'expr' at the start of the
>> function had REFERENCE_TYPE, corresponding to
>>
>>>              /* Check that this argument initializes a reference, except
>>> for
>>> the argument initializing the object of a member function.  */
>>>              if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>>>                  && !TYPE_REF_P (TREE_TYPE (arg)))
>>>                continue;
>>
>> above the code for stripping an ADDR_EXPR from an argument that your patch
>> removes.
> 
> I see.
> 
>> If the original expr is a pointer rather than a reference, we don't want to
>> complain about it pointing to a temporary.
> 
> Ug, I can't make it work.  When we recurse, I can no longer check
> fndecl.  How about just moving the stripping back where it was?

Sure.

> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> This patch adjusts do_warn_dangling_reference so that we look through
> reference wrapper classes (meaning, has a reference member and a
> constructor taking the same reference type, or is std::reference_wrapper
> or std::ranges::ref_view) and don't warn for them, supposing that the
> member function returns a reference to a non-temporary object.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (reference_like_class_p): New.
> 	(do_warn_dangling_reference): Add new bool parameter.  See through
> 	reference_like_class_p.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> 	* g++.dg/warn/Wdangling-reference9.C: New test.
> ---
>   gcc/cp/call.cc                                | 92 ++++++++++++++++---
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 ++++++++++++++++
>   .../g++.dg/warn/Wdangling-reference9.C        | 21 +++++
>   3 files changed, 176 insertions(+), 14 deletions(-)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index 048b2b052f8..62536573633 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13779,6 +13779,45 @@ std_pair_ref_ref_p (tree t)
>     return true;
>   }
>   
> +/* Return true if a class CTYPE is either std::reference_wrapper or
> +   std::ref_view, or a reference wrapper class.  We consider a class
> +   a reference wrapper class if it has a reference member and a
> +   constructor taking the same reference type.  */
> +
> +static bool
> +reference_like_class_p (tree ctype)
> +{
> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> +  if (decl_in_std_namespace_p (tdecl))
> +    {
> +      tree name = DECL_NAME (tdecl);
> +      return (name
> +	      && (id_equal (name, "reference_wrapper")
> +		  || id_equal (name, "ref_view")));
> +    }
> +  for (tree fields = TYPE_FIELDS (ctype);
> +       fields;
> +       fields = DECL_CHAIN (fields))
> +    {
> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +	continue;
> +      tree type = TREE_TYPE (fields);
> +      if (!TYPE_REF_P (type))
> +	continue;
> +      /* OK, the field is a reference member.  Do we have a constructor
> +	 taking its type?  */
> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> +	{
> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +	  if (args
> +	      && same_type_p (TREE_VALUE (args), type)
> +	      && TREE_CHAIN (args) == void_list_node)
> +	    return true;
> +	}
> +    }
> +  return false;
> +}
> +
>   /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>      that initializes the LHS (and at least one of its arguments represents
>      a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> @@ -13793,12 +13832,37 @@ std_pair_ref_ref_p (tree t)
>        const int& y = (f(1), 42); // NULL_TREE
>        const int& z = f(f(1)); // f(f(1))
>   
> -   EXPR is the initializer.  */
> +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
> +   to a function; the point is to distinguish between, for example,
> +
> +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
> +
> +   where we shouldn't warn, and
> +
> +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
> +
> +   where we should warn (Ref is a reference_like_class_p so we see through
> +   it.  */
>   
>   static tree
> -do_warn_dangling_reference (tree expr)
> +do_warn_dangling_reference (tree expr, bool arg_p)
>   {
>     STRIP_NOPS (expr);
> +
> +  if (arg_p && expr_represents_temporary_p (expr))
> +    {
> +      /* An attempt to reduce the number of -Wdangling-reference
> +	 false positives concerning reference wrappers (c++/107532).
> +	 Here we suppose that a member function of such a reference
> +	 wrapper class returns a reference to a non-temporary object.  */
> +      tree e = expr;
> +      while (handled_component_p (e))
> +	e = TREE_OPERAND (e, 0);
> +      e = TREE_TYPE (e);
> +      if (!CLASS_TYPE_P (e) || !reference_like_class_p (e))
> +	return expr;
> +    }
> +
>     switch (TREE_CODE (expr))
>       {
>       case CALL_EXPR:
> @@ -13831,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
>   	     std::pair<const int&, const int&> v = std::minmax(1, 2);
>   	   which also creates a dangling reference, because std::minmax
>   	   returns std::pair<const T&, const T&>(b, a).  */
> -	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> +	if (!arg_p
> +	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))

Instead of checking !arg_p maybe the std_pair_ref_ref_p call should 
change to reference_like_class_p (which in turn should check 
std_pair_ref_ref_p)?

>   	  return NULL_TREE;
>   
>   	/* Here we're looking to see if any of the arguments is a temporary
> @@ -13844,14 +13909,13 @@ do_warn_dangling_reference (tree expr)
>   	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>   		&& !TYPE_REF_P (TREE_TYPE (arg)))
>   	      continue;
> -	    /* It could also be another call taking a temporary and returning
> -	       it and initializing this reference parameter.  */
> -	    if (do_warn_dangling_reference (arg))
> -	      return expr;
>   	    STRIP_NOPS (arg);
>   	    if (TREE_CODE (arg) == ADDR_EXPR)
>   	      arg = TREE_OPERAND (arg, 0);
> -	    if (expr_represents_temporary_p (arg))
> +	    /* Recurse to see if the argument is a temporary.  It could also
> +	       be another call taking a temporary and returning it and
> +	       initializing this reference parameter.  */
> +	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
>   	      return expr;
>   	  /* Don't warn about member function like:
>   	      std::any a(...);
> @@ -13868,15 +13932,15 @@ do_warn_dangling_reference (tree expr)
>   	return NULL_TREE;
>         }
>       case COMPOUND_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
>       case COND_EXPR:
> -      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
> +      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
>   	return t;
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
>       case PAREN_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
>       case TARGET_EXPR:
> -      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
> +      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
>       default:
>         return NULL_TREE;
>       }
> @@ -13919,7 +13983,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
>       = make_temp_override (global_dc->dc_warn_system_headers,
>   			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
>   			   || global_dc->dc_warn_system_headers));
> -  if (tree call = do_warn_dangling_reference (init))
> +  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
>       {
>         auto_diagnostic_group d;
>         if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..330de1fd05d
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> new file mode 100644
> index 00000000000..9ad83f7365e
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> @@ -0,0 +1,21 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +#include <functional>
> +
> +struct X { int n; };
> +
> +struct S {
> +  std::reference_wrapper<const X> wrapit() const { return x; }
> +  X x;
> +};
> +
> +void
> +g (const S& s)
> +{
> +  const auto& a1 = s.wrapit().get();
> +  (void) a1;
> +  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
> +  (void) a2;
> +}
> 
> base-commit: ce1c99f1ccd7b1229a4f8531d6b6de6cf571a9ef


^ permalink raw reply	[flat|nested] 17+ messages in thread

* [PATCH v6] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-03-04  2:30                         ` Jason Merrill
@ 2023-03-06 21:54                           ` Marek Polacek
  2023-03-07 14:37                             ` Jason Merrill
  0 siblings, 1 reply; 17+ messages in thread
From: Marek Polacek @ 2023-03-06 21:54 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

On Fri, Mar 03, 2023 at 09:30:38PM -0500, Jason Merrill wrote:
> On 3/3/23 12:50, Marek Polacek wrote:
> >     switch (TREE_CODE (expr))
> >       {
> >       case CALL_EXPR:
> > @@ -13831,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
> >   	     std::pair<const int&, const int&> v = std::minmax(1, 2);
> >   	   which also creates a dangling reference, because std::minmax
> >   	   returns std::pair<const T&, const T&>(b, a).  */
> > -	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> > +	if (!arg_p
> > +	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))
> 
> Instead of checking !arg_p maybe the std_pair_ref_ref_p call should change
> to reference_like_class_p (which in turn should check std_pair_ref_ref_p)?

Could do.  I suppose the logic is that for std::pair<const int&, const int&>
arguments we want to see through it to get at its arguments.

Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?

-- >8 --
Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

This patch adjusts do_warn_dangling_reference so that we look through
reference wrapper classes (meaning, has a reference member and a
constructor taking the same reference type, or is std::reference_wrapper
or std::ranges::ref_view) and don't warn for them, supposing that the
member function returns a reference to a non-temporary object.

	PR c++/107532

gcc/cp/ChangeLog:

	* call.cc (reference_like_class_p): New.
	(do_warn_dangling_reference): Add new bool parameter.  See through
	reference_like_class_p.

gcc/testsuite/ChangeLog:

	* g++.dg/warn/Wdangling-reference8.C: New test.
	* g++.dg/warn/Wdangling-reference9.C: New test.
---
 gcc/cp/call.cc                                | 97 ++++++++++++++++---
 .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++
 .../g++.dg/warn/Wdangling-reference9.C        | 21 ++++
 3 files changed, 181 insertions(+), 14 deletions(-)
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
 create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C

diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index 048b2b052f8..a43980b6e15 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13779,6 +13779,52 @@ std_pair_ref_ref_p (tree t)
   return true;
 }
 
+/* Return true if a class CTYPE is either std::reference_wrapper or
+   std::ref_view, or a reference wrapper class.  We consider a class
+   a reference wrapper class if it has a reference member and a
+   constructor taking the same reference type.  */
+
+static bool
+reference_like_class_p (tree ctype)
+{
+  if (!CLASS_TYPE_P (ctype))
+    return false;
+
+  /* Also accept a std::pair<const T&, const T&>.  */
+  if (std_pair_ref_ref_p (ctype))
+    return true;
+
+  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
+  if (decl_in_std_namespace_p (tdecl))
+    {
+      tree name = DECL_NAME (tdecl);
+      return (name
+	      && (id_equal (name, "reference_wrapper")
+		  || id_equal (name, "ref_view")));
+    }
+  for (tree fields = TYPE_FIELDS (ctype);
+       fields;
+       fields = DECL_CHAIN (fields))
+    {
+      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
+	continue;
+      tree type = TREE_TYPE (fields);
+      if (!TYPE_REF_P (type))
+	continue;
+      /* OK, the field is a reference member.  Do we have a constructor
+	 taking its type?  */
+      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
+	{
+	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
+	  if (args
+	      && same_type_p (TREE_VALUE (args), type)
+	      && TREE_CHAIN (args) == void_list_node)
+	    return true;
+	}
+    }
+  return false;
+}
+
 /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
    that initializes the LHS (and at least one of its arguments represents
    a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
@@ -13793,12 +13839,36 @@ std_pair_ref_ref_p (tree t)
      const int& y = (f(1), 42); // NULL_TREE
      const int& z = f(f(1)); // f(f(1))
 
-   EXPR is the initializer.  */
+   EXPR is the initializer.  If ARG_P is true, we're processing an argument
+   to a function; the point is to distinguish between, for example,
+
+     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
+
+   where we shouldn't warn, and
+
+     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
+
+   where we should warn (Ref is a reference_like_class_p so we see through
+   it.  */
 
 static tree
-do_warn_dangling_reference (tree expr)
+do_warn_dangling_reference (tree expr, bool arg_p)
 {
   STRIP_NOPS (expr);
+
+  if (arg_p && expr_represents_temporary_p (expr))
+    {
+      /* An attempt to reduce the number of -Wdangling-reference
+	 false positives concerning reference wrappers (c++/107532).
+	 Here we suppose that a member function of such a reference
+	 wrapper class returns a reference to a non-temporary object.  */
+      tree e = expr;
+      while (handled_component_p (e))
+	e = TREE_OPERAND (e, 0);
+      if (!reference_like_class_p (TREE_TYPE (e)))
+	return expr;
+    }
+
   switch (TREE_CODE (expr))
     {
     case CALL_EXPR:
@@ -13831,7 +13901,7 @@ do_warn_dangling_reference (tree expr)
 	     std::pair<const int&, const int&> v = std::minmax(1, 2);
 	   which also creates a dangling reference, because std::minmax
 	   returns std::pair<const T&, const T&>(b, a).  */
-	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
+	if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
 	  return NULL_TREE;
 
 	/* Here we're looking to see if any of the arguments is a temporary
@@ -13844,14 +13914,13 @@ do_warn_dangling_reference (tree expr)
 	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
 		&& !TYPE_REF_P (TREE_TYPE (arg)))
 	      continue;
-	    /* It could also be another call taking a temporary and returning
-	       it and initializing this reference parameter.  */
-	    if (do_warn_dangling_reference (arg))
-	      return expr;
 	    STRIP_NOPS (arg);
 	    if (TREE_CODE (arg) == ADDR_EXPR)
 	      arg = TREE_OPERAND (arg, 0);
-	    if (expr_represents_temporary_p (arg))
+	    /* Recurse to see if the argument is a temporary.  It could also
+	       be another call taking a temporary and returning it and
+	       initializing this reference parameter.  */
+	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
 	      return expr;
 	  /* Don't warn about member function like:
 	      std::any a(...);
@@ -13868,15 +13937,15 @@ do_warn_dangling_reference (tree expr)
 	return NULL_TREE;
       }
     case COMPOUND_EXPR:
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
     case COND_EXPR:
-      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
+      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
 	return t;
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
     case PAREN_EXPR:
-      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
+      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
     case TARGET_EXPR:
-      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
+      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
     default:
       return NULL_TREE;
     }
@@ -13919,7 +13988,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
     = make_temp_override (global_dc->dc_warn_system_headers,
 			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
 			   || global_dc->dc_warn_system_headers));
-  if (tree call = do_warn_dangling_reference (init))
+  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
     {
       auto_diagnostic_group d;
       if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
new file mode 100644
index 00000000000..330de1fd05d
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
@@ -0,0 +1,77 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+struct Plane { unsigned int bytesused; };
+
+// Passes a reference through. Does not change lifetime.
+template <typename T>
+struct Ref {
+    const T& i_;
+    Ref(const T & i) : i_(i) {}
+    const T & inner();
+};
+
+struct FrameMetadata {
+    Ref<const Plane> planes() const { return p_; }
+
+    Plane p_;
+};
+
+void bar(const Plane & meta);
+void foo(const FrameMetadata & fm)
+{
+    const Plane & meta = fm.planes().inner();
+    bar(meta);
+    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
+    bar(meta2);
+}
+
+struct S {
+  const S& self () { return *this; }
+} s;
+
+const S& r1 = s.self();
+const S& r2 = S().self(); // { dg-warning "dangling reference" }
+
+struct D {
+};
+
+struct C {
+  D d;
+  Ref<const D> get() const { return d; }
+};
+
+struct B {
+  C c;
+  const C& get() const { return c; }
+  B();
+};
+
+struct A {
+  B b;
+  const B& get() const { return b; }
+};
+
+void
+g (const A& a)
+{
+  const auto& d1 = a.get().get().get().inner();
+  (void) d1;
+  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d2;
+  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
+  (void) d3;
+  const auto& d4 = a.b.get().get().inner();
+  (void) d4;
+  const auto& d5 = a.b.c.get().inner();
+  (void) d5;
+  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
+  (void) d6;
+  Plane p;
+  Ref<Plane> r(p);
+  const auto& d7 = r.inner();
+  (void) d7;
+  const auto& d8 = Ref<Plane>(p).inner();
+  (void) d8;
+}
diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
new file mode 100644
index 00000000000..9ad83f7365e
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
@@ -0,0 +1,21 @@
+// PR c++/107532
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wdangling-reference" }
+
+#include <functional>
+
+struct X { int n; };
+
+struct S {
+  std::reference_wrapper<const X> wrapit() const { return x; }
+  X x;
+};
+
+void
+g (const S& s)
+{
+  const auto& a1 = s.wrapit().get();
+  (void) a1;
+  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
+  (void) a2;
+}

base-commit: 553ff2524f412be4e02e2ffb1a0a3dc3e2280742
-- 
2.39.2


^ permalink raw reply	[flat|nested] 17+ messages in thread

* Re: [PATCH v6] c++: -Wdangling-reference with reference wrapper [PR107532]
  2023-03-06 21:54                           ` [PATCH v6] " Marek Polacek
@ 2023-03-07 14:37                             ` Jason Merrill
  0 siblings, 0 replies; 17+ messages in thread
From: Jason Merrill @ 2023-03-07 14:37 UTC (permalink / raw)
  To: Marek Polacek; +Cc: GCC Patches

On 3/6/23 16:54, Marek Polacek wrote:
> On Fri, Mar 03, 2023 at 09:30:38PM -0500, Jason Merrill wrote:
>> On 3/3/23 12:50, Marek Polacek wrote:
>>>      switch (TREE_CODE (expr))
>>>        {
>>>        case CALL_EXPR:
>>> @@ -13831,7 +13895,8 @@ do_warn_dangling_reference (tree expr)
>>>    	     std::pair<const int&, const int&> v = std::minmax(1, 2);
>>>    	   which also creates a dangling reference, because std::minmax
>>>    	   returns std::pair<const T&, const T&>(b, a).  */
>>> -	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
>>> +	if (!arg_p
>>> +	    && (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype))))
>>
>> Instead of checking !arg_p maybe the std_pair_ref_ref_p call should change
>> to reference_like_class_p (which in turn should check std_pair_ref_ref_p)?
> 
> Could do.  I suppose the logic is that for std::pair<const int&, const int&>
> arguments we want to see through it to get at its arguments.
> 
> Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk?
> 
> -- >8 --
> Here, -Wdangling-reference triggers where it probably shouldn't, causing
> some grief.  The code in question uses a reference wrapper with a member
> function returning a reference to a subobject of a non-temporary object:
> 
>    const Plane & meta = fm.planes().inner();
> 
> I've tried a few approaches, e.g., checking that the member function's
> return type is the same as the type of the enclosing class (which is
> the case for member functions returning *this), but that then breaks
> Wdangling-reference4.C with std::optional<std::string>.
> 
> This patch adjusts do_warn_dangling_reference so that we look through
> reference wrapper classes (meaning, has a reference member and a
> constructor taking the same reference type, or is std::reference_wrapper
> or std::ranges::ref_view) and don't warn for them, supposing that the
> member function returns a reference to a non-temporary object.
> 
> 	PR c++/107532
> 
> gcc/cp/ChangeLog:
> 
> 	* call.cc (reference_like_class_p): New.
> 	(do_warn_dangling_reference): Add new bool parameter.  See through
> 	reference_like_class_p.
> 
> gcc/testsuite/ChangeLog:
> 
> 	* g++.dg/warn/Wdangling-reference8.C: New test.
> 	* g++.dg/warn/Wdangling-reference9.C: New test.
> ---
>   gcc/cp/call.cc                                | 97 ++++++++++++++++---
>   .../g++.dg/warn/Wdangling-reference8.C        | 77 +++++++++++++++
>   .../g++.dg/warn/Wdangling-reference9.C        | 21 ++++
>   3 files changed, 181 insertions(+), 14 deletions(-)
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
>   create mode 100644 gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> 
> diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
> index 048b2b052f8..a43980b6e15 100644
> --- a/gcc/cp/call.cc
> +++ b/gcc/cp/call.cc
> @@ -13779,6 +13779,52 @@ std_pair_ref_ref_p (tree t)
>     return true;
>   }
>   
> +/* Return true if a class CTYPE is either std::reference_wrapper or
> +   std::ref_view, or a reference wrapper class.  We consider a class
> +   a reference wrapper class if it has a reference member and a
> +   constructor taking the same reference type.  */
> +
> +static bool
> +reference_like_class_p (tree ctype)
> +{
> +  if (!CLASS_TYPE_P (ctype))
> +    return false;
> +
> +  /* Also accept a std::pair<const T&, const T&>.  */
> +  if (std_pair_ref_ref_p (ctype))
> +    return true;
> +
> +  tree tdecl = TYPE_NAME (TYPE_MAIN_VARIANT (ctype));
> +  if (decl_in_std_namespace_p (tdecl))
> +    {
> +      tree name = DECL_NAME (tdecl);
> +      return (name
> +	      && (id_equal (name, "reference_wrapper")
> +		  || id_equal (name, "ref_view")));
> +    }
> +  for (tree fields = TYPE_FIELDS (ctype);
> +       fields;
> +       fields = DECL_CHAIN (fields))
> +    {
> +      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
> +	continue;
> +      tree type = TREE_TYPE (fields);
> +      if (!TYPE_REF_P (type))
> +	continue;
> +      /* OK, the field is a reference member.  Do we have a constructor
> +	 taking its type?  */
> +      for (tree fn : ovl_range (CLASSTYPE_CONSTRUCTORS (ctype)))
> +	{
> +	  tree args = FUNCTION_FIRST_USER_PARMTYPE (fn);
> +	  if (args
> +	      && same_type_p (TREE_VALUE (args), type)
> +	      && TREE_CHAIN (args) == void_list_node)
> +	    return true;
> +	}
> +    }
> +  return false;
> +}
> +
>   /* Helper for maybe_warn_dangling_reference to find a problematic CALL_EXPR
>      that initializes the LHS (and at least one of its arguments represents
>      a temporary, as outlined in maybe_warn_dangling_reference), or NULL_TREE
> @@ -13793,12 +13839,36 @@ std_pair_ref_ref_p (tree t)
>        const int& y = (f(1), 42); // NULL_TREE
>        const int& z = f(f(1)); // f(f(1))
>   
> -   EXPR is the initializer.  */
> +   EXPR is the initializer.  If ARG_P is true, we're processing an argument
> +   to a function; the point is to distinguish between, for example,
> +
> +     Ref::inner (&TARGET_EXPR <D.2839, F::foo (fm)>)
> +
> +   where we shouldn't warn, and
> +
> +     Ref::inner (&TARGET_EXPR <D.2908, F::foo (&TARGET_EXPR <...>)>)
> +
> +   where we should warn (Ref is a reference_like_class_p so we see through
> +   it.  */
>   
>   static tree
> -do_warn_dangling_reference (tree expr)
> +do_warn_dangling_reference (tree expr, bool arg_p)
>   {
>     STRIP_NOPS (expr);
> +
> +  if (arg_p && expr_represents_temporary_p (expr))
> +    {
> +      /* An attempt to reduce the number of -Wdangling-reference
> +	 false positives concerning reference wrappers (c++/107532).
> +	 Here we suppose that a member function of such a reference
> +	 wrapper class returns a reference to a non-temporary object.  */

This comment needs updating, I think; OK with that change.

> +      tree e = expr;
> +      while (handled_component_p (e))
> +	e = TREE_OPERAND (e, 0);
> +      if (!reference_like_class_p (TREE_TYPE (e)))
> +	return expr;
> +    }
> +
>     switch (TREE_CODE (expr))
>       {
>       case CALL_EXPR:
> @@ -13831,7 +13901,7 @@ do_warn_dangling_reference (tree expr)
>   	     std::pair<const int&, const int&> v = std::minmax(1, 2);
>   	   which also creates a dangling reference, because std::minmax
>   	   returns std::pair<const T&, const T&>(b, a).  */
> -	if (!(TYPE_REF_OBJ_P (rettype) || std_pair_ref_ref_p (rettype)))
> +	if (!(TYPE_REF_OBJ_P (rettype) || reference_like_class_p (rettype)))
>   	  return NULL_TREE;
>   
>   	/* Here we're looking to see if any of the arguments is a temporary
> @@ -13844,14 +13914,13 @@ do_warn_dangling_reference (tree expr)
>   	    if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
>   		&& !TYPE_REF_P (TREE_TYPE (arg)))
>   	      continue;
> -	    /* It could also be another call taking a temporary and returning
> -	       it and initializing this reference parameter.  */
> -	    if (do_warn_dangling_reference (arg))
> -	      return expr;
>   	    STRIP_NOPS (arg);
>   	    if (TREE_CODE (arg) == ADDR_EXPR)
>   	      arg = TREE_OPERAND (arg, 0);
> -	    if (expr_represents_temporary_p (arg))
> +	    /* Recurse to see if the argument is a temporary.  It could also
> +	       be another call taking a temporary and returning it and
> +	       initializing this reference parameter.  */
> +	    if (do_warn_dangling_reference (arg, /*arg_p=*/true))
>   	      return expr;
>   	  /* Don't warn about member function like:
>   	      std::any a(...);
> @@ -13868,15 +13937,15 @@ do_warn_dangling_reference (tree expr)
>   	return NULL_TREE;
>         }
>       case COMPOUND_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 1));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p);
>       case COND_EXPR:
> -      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1)))
> +      if (tree t = do_warn_dangling_reference (TREE_OPERAND (expr, 1), arg_p))
>   	return t;
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 2));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 2), arg_p);
>       case PAREN_EXPR:
> -      return do_warn_dangling_reference (TREE_OPERAND (expr, 0));
> +      return do_warn_dangling_reference (TREE_OPERAND (expr, 0), arg_p);
>       case TARGET_EXPR:
> -      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr));
> +      return do_warn_dangling_reference (TARGET_EXPR_INITIAL (expr), arg_p);
>       default:
>         return NULL_TREE;
>       }
> @@ -13919,7 +13988,7 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
>       = make_temp_override (global_dc->dc_warn_system_headers,
>   			  (!in_system_header_at (DECL_SOURCE_LOCATION (decl))
>   			   || global_dc->dc_warn_system_headers));
> -  if (tree call = do_warn_dangling_reference (init))
> +  if (tree call = do_warn_dangling_reference (init, /*arg_p=*/false))
>       {
>         auto_diagnostic_group d;
>         if (warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wdangling_reference,
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> new file mode 100644
> index 00000000000..330de1fd05d
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference8.C
> @@ -0,0 +1,77 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +struct Plane { unsigned int bytesused; };
> +
> +// Passes a reference through. Does not change lifetime.
> +template <typename T>
> +struct Ref {
> +    const T& i_;
> +    Ref(const T & i) : i_(i) {}
> +    const T & inner();
> +};
> +
> +struct FrameMetadata {
> +    Ref<const Plane> planes() const { return p_; }
> +
> +    Plane p_;
> +};
> +
> +void bar(const Plane & meta);
> +void foo(const FrameMetadata & fm)
> +{
> +    const Plane & meta = fm.planes().inner();
> +    bar(meta);
> +    const Plane & meta2 = FrameMetadata().planes().inner(); // { dg-warning "dangling reference" }
> +    bar(meta2);
> +}
> +
> +struct S {
> +  const S& self () { return *this; }
> +} s;
> +
> +const S& r1 = s.self();
> +const S& r2 = S().self(); // { dg-warning "dangling reference" }
> +
> +struct D {
> +};
> +
> +struct C {
> +  D d;
> +  Ref<const D> get() const { return d; }
> +};
> +
> +struct B {
> +  C c;
> +  const C& get() const { return c; }
> +  B();
> +};
> +
> +struct A {
> +  B b;
> +  const B& get() const { return b; }
> +};
> +
> +void
> +g (const A& a)
> +{
> +  const auto& d1 = a.get().get().get().inner();
> +  (void) d1;
> +  const auto& d2 = A().get().get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d2;
> +  const auto& d3 = A().b.get().get().inner(); // { dg-warning "dangling reference" }
> +  (void) d3;
> +  const auto& d4 = a.b.get().get().inner();
> +  (void) d4;
> +  const auto& d5 = a.b.c.get().inner();
> +  (void) d5;
> +  const auto& d6 = A().b.c.get().inner(); // { dg-warning "dangling reference" }
> +  (void) d6;
> +  Plane p;
> +  Ref<Plane> r(p);
> +  const auto& d7 = r.inner();
> +  (void) d7;
> +  const auto& d8 = Ref<Plane>(p).inner();
> +  (void) d8;
> +}
> diff --git a/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> new file mode 100644
> index 00000000000..9ad83f7365e
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/warn/Wdangling-reference9.C
> @@ -0,0 +1,21 @@
> +// PR c++/107532
> +// { dg-do compile { target c++11 } }
> +// { dg-options "-Wdangling-reference" }
> +
> +#include <functional>
> +
> +struct X { int n; };
> +
> +struct S {
> +  std::reference_wrapper<const X> wrapit() const { return x; }
> +  X x;
> +};
> +
> +void
> +g (const S& s)
> +{
> +  const auto& a1 = s.wrapit().get();
> +  (void) a1;
> +  const auto& a2 = S().wrapit().get(); // { dg-warning "dangling reference" }
> +  (void) a2;
> +}
> 
> base-commit: 553ff2524f412be4e02e2ffb1a0a3dc3e2280742


^ permalink raw reply	[flat|nested] 17+ messages in thread

end of thread, other threads:[~2023-03-07 14:37 UTC | newest]

Thread overview: 17+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-01-18 17:52 [PATCH] c++: -Wdangling-reference with reference wrapper [PR107532] Marek Polacek
2023-01-18 21:07 ` Jason Merrill
2023-01-19  1:13   ` [PATCH v2] " Marek Polacek
2023-01-19 18:02     ` Jason Merrill
2023-01-20  2:03       ` [PATCH v3] " Marek Polacek
2023-01-20 20:19         ` Jason Merrill
2023-01-24 22:49           ` Marek Polacek
2023-02-06  1:25             ` Jason Merrill
2023-02-07 16:46               ` [PATCH v4] " Marek Polacek
2023-03-01 20:34                 ` Marek Polacek
2023-03-01 21:53                 ` Jason Merrill
2023-03-02 21:24                   ` Marek Polacek
2023-03-03 16:25                     ` Jason Merrill
2023-03-03 17:50                       ` [PATCH v5] " Marek Polacek
2023-03-04  2:30                         ` Jason Merrill
2023-03-06 21:54                           ` [PATCH v6] " Marek Polacek
2023-03-07 14:37                             ` Jason Merrill

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).