Branch-Free Absolute Value Calculation

Microsoft’s Visual C compiler generates the following branch-free code to calculate the absolute value of an integer.

   xor     eax, edx
   sub     eax, edx

The cdq instruction sign-extends eax into the register pair edx:eax. The cute trick here is to abuse that behavior to get an all-ones register (edx) in the case of negative input. This can be used to compute the 1’s complement, and we can also subtract it to add one (for the 2’s complement). In the case of a positive input, edx is zero and thus the xor and sub are harmless.

This is faster than the naive version, which would likely contain an unpredictable branch.

I’m surely not clever enough to have written abs this way. It seems like something the Superoptimizer might have conjured up.


1 Response to “Branch-Free Absolute Value Calculation”

  1. 1 Fast x86 Integer to Boolean at mark++ Trackback on March 21, 2008 at 5:52 pm
Comments are currently closed.

%d bloggers like this: