4 ms·
Did you read TFA? The author did that (though using GCC), and the reason the optimizer does what you see is undefined behavior due to signed integer overflow.
by cryptonector 8y ago
Did you read TFA? The author did that (though using GCC), and the reason the optimizer does what you see is undefined behavior due to signed integer overflow.
- xeeeeeeeeeeenu 8y agoThere is no undefined behaviour, '#pragma GCC optimize("wrapv")' takes care of that. EDIT: It seems that clang doesn't support #pragma GCC optimize, so it's a no-op in that snippet. It doesn't change the result though. If you pass -fwrapv flag to clang, it will be optimized in exactly the same way.
- geezerjay 8y ago> does what you see is undefined behavior Just to be clear, undefined behavior means the standard allows implementations to do what they they feel is the right thing to do under that scenario, and the outcome will still comply with the standard.
- berti 8y agoNo, that's implementation defined behaviour.
- deleted 8y ago[deleted]
- nothrabannosir 8y agoUndefined behaviour, in reality, means: the compiler will assume that it doesn’t happen, so whatever code path leading up to it can also (by definition) not happen and be eliminated. E.g. signed integer overflow “cannot happen” so you never need to emit code checking for it or dealing with it. That’s the real world implication of undefined behaviour.
- MauranKilom 8y agoUndefined behavior is "literally anything can happen". So yes, implementations doing "what they feel is the right thing to do" is one possible result of UB (as in this case). It could also emit an rm -rf / call and it would still comply with the standard...
- kccqzy 8y agoDid you understand the comment? The author used GCC, and GCC is only able to vectorize the loop. But clang on the other hand, essentially turned this O(n) algorithm to calculate a particular sum into an O(1) result. > the reason the optimizer does what you see is undefined behavior due to signed integer overflow Yes undefined behavior gives the optimizer the right in this case to transform the code into anything, including a nonsense answer, or a trap instruction. But the optimizer did not; it produced the right answer under 2's complement arithmetic.
- cryptonector 8y agoI did read the comment, but it wasn't clear which of the two possibilities you meant. I wanted a clarification. Thanks.