Code optimization is absolutely fascinating.
When you multiply something by a constant (let's say 24), LLVM replaces multiplication (imul) with a combination of left shift (shl) and load effective address (lea)
Left shift by 3 is the same as multiplying by 8, load effective address does math of [base + index] in the brackets, and then stores its result.
All of this literally to save 1 cycle. Because imul takes 3 cycles, and shl and lea take 1 each.
And you can find tables with similar heuristics for a lot of different constants. These people who write optimizing compiler backends spend so much effort to save just one instruction, so don't throw it all away!
2
0 comments