Why are compilers unable to optimize an array being written to twice?

Viewed 89

Consider the following code:

#include <algorithm>
#include <numeric>

int main() {
    int* v = new int[1000];
    std::fill(v,v+1000,0);
    std::iota(v,v+1000,0);
    int res = v[999];
    delete[] v;
    return res;
}

I would expect the compiler to see that the std::fill is not needed because the array is immediately overwritten by std::iota. However, with either Clang or GCC (with -O3), the assembly code is different if I remove the std::fill instruction (it is shorter, and from my understanding, it is because in one case instructions are emitted from std::fill). See here and here.

Is something really preventing compilers to optimize it away from a correctness point of view? Or is it a missing optimization, and if so, why is it so complicated to figure it out?

I stumbled accross the issue because if one wants to create a vector with a size, and then assign values to it, the default constructor will zero out the vector, even if it is not needed, see this question

0 Answers
Related