Re:Low Level Bit Hacks You Absolutely Must Know
by Hello71 on Friday May 11, 2018 @08:41AM
(#17046858)
In fact, newer gcc versions are unable to optimize (x & 1) == 0 at level -O1, and require -O2. I assume that the code emitted at -O2 and -O3 for both constructs is the more efficient version than the literal translation, even though they are the same number of instructions.
[ Parent
| on HN ]
Re:Low Level Bit Hacks You Absolutely Must Know
by vardump on Friday May 11, 2018 @02:08PM
(#17049546)
Apparently not true, at least in a simple function.
int isEven(int number)
{
return number & 1;
}
gcc 7.3, -O1, -O2 and -O3 (identical codegen for all optimization levels): isEven(int):
mov eax, edi
and eax, 1
ret
Re:Low Level Bit Hacks You Absolutely Must Know
by Hello71 on Friday May 11, 2018 @06:31PM
(#17051194)
that function checks if a number is odd, not even.
Re:Low Level Bit Hacks You Absolutely Must Know
by vardump on Friday May 11, 2018 @07:31PM
(#17051454)
My bad. Didn't even check it at any point.
Anyways, you still prove my point. All those three are pretty close.
-O1 sete instruction is very slightly unoptimal, but even it is just a fractional clock cycle.
Re:Low Level Bit Hacks You Absolutely Must Know
by BearOso on Friday May 11, 2018 @01:33PM
(#17049257)
I highly doubt it. That’s 1:1
test eax, 1
; use result
Re:Low Level Bit Hacks You Absolutely Must Know
by Hello71 on Friday May 11, 2018 @06:33PM
(#17051203)
gcc -O2, clang, and icc all produce the sequence:
is_even(int):
mov eax, edi
not eax
and eax, 1
ret
I am far from a x86 expert, but I assume this version avoids contention on the flags registers and increases pipelining.edit: my mistake, icc and clang produce the equivalent sequence "not edi; and edi, 1; mov eax, edi; ret".