Loop Optimization

Mason slash.tmp@free.fr
Fri Oct 14 07:44:00 GMT 2016


On 13/10/2016 08:11, Debajyoti Chatterjee wrote:
> Hello,
> I was wondering if gcc can optimize this type of for loop using loop
> rollback technique,
> for(int i=5;i--;){//body}
> in general we use,
> for(int i=0;i<5;i++){//body} , this type of loops are easy to
> understand for compilers and as 5 is constant compiler can apply loop
> rollback technique to optimize.
> I wonder which type of for loop will be good to use.

Do you read assembly code?

If so, https://gcc.godbolt.org/ is nice to examine the assembly code
output by different versions of gcc.

For example, paste the following code in the source window:

extern void foo(int);
void do_loop(void) {
  int i;
  for (int i=5; i--; ) {
    foo(i);
  }
}

Then x86-64 gcc 6.2 -O3 will output

do_loop():
        push    rbx
        mov     ebx, 4
.L2:
        mov     edi, ebx
        sub     ebx, 1
        call    foo(int)
        cmp     ebx, -1
        jne     .L2
        pop     rbx
        ret


What exactly is loop rollback?
https://en.wikipedia.org/wiki/Loop_optimization#Common_loop_transformations

Regards.



More information about the Gcc-help mailing list