Calculating elements addresses from arrays once

Dave Korn dk@artimi.com
Thu May 20 10:06:00 GMT 2004


> -----Original Message-----
> From: gcc-owner On Behalf Of Gruik
> Sent: 20 May 2004 10:45

> You can see my_array[i] is often accessed.
> I know that in assembly (and so in machine code), to write in 
> my_array[i], the computer has to :
> 1) Retrieve my_array address
> 2) Retrieve i value
> 3) Adding i to my_array address
> 4) Writing to the obtained address
> 
> My question is : do you think GCC, in this kind of loops, performs a 
> little optimisation by saving somewhere the address of my_array[i] ?

  Yes, gcc should be doing this kind of optimisation; it's a type of CSE.
I'm not sure if -O1 will do it but -O2 certainly ought to.

> If not, do you think the following code does a significant 
> optimisation ?
> 
> void my_func ()
> {
>     abc * current_abc;
> 
>     for (current_abc = my_array, i = 0; i < n; current_abc++, i++)
>     {
>        if (current_abc->a == value)
>           current_abc->b ++;
>        //...
>        current_abc->c = current_abc->b + 15;
> 
>        //other operations accessing fields of *current_abc
>     }
> 
>     //...
> }

  Doing this kind of optimisation by hand-rewriting to give the compiler
better clues used to be an important technique ten years ago, but most
compilers are clever enough these days to work it out for themselves.  Gcc
should even be clever enough to turn the array accesses into a pointer,
thanks to loop optimisation (induction variables), then notice that the loop
counter isn't used as an index any more and turn the loop into a count-down
since the value doesn't matter, just the number of loops.



    cheers, 
      DaveK
-- 
Can't think of a witty .sigline today....



More information about the Gcc mailing list