https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102684
Bug ID: 102684 Summary: [missed optimization] std::min_element / ranges::min_element does not get optimized away with std::gcd Product: gcc Version: 11.2.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: xkeviota at gmail dot com Target Milestone: --- This code which calculates the gcd of the minimum and maximum element of a range of elements gets optimized away entirely with clang to just a `return` statement with `-O3` while gcc (trunk) produces up to 232 lines of assembly depending on the optimization level (https://compiler-explorer.com/z/TYrx5exP3). #include <algorithm> #include <numeric> #include <span> #include <vector> namespace r = std::ranges; template <typename T> constexpr auto find_gcd(std::span<T> container) { return std::gcd(*r::min_element(container), *r::max_element(container)); } int main() { std::vector<int> ints = {2, 4, 6, 10}; return find_gcd<int>(ints); } The same happens when `std::min_element` is used for example. I found one other post regarding `std::min_element` from 2018 about custom predicates but I wasn't sure if it might have the same underlying problem.