4 ms·
Compilers often don't optimise loops away because they feel that the user put them there for a reason -- after all they are so obvious that the user could have
by adrianratnapala 10y ago
Compilers often don't optimise loops away because they feel that the user put them there for a reason -- after all they are so obvious that the user could have removed them herself.
One use for such a loop is a delay -- not so common nowadays, but it used to be a mainstay of DOS based games etc.
I bet that if GCC started aggressively optimising out empty loops, it would interact with some subtlety of concurrency to break a spinlock or three in various kernels.
- danellis 10y agoCompilers can only optimize away loops if they know that the loop has no side effects. Compilers like GCC have to have a list of standard functions that they know are pure. This can trip you up sometimes. For example, if you do something like use memset to zero out sensitive data when you're done using it, the computer can say "the result of memset is never used, and the reference to that memory is lost, so there's no need to actually make the call" and you're left with secrets in memory.
- saagarjha 10y agoForgive me if I don't know what I'm talking about here, but could volatile be used here to force the compiler to perform the memset?
- HorizonXP 10y agoYou're correct. (https://barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword https://barrgroup.com/Embedded-Systems/How-To/C-Volatile-Key...) But again, you're telling the compiler that you know what you're doing, and to not perform its normal optimization. I'm not well-versed in compiler design, but I think that's the tradeoff you have to make between trusting the user's design choices, or not.