Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.

Optimization miss with __builtin_expect

Margaret_B_
Beginner
1,179 Views

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
1,179 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!

 

0 Kudos
Margaret_B_
Beginner
1,179 Views

Thank you, Yolanda

0 Kudos
Reply