egcs-19990502 misses opportunity to do tail recursion optimizationon void funcs

Seapig6@aol.com Seapig6@aol.com
Sun May 9 09:57:00 GMT 1999


The thing to notice in the following assembly output is that the recursive 
call is present in the code for sum1 but not for sum2 (it has been optimized 
away).  Why hasn't the same optimization been applied to sum1?

[ if you need to reply to me, please use kosak@cs.cmu.edu ]

% cat opt.c
#include <stdio.h>

void sum1(int total, int x)
{
  if(x==0)
    printf("total is %d\n", total);
  else
    sum1(total+x, x-1);
}
int sum2(int total, int x)
{
  if(x==0)
    printf("total is %d\n", total);
  else
    return sum2(total+x, x-1);
  return 0;
}


% gcc -v && gcc -S -O2 opt.c && cat opt.s

Reading specs from 
/afs/cs.cmu.edu/project/cmcl-kosak/various-gcc/egcs-19990502/i386_linux3/lib/g
cc-lib/i686-pc-linux-gnu/egcs-2.93.21/specs
gcc version egcs-2.93.21 19990502 (gcc2 ss-980929 experimental)
        .file   "opt.c"
        .version        "01.01"
gcc2_compiled.:
.section        .rodata
.LC0:
        .string "total is %d\n"
.text
        .align 4
.globl sum1
        .type    sum1,@function
sum1:
        pushl %ebp
        movl %esp,%ebp
        subl $8,%esp
        movl 8(%ebp),%ecx
        movl 12(%ebp),%edx
        testl %edx,%edx
        jne .L3
        addl $-8,%esp
        pushl %ecx
        pushl $.LC0
        call printf
        jmp .L4
        .p2align 4,,7
.L3:
        addl $-8,%esp
        leal -1(%edx),%eax
        pushl %eax
        leal (%edx,%ecx),%eax
        pushl %eax
        call sum1
.L4:
        movl %ebp,%esp
        popl %ebp
        ret
.Lfe1:
        .size    sum1,.Lfe1-sum1
        .align 4
.globl sum2
        .type    sum2,@function
sum2:
        pushl %ebp
        movl %esp,%ebp
        subl $8,%esp
        movl 8(%ebp),%edx
        movl 12(%ebp),%eax
.L8:
        testl %eax,%eax
        je .L6
        addl %eax,%edx
        decl %eax
        jmp .L8
        .p2align 4,,7
.L6:
        addl $-8,%esp
        pushl %edx
        pushl $.LC0
        call printf
        xorl %eax,%eax
        movl %ebp,%esp
        popl %ebp
        ret
.Lfe2:
        .size    sum2,.Lfe2-sum2
        .ident  "GCC: (GNU) egcs-2.93.21 19990502 (gcc2 ss-980929 
experimental)"


More information about the Gcc-bugs mailing list