3 ms·
If the function returned s (the sum number), would it not optimize it away?
by 2bitencryption 11y ago
If the function returned s (the sum number), would it not optimize it away?
- asdfaoeu 11y agoWell so gcc -O2 will just replace the loop with s = NUMBER.
- schoen 11y agoI also confirmed this behavior with disassembly, and now I'm wondering what the basis of this optimization is. Can anyone explain the logic that gcc would have used to do this? As a human, I can see that the loop has no effects except to increase s by 1 each of NUMBER times, and that the result of doing so would increase s by 1 * NUMBER, and that s started as 0, so s ends up as NUMBER. (Also the loop variable i is incremented NUMBER times so it ends up as NUMBER too, but its value is never referred to again.) I'm wondering how the optimizer observed and represented these facts, and how much more general its attempts at optimizing this loop were.
- Gankro 11y agoNot 100% sure but this precise optimization for LLVM is probably part of ScalarEvolution, which tries to figure out how values in a loop evolve: http://llvm.org/devmtg/2009-10/ScalarEvolutionAndLoopOptimization.pdf http://llvm.org/devmtg/2009-10/ScalarEvolutionAndLoopOptimiz... LLVM also has a pass dedicated to detecting loop idioms: http://llvm.org/docs/doxygen/html/LoopIdiomRecognize_8cpp_source.html http://llvm.org/docs/doxygen/html/LoopIdiomRecognize_8cpp_so... (I'm not at all familiar with how GCC is architected, sorry)
- schoen 11y agoCool, thanks for the references!