Wednesday, May 11, 2011

signed to unsigned optimization

Consider the following code snippet:

#define MAX_NR 123

int
check_nr(int nr)
{
     return ((nr >= 0) && (nr < MAX_NR));
}



which is supposed to be compiled into the following instruction set:

   push   %rbp
   mov    %rsp,%rbp
   mov    %edi,-0x4(%rbp)
   cmpl   $0x0,-0x4(%rbp)
   js     0x4004be
   cmpl   $0x7a,-0x4(%rbp)
   jg     0x4004be
   mov    $0x1,%eax
   jmp    0x4004c3
   mov    $0x0,%eax
   pop    %rbp
   retq 


The fun part begins when optimizer touches the code. Compiler can
prove that with the above limitation [0, MAX_NR) it's actually safe
to eliminate one of the checks by casting signed int nr to unsigned
int
nr, thus shortening the instruction set to:

   xor    %eax,%eax
   cmp    $0x7a,%edi
   setbe  %al
   retq  


Future is awesome!

No comments:

Post a Comment