]> git.ipfire.org Git - thirdparty/gcc.git/commit
c++: quadratic constexpr folding of arith expr [PR118340]
authorPatrick Palka <ppalka@redhat.com>
Thu, 5 Jun 2025 15:06:04 +0000 (11:06 -0400)
committerPatrick Palka <ppalka@redhat.com>
Thu, 5 Jun 2025 15:06:04 +0000 (11:06 -0400)
commite71c0157478e49188cd754693dcc2059d63573e9
tree6fb52fd2199473c106d456ec1abbd5790570e2e9
parent35200a033dfcfe38ce5c066651f94e5475a40373
c++: quadratic constexpr folding of arith expr [PR118340]

Here the PR's testcase demonstrates that the cp_fully_fold calls in
cp_build_binary_op (for diagnosing arithmetic overflow) lead to
quadratic behavior when building up a large arithmetic constant
expression.  The problem is ultimately that maybe_constant_value's
caching doesn't reuse intermediate values, unlike cp_fold.  (And
unfortunately we can't leverage the cp_fold cache in this call site
because here we want to evaluate constexpr calls even in -O0, which
cp_fold avoids.)

This patch fixes this by making maybe_constant_value look up each
operand of the given expression to see if we've previously reduced it,
and if so, rebuild the expression using the (presumably) reduced
operands and evaluate that.  After this patch each version of the
testcase from the PR compiles in ~0.1s on my machine.

PR c++/118340

gcc/cp/ChangeLog:

* constexpr.cc (maybe_constant_value): First try looking up each
operand in the cv_cache and reusing the result.

Reviewed-by: Jason Merrill <jason@redhat.com>
gcc/cp/constexpr.cc