Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Margaret_B_
Beginner
242 Views

Optimization miss with __builtin_expect

The following code

int foo(int a, int b)
{

   do
   {
      a *= 77;
   } while (b-- > 0);  
  
   return a * 77;
}

gets perfectly optimised into 

foo(int, int):
..B1.2:                         # Preds ..B1.2 ..B1.1
        imul      edi, edi, 77                                  #4.6
        dec       esi                                           #5.12
        jns       ..B1.2        # Prob 82%                      #5.18
        imul      eax, edi, 77                                  #6.14
        ret

Adding a __builtin_expect in the loop condition 

#define likely(x) __builtin_expect((x), 1)
#define unlikely(x) __builtin_expect((x), 0)

int foo(int a, int b)
{

   do {
     a *= 77;
  } while (unlikely(b-- > 0));  
  
   return a * 77;
}

produces terrible code no matter the likelihood advised.  

foo(int, int):
        mov       eax, 1         
..B1.2:    
        xor       edx, edx  
        test      esi, esi   
        cmovg     edx, eax      
        dec       esi     
        imul      edi, edi, 77        
        test      edx, edx             
        jne       ..B1.2  
        imul      eax, edi, 77    
        ret      

By simply introducing a redundant local variable

#define likely(x) __builtin_expect((x), 1)
#define unlikely(x) __builtin_expect((x), 0)

int foo(int a, int b)
{
	int c;
  
	do 
	{
		a *= 77;
		c = b--;
	} 
	while (unlikely(c > 0));  
  
   return a * 77;
}

the code generated improves

foo(int, int):
..B1.2:                   
        mov       eax, esi
        dec       esi  
        imul      edi, edi, 77
        test      eax, eax
        jg        ..B1.2
        imul      eax, edi, 77  
        ret 

It seems that ICC get confused by the use of __builtin_expect, is this a bug of ICC or this GCC built-in is not fully functional yet?

0 Kudos
2 Replies
Yuan_C_Intel
Employee
242 Views

Hi, Margaret

Thank you for reporting this issue. I have reproduced it and entered it into our problem tracking system for a resolution.

I will let you know when I have an update on this.

Thank you!

 

Margaret_B_
Beginner
242 Views

Thank you, Yolanda

Reply