void foo (int& sz, int n)
{
    for (++n; --n;)
        sz += 5;
}

Produces (-Os):

_Z3fooRii:
        incl    %esi
        jmp     .L2
.L3:
        addl    $5, (%rdi)
.L2:
        decl    %esi
        jne     .L3
        ret

gcc thinks that every little change to sz needs to be stored in memory, causing
the above inefficiency of emitting a loop instead of a multiplication. It would
be desirable to treat sz as a local variable and optimize as if:

void bar (int& sz, int n)
{
    int tmp = sz;
    for (++n; --n;)
        tmp += 5;
    sz = tmp;
}

Which compiles to:

_Z3barRii:
        leal    (%rsi,%rsi,4), %esi
        addl    %esi, (%rdi)
        ret

much better code. If somebody really does need each variable access to be a
memory access, that variable should be declared volatile.

If you don't want to fix this, at least provide a variable attribute to tell
the compiler that it's ok to omit stores.


-- 
           Summary: Non-volatile variables don't need to be constantly
                    modified
           Product: gcc
           Version: 4.5.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: msharov at users dot sourceforge dot net
  GCC host triplet: x86_64-gnu-linux


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45243

Reply via email to