Re: "if (i == n) ++i;" or "i += i == n;"?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Erik writes:
 > Suppose that we have a function f that can be written in 2 ways with 
 > identical result:
 > unsigned int f(unsigned int i, unsigned int n) {++i; if (i == n) ++i; 
 > return i;}
 > unsigned int f(unsigned int i, unsigned int n) {++i; i += i == n; return i;}
 > 
 > g++ -O3 produces different code for the 2 versions:
 >         pushl   %ebp
 >  .LCFI0:
 > +       xorl    %edx, %edx
 >         movl    %esp, %ebp
 >  .LCFI1:
 > -       movl    8(%ebp), %edx
 > -       leal    1(%edx), %eax
 > +       movl    8(%ebp), %eax
 > +       incl    %eax
 >         cmpl    12(%ebp), %eax
 > -       je      .L6
 >         popl    %ebp
 > -       ret
 > -       .p2align 4,,7
 > -.L6:
 > -       popl    %ebp
 > -       leal    2(%edx), %eax
 > +       sete    %dl
 > +       addl    %edx, %eax
 >         ret
 >  .LFE2:
 > 
 > This implies that one of the following 3 statements holds:
 > 1. The 2 versions of f are indeed not identical.
 > 2. The 2 versions of the generated code are equally efficient, so the 
 > difference does not matter.
 > 3. g++ generates suboptimal code for one of the versions of f.
 > 
 > Anyone knows which statement holds.

Probably 3.  Looking at the optimized code dump, we have:


unsigned int f1(unsigned int, unsigned int) (i, n)
{
  unsigned int i.24;

<bb 2>:
  i.24 = i + 1;
  if (i.24 == n) goto <L0>; else goto <L1>;

<L0>:;
  i.24 = i.24 + 1;

<L1>:;
  return i.24;

}

unsigned int f2(unsigned int, unsigned int) (i, n)
{
  unsigned int i.49;
  unsigned int D.2439;

<bb 2>:
  i.49 = i + 1;
  D.2439 = i.49 == n;
  return D.2439 + i.49;

}


I note that identical code is generated for the two functions at -O1.

I don't know which is faster.

Andrew.

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux