]> gcc.gnu.org Git - gcc.git/commit - gcc/cp/constexpr.cc
c++: const_cast of null pointer in constant expr [PR99176]
authorMarek Polacek <polacek@redhat.com>
Wed, 24 Feb 2021 15:08:44 +0000 (10:08 -0500)
committerMarek Polacek <polacek@redhat.com>
Thu, 25 Feb 2021 21:29:12 +0000 (16:29 -0500)
commit2ffc26458dd7ba7b3fa00897f2d8c6cd24ba06f3
tree0887b9334bdb3b0d848a02f4334239776e8b0c98
parentb8ff3f8efeda02a6bedebfaf20b93645ae3bb5b8
c++: const_cast of null pointer in constant expr [PR99176]

Here we reject

  constexpr const int *p = nullptr;
  constexpr int *q = const_cast<int*>(p);

with "conversion of 'const int*' null pointer to 'int*' is not a
constant expression", which seems bogus.  This code has been rejected
since r238909 which added the can_convert check when converting a null
pointer.  I'm not finding any standard rule that this check was supposed
to enforce.  The original discussion was here
<https://gcc.gnu.org/legacy-ml/gcc-patches/2016-06/msg01447.html>
and here
<https://gcc.gnu.org/legacy-ml/gcc-patches/2016-07/msg00280.html>.

Since can_convert never assumes a C-style cast, it rejects casting
away constness as in the test above and in:

  constexpr int *q = (int *)(const int *) nullptr;

Removing the check only breaks constexpr-nullptr-2.C by not giving any
diagnostic for line 229:

  constexpr B *pb2 = static_cast<B*>(pa0);  // { dg-error "not a constant expression" }

but the cast seems to be valid: we do [expr.static.cast]/7, and
[expr.const] only says that a reinterpreter_cast and converting from
void* is invalid in constexpr.  The can_convert check rejected convering
from void *, but only when converting from a null pointer, so it's not
good enough.  So I've added a check to catch conversions from cv void*.
I realize it's not a great time to be adding additional checking, but
removing the can_convert check would then technically be a regression.

Let's limit the new check to only trigger for integer_zerop and then remove
it in GCC 12.

gcc/cp/ChangeLog:

DR 1312
PR c++/99176
* constexpr.c (is_std_construct_at): New overload.
(is_std_allocator_allocate): New overload.
(cxx_eval_call_expression): Use the new overloads.
(cxx_eval_constant_expression): Reject casting
from void * as per DR 1312.  Don't check can_convert.

gcc/testsuite/ChangeLog:

DR 1312
PR c++/99176
* g++.dg/cpp0x/constexpr-nullptr-2.C: Adjust dg-error.
* g++.dg/cpp0x/constexpr-cast2.C: New test.
* g++.dg/cpp0x/constexpr-cast3.C: New test.
gcc/cp/constexpr.c
gcc/testsuite/g++.dg/cpp0x/constexpr-cast2.C [new file with mode: 0644]
gcc/testsuite/g++.dg/cpp0x/constexpr-cast3.C [new file with mode: 0644]
gcc/testsuite/g++.dg/cpp0x/constexpr-nullptr-2.C
This page took 0.070036 seconds and 5 git commands to generate.