c++: Fix up potential_constant_expression_1 FOR/WHILE_STMT handling [PR98672]
authorJakub Jelinek <jakub@redhat.com>
Thu, 21 Jan 2021 16:20:24 +0000 (17:20 +0100)
committerJakub Jelinek <jakub@redhat.com>
Thu, 21 Jan 2021 16:22:45 +0000 (17:22 +0100)
commit0fb7aa205afebe178c06683037ccd4c41104337a
tree6728c65b4d08ab5e7a09c623b8448c58fec856a9
parent43705f3fa343e08b2fb030460fc5e2a969954398
c++: Fix up potential_constant_expression_1 FOR/WHILE_STMT handling [PR98672]

The following testcase is rejected even when it is valid.
The problem is that potential_constant_expression_1 doesn't have the
accurate *jump_target tracking cxx_eval_* has, and when the loop has
a condition that isn't guaranteed to be always true, the body isn't walked
at all.  That is mostly a correct conservative behavior, except that it
doesn't detect if there are any return statements in the body, which means
the loop might return instead of falling through to the next statement.
We already have code for return stmt discovery in code snippets we don't
try to evaluate for switches, so this patch reuses that for FOR_STMT
and WHILE_STMT bodies.

Note, I haven't touched FOR_EXPR, with statement expressions it could
have return stmts in it too, or it could have break or continue statements
that wouldn't bind to the current loop but to something outer.  That
case is clearly mishandled by potential_constant_expression_1 even
when the condition is missing or is always true, and it wouldn't surprise me
if cxx_eval_* didn't handle it right either, so I'm deferring that to
separate PR for later.  We'd need proper test coverage for all of that.

> Hmm, IF_STMT probably also needs to check the else clause, if the condition
> isn't a known constant.

You're right, I thought it was ok because it recurses with tf_none, but
if the then branch is potentially constant and only else returns, continues
or breaks, then as the enhanced testcase shows we were mishandling it too.

2021-01-21  Jakub Jelinek  <jakub@redhat.com>

PR c++/98672
* constexpr.c (check_for_return_continue_data): Add break_stmt member.
(check_for_return_continue): Also look for BREAK_STMT.  Handle
SWITCH_STMT by ignoring break_stmt from its body.
(potential_constant_expression_1) <case FOR_STMT>,
<case WHILE_STMT>: If the condition isn't constant true, check if
the loop body can contain a return stmt.
<case SWITCH_STMT>: Adjust check_for_return_continue_data initializer.
<case IF_STMT>: If recursion with tf_none is successful,
merge *jump_target from the branches - returns with highest priority,
breaks or continues lower.  If then branch is potentially constant and
doesn't return, check the else branch if it could return, break or
continue.

* g++.dg/cpp1y/constexpr-98672.C: New test.
gcc/cp/constexpr.c
gcc/testsuite/g++.dg/cpp1y/constexpr-98672.C [new file with mode: 0644]