Why gcc can't inline function pointers that can be determined?
c++, gcc
Solution
I think, GCC tries to optimize whole `main` function, but fails (lots of indirect calls of global functions to allocate/free memory for `xv`, get timer value, input/output, etc). So, you can try to split your code into two (or more) independent parts, like this:
inline
void foobar(vector<X>& xv)
{
for_each (xv.begin(), xv.end(), F<X>(&X::f));
}
int main()
{
const int N = 100000000;
vector<X> xv(N);
auto begin = clock();
foobar(xv);
auto end = clock();
cout << end - begin << endl;
}
So, now we have "equivalent" code as before, but GCC's optimizer has easier task to do now. I don't see any calls of `ZN1X1fEv` in assembler listing now.
Problem
The following program compiled under gcc 4.6.2 on centos with -O3: ``` #include <iostream> #include <vector> #include <algorithm> #include <ctime> using namespace std; template <typename T> class F { public: typedef void (T::*Func)(); F(Func f) : f_(f) {} void operator()(T& t) { (t.*f_)(); } private: Func f_; }; struct X { X() : x_(0) {} void f(){ ++x_; } int x_; }; int main() { const int N = 100000000; vector<X> xv(N); auto begin = clock(); for_each (xv.begin(), xv.end(), F<X>(&X::f)); auto end = clock(); cout << end - begin << endl; } ``` `objdump -D` shows that the generated code for the loop is: ``` 40097c: e8 57 fe ff ff callq 4007d8 <clock@plt> 400981: 49 89 c5 mov %rax,%r13 400984: 0f 1f 40 00 nopl 0x0(%rax) 400988: 48 89 ef mov %rbp,%rdi 40098b: 48 83 c5 04 add $0x4,%rbp 40098f: e8 8c ff ff ff callq 400920 <_ZN1X1fEv> 400994: 4c 39 e5 cmp %r12,%rbp 400997: 75 ef jne 400988 <main+0x48> 400999: e8 3a fe ff ff callq 4007d8 <clock@plt> ``` Obviously gcc doesn't inline the function. Why isn't gcc capable of this optimization? Is there any compiler flag that can make gcc do the desired optimization?