Compiler loop optimizations

Christian Sturz <linuxkaffee@gmx.net>
29 Dec 2006 22:58:13 -0500

          From comp.compilers

Related articles
Compiler loop optimizations linuxkaffee@gmx.net (Christian Sturz) (2006-12-29)
Re: Compiler loop optimizations emailamit@gmail.com (Amit Gupta) (2006-12-31)
Re: Compiler loop optimizations robert.hundt@gmail.com (Robert H) (2007-01-01)
Re: Compiler loop optimizations robert.hundt@gmail.com (Robert H) (2007-01-01)
Re: Compiler loop optimizations torbenm@app-0.diku.dk (2007-01-05)
Re: Compiler loop optimizations linuxkaffee@gmx.net (Christian Sturz) (2007-01-05)
Re: Compiler loop optimizations emailamit@gmail.com (Amit Gupta) (2007-01-07)
[3 later articles]
| List of all articles for this month |

From: Christian Sturz <linuxkaffee@gmx.net>
Newsgroups: comp.compilers
Date: 29 Dec 2006 22:58:13 -0500
Organization: Compilers Central
Keywords: optimize, question
Posted-Date: 29 Dec 2006 22:58:13 EST

Hi,


I was curious if there are any gcc compiler optimizations that can improve
this code:


void foo10( )
{
    for ( int i = 0; i < 10; ++i )
    {
        [...]
        if( i == 15 ) { [BLOCK1] }
    }
}


void foo100( )
{
    for ( int i = 0; i < 100; ++i )
    {
        [...]
        if( i == 15 ) { [BLOCK2] }
    }
}


int main( void )
{
    foo10( );
    foo100( );
    return 0;
}


1) For the function foo10:
The if-block following "if( i == 15 )" will be never executed since 'i'
will never become 15 here. So, this entire block could be removed without
changing the semantics. This would improve the program execution since the
if-condition does not need to be evaluated in each loop iteration. Can
this code transformation be automatically performed by a compiler? If so,
which techniques/analyzes and optimizations must be applied? Would gcc
simplify this loop?


2) For the function foo100:
This code is not optimal as well. The if-condition is just once met but
has to be evaluated for all of the 100 loop iterations. An idea I had in
mind was to split the loop in two parts: for ( int i = 0; i <= 15; ++i )
{...} BLOCK2
for ( int 16 = 0; i < 100; ++i ) {...} So, here the evaluation of "i==15"
is not required any more and we save 100 comparisons. Is this a good idea
and always applicable? Or are there better compiler optimizations?


Thank you very much for your help.


Regards,
Christian


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.