This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

missed tail-optimization with templates


Hi,

I'm using g++ (GCC) 3.3.3 20031206 (prerelease) (Debian). I don't fully
understand the behavior of the compiler -O2 with the C++ program (the
smallest I could produce showing the "problem") attached to this email. 

The zero() function gets compiled and tail-optimized, fine. However, the
A::zero() and B::zero() static member functions, although they amount in
combination at the same code of zero(), are _not_ tail optimized. At
first I thought templates prevent the compiler from tail-optimizing, but
if I make A::zero() more trivial (turn the #if 1 into an #if 0) the tail
optimization shows up.  

Is there anything that prevents tail optimization with #if 1? If not, is
this to be considered a possible improvement for gcc or it is just too
specific/hard to implement?

TIA,
-- 
Luca Padovani <lpadovan@cs.unibo.it>
#include <iostream>

struct Node
{
  Node(int v0, Node* n0 = 0) : value(v0), next(n0) { }

  int value;
  Node* next;
};

template <typename C>
struct A
{
  static int zero(const Node* x)
  {
#if 1
    if (x->next)
      return C::zero(x);
    else
      return 0;
#else
    return C::zero(x);
#endif
  }
};

struct B
{
  static int zero(const Node* x)
  { 
    return A<B>::zero(x);
  }
};

int zero(const Node* x)
{
  if (x->next)
    return zero(x);
  else
    return zero(x);
}

void
do_it(Node* x)
{
  std::cout << B::zero(x) << std::endl;
}

main()
{
  Node n3(3);
  Node n2(2,&n3);
  Node n1(1,&n2);
  do_it(&n1);
}

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