Reputation: 303
My question is opened ended and the answer may be too sophisticated for me to understand, but if you have some high level comments I would greatly appreciate them!
I wrote a simple absolute value function
int absval(int val)
{
return (val<0) ? -val: val;
}
and then compiled it with a -O flag and -S option with gcc. gcc generated the following assembly code
movl %edi, %edx
sarl $31, %edx
movl %edx, %eax
xorl %edi, %eax
subl %edx, %eax
ret
I understand how the assembly code will find the absolute value of a number, what I'm confused about is how the compiler arrived at this code. Specifically, it eliminated any control flow. Would an older version of gcc generate this same code?
Upvotes: 1
Views: 94
Reputation: 320541
Optimizations are typically implemented through pattern matching algorithms. Compiler writers hardcode a fixed set of patterns for the optimizer to look for and make the compiler to generate optimal code for them.
In other words, the compiler is hardcoded to recognize this specific "negate if negative" pattern in various contexts and generate this branchless machine code for it.
In the actual compiler the pattern is not necessarily as specific as "negate if negative". It could be some higher-level meta-pattern that reduces to "negate if negative" once the specific details from your code are substituted into it. But some sort of pattern matching happens in any case.
Upvotes: 3