https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108635
Bug ID: 108635 Summary: Redundant calls to C++ spaceship operator<=> with attribute pure or const Product: gcc Version: 12.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: jzwinck at gmail dot com Target Milestone: --- This code seems to have a missed optimization in GCC 10/11/12: #include <compare> struct S { std::weak_ordering operator<=>(const S&) const __attribute__((const)); }; int compare3way(S& a, S& b) { return (a < b) ? -1 : (a > b) ? 1 : 0; } I expect operator<=> to be called once, but it is called twice. This can be a major missed optimization if operator<=> is expensive. It happens regardless of: 1. Using attribute((const)) or attribute((pure)). 2. Making operator<=> a free function or a member. 3. Comparing (a > b) or (a < b) in the second ternary expression. This is especially strange, because it's really calling the same pure function twice, and that's optimized correctly when the function being called is operator< instead of operator<=>. Clang optimizes it as expected. Demo: https://godbolt.org/z/jP51E6xaz