commoning up template instantiations

Jay Foad jay.foad@gmail.com
Wed Nov 4 10:27:00 GMT 2015


Is GCC able to common-up the code for C++ template instantiations with
different template arguments, if they happen to generate identical
code?

Here's a simplified example:

namespace {
  template<int N>
  int f() { return 0; }
}
int g(int n) {
  static int (*const t[4])() = { f<0>, f<1>, f<2>, f<3> };
  return t[n]();
}

I can see from the output of "gcc -S -o - -O3 x.cpp" that GCC
generates four separate but identical function bodies for f<0>, f<1>,
f<2> and f<3>. It would be nice if it could generate just one copy.

(I realise that there might be concerns about the standard specifying
that different functions should have different addresses; but in a
case like this the compiler should be able to prove that the addresses
of the functions don't escape.)

Thanks,
Jay.



More information about the Gcc-help mailing list