https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85747

            Bug ID: 85747
           Summary: suboptimal code without constexpr
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: antoshkka at gmail dot com
  Target Milestone: ---

Consider the following code snippet:

// Bubble-like sort. Anything complex enough will work
template <class It>
constexpr void sort(It first, It last) {
    for (;first != last; ++first) {
        auto it = first;
        ++it;
        for (; it != last; ++it) {
            if (*it < *first) {
                auto tmp = *it;
                *it = *first;
                *first = tmp;
            }
        }
    }
}

static int generate() {
    int a[7] = {3, 7, 4, 2, 8, 0, 1};
    sort(a + 0, a + 7);
    return a[0] + a[6];
}

int no_constexpr() {
    return generate();
}



Above code generates ~30 assembly instructions instead of just generating:

no_constexpr():
  mov eax, 8
  ret



But if we change `static` to `constexpr` then the compiler will optimize the
code correctly.

Could the compiler detect that `a[7]` holds values known at compile time and
force the constexpr on `sort(a + 0, a + 7);`? Could the compiler detect that
the function `generate()` is an `__attribute__((const))` function without
arguments and fully evaluate it's body?

Reply via email to