This is the mail archive of the ecos-discuss@sources.redhat.com mailing list for the eCos project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Optimizations and bad code



Compiler optimizations can be a real pain, especially if you have some funny code.
Look at the following example:

{
    int i, y;

   i = 0;

    for(y=0; y<176; y++)
    {
        func(x, y, (a[i++] + (a[i++]<<1) + a[i++])>>2);
    }
}

This is real ugly code, extracted from a non working progam.
It was meant to combine three values from an RGB buffer (containing a 24 bit image)
into one 8 bit gray scale value. This was no serious programming but just a fast hack
to get something on the LCD.

According to the C standard, the arguments to the + operator may be evaluated in any
order, making it unpredictable to tell if the R, G or B value will get the <<1. But I guess that
the "i" should always be three more that it started of with after going through the loop once.

The amizing part however is that with the arm-elf-gcc compiler, it depends if optimizations
are on "-O2" or off "-O0". Without optimizations i is incremented with 1 (!) after going through
the loop once. All other variants (including different optimization settings for the i686-pc-linux-gnu
and native linux compiler) have i incremented by 3.

Although I admit that one should never write code like this, the results are amazing.
It just shows that "working in my private enviroment" does not mean it is correct code.

Regards,

     Rob Jansen

Software Engineer
Competence Center Platforms
BU Mobile Communications
Meijhorst 60-10, 6537 KT Nijmegen, The Netherlands
Tel: +31-24-353-6329
Fax: +31-24-353-3613
mailto:Rob.WJ.Jansen@philips.com




Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]