c++: improve -Waddress warnings with *_cast [PR105569]
authorMarek Polacek <polacek@redhat.com>
Wed, 11 May 2022 18:38:49 +0000 (14:38 -0400)
committerMarek Polacek <polacek@redhat.com>
Thu, 26 May 2022 21:11:07 +0000 (17:11 -0400)
This patch improves the diagnostic for -Waddress when it warns for

  if (dynamic_cast<A*>(&ref))
    // ...

where 'ref' is a reference, which cannot be null.  In particular, it
changes
warning: comparing the result of pointer addition '(((A*)ref) + ((sizetype)(*(long int*)((& ref)->B::_vptr.B + -24))))' and NULL
to
warning: the compiler can assume that the address of 'ref' will never be NULL

PR c++/105569

gcc/cp/ChangeLog:

* typeck.cc (warn_for_null_address): Improve the warning when
the POINTER_PLUS_EXPR's base is of reference type.

gcc/testsuite/ChangeLog:

* g++.dg/warn/Waddress-9.C: New test.

gcc/cp/typeck.cc
gcc/testsuite/g++.dg/warn/Waddress-9.C [new file with mode: 0644]

index 385cdf4..190d710 100644 (file)
@@ -4757,8 +4757,16 @@ warn_for_null_address (location_t location, tree op, tsubst_flags_t complain)
       tree off = TREE_OPERAND (cop, 1);
       if (!integer_zerop (off)
          && !warning_suppressed_p (cop, OPT_Waddress))
-       warning_at (location, OPT_Waddress, "comparing the result of pointer "
-                   "addition %qE and NULL", cop);
+       {
+         tree base = TREE_OPERAND (cop, 0);
+         STRIP_NOPS (base);
+         if (TYPE_REF_P (TREE_TYPE (base)))
+           warning_at (location, OPT_Waddress, "the compiler can assume that "
+                       "the address of %qE will never be NULL", base);
+         else
+           warning_at (location, OPT_Waddress, "comparing the result of "
+                       "pointer addition %qE and NULL", cop);
+       }
       return;
     }
   else if (CONVERT_EXPR_P (op)
diff --git a/gcc/testsuite/g++.dg/warn/Waddress-9.C b/gcc/testsuite/g++.dg/warn/Waddress-9.C
new file mode 100644 (file)
index 0000000..d3e4697
--- /dev/null
@@ -0,0 +1,31 @@
+// PR c++/105569
+// { dg-do compile { target c++11 } }
+// { dg-options -Waddress }
+
+class A {};
+
+class B : public virtual A {};
+
+class C : public A {};
+
+int main() {
+    B* object = new B();
+    B &ref = *object;
+
+    bool b = nullptr == dynamic_cast<A*>(&ref); // { dg-warning "the address of 'ref' will never be NULL" }
+    bool b4 = nullptr == static_cast<A*>(&ref); // { dg-warning "the address of 'ref' will never be NULL" }
+    if (dynamic_cast<A*>(&ref)) // { dg-warning "the address of 'ref' will never be NULL" }
+      {
+      }
+    if (static_cast<A*>(&ref)) // { dg-warning "the address of 'ref' will never be NULL" }
+      {
+      }
+
+    auto ptr = dynamic_cast<A*>(&ref);
+    bool b2 = ptr == nullptr;
+
+    C* cobject = new C();
+    C &cref = *cobject;
+
+    bool b3 = nullptr == dynamic_cast<A*>(&cref);
+}