https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129232
Bug ID: 129232
Summary: [C++26] constexpr function with postcondition
referencing return value or implicit this fails
constant evaluation
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: c++-contracts, c++26, rejects-valid
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: adrian.herrmann.xyz at gmail dot com
Target Milestone: ---
Constant evaluation fails for constexpr/consteval functions when a
postcondition names the return value or references a member through implicit
'this':
--- repro.cpp ---
constexpr int add1(const int x) post (r : r == x + 1) {
return x + 1;
}
template <typename T>
struct Box {
T value;
constexpr T get() const pre (value > 0) post (r : r == value) {
return value;
}
};
static_assert(add1(41) == 42);
static_assert(Box<int>{7}.get() == 7);
int runtime_call(int x) {
return add1(x) + Box<int>{x}.get();
}
$ g++ -std=c++26 -fcontract-evaluation-semantic=enforce -c repro.cpp -o
/dev/null
error: 'r' is not a constant expression
In gcc/cp/contracts.cc, remap_dummy_this and remap_retval are only called from
build_contract_check during cp_genericize, which runs after constant
evaluation. When constexpr.cc evaluates PRECONDITION_STMT/POSTCONDITION_STMT
from apply_preconditions/apply_postconditions, CONTRACT_CONDITION still
contains the placeholder POSTCONDITION_IDENTIFIER PARM_DECL and dummy 'this'.
Both helpers also use walk_tree instead of cp_walk_tree, remap_dummy_this lacks
a DECL_IOBJ_MEMBER_FUNCTION_P (fndecl) guard, and remap_retval does not clear
POSTCONDITION_IDENTIFIER (contract) after remapping.
I have a fix for this and plan to send it to gcc-patches.
Tested on master 48688cfeadf6ec3b2dd22783f5048db6fc444d04 (also reproduces on
5a61875b0cd983e57dd44b7d6e12b9eb11985bae):
Using built-in specs.
COLLECT_GCC=xg++
Target: x86_64-elf
Configured with: src/configure --target=x86_64-elf --enable-languages=c++
--disable-nls --disable-lto --disable-libssp --disable-multilib
--without-headers --without-isl --without-zstd --enable-checking=yes
Thread model: single
gcc version 17.0.0 20261126 (experimental) (GCC)