A small correction: the sigma summation should go to n-1, not n. It's weird that LLVM computes n(n-1)/2 in such a convoluted way, namely: (n-1)(n-2)/2 + n - 1
count = count + i
is just before overflowing. In that case the O(N) algorithm has no overflow, but if you look at the closed form solution. Surely
(count)*(count-1)
would overflow.
A compiler must never be allowed to swap a non-overflow with a overflow. Which is one big limit of these optimizations.