http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59948
Bug ID: 59948 Summary: Optimize std::function Product: gcc Version: 4.9.0 Status: UNCONFIRMED Keywords: missed-optimization Severity: normal Priority: P3 Component: ipa Assignee: unassigned at gcc dot gnu.org Reporter: glisse at gcc dot gnu.org #include <functional> inline int f(int i){return i-1;} int m(){ std::function<int(int)> h=f; return h(1); } clang manages to optimize this to just: int m(){return 0;} However, g++ is stuck with a much longer code (comments inline): int m() () { void * D.29797; struct function h; bool (*<T5503>) (union _Any_data &, const union _Any_data &, _Manager_operation) _8; bool (*<T5503>) (union _Any_data &, const union _Any_data &, _Manager_operation) _9; int (*<T590e>) (const union _Any_data &, int) _24; int _26; <bb 2>: MEM[(struct _Function_base *)&h]._M_manager = 0B; if (f != 0B) // Shouldn't we know that f!=0? It is defined just above. goto <bb 3>; else goto <bb 4>; <bb 3>: MEM[(int (*<T5912>) (int) *)&h] = f; h._M_invoker = _M_invoke; h.D.26519._M_manager = _M_manager; if (_M_manager == 0B) // Same, shouldn't we know that _M_manager!=0? goto <bb 4>; else goto <bb 5>; <bb 4>: std::__throw_bad_function_call (); <bb 5>: _24 = h._M_invoker; // Why not _M_invoke directly, we can only arrive here from bb3 // and nothing can clobber h._M_invoker. Then we might have a chance // to inline the next line. _26 = _24 (&h.D.26519._M_functor, 1); <bb 6>: _8 = MEM[(struct _Function_base *)&h]._M_manager; // I guess we need to fix the call to _24 above to know // there is nothing clobbering h._M_manager. if (_8 != 0B) goto <bb 7>; else goto <bb 8>; <bb 7>: _8 (&MEM[(struct _Function_base *)&h]._M_functor, &MEM[(struct _Function_base *)&h]._M_functor, 3); <bb 8>: h ={v} {CLOBBER}; h ={v} {CLOBBER}; return _26; <L3>: _9 = MEM[(struct _Function_base *)&h]._M_manager; if (_9 != 0B) goto <bb 10>; else goto <bb 11>; <bb 10>: _9 (&MEM[(struct _Function_base *)&h]._M_functor, &MEM[(struct _Function_base *)&h]._M_functor, 3); <bb 11>: h ={v} {CLOBBER}; _10 = __builtin_eh_pointer (2); __builtin_unwind_resume (_10); } Trying to modify std::function by removing tests, compiling with -fno-exceptions, etc, I got to situations with f(1) (not inlined), or we still had an uninlined call to _M_manager (which, inlined, would reduce to nothing), but never a clean return 0. If this simple example gets fixed, please check on the example in http://gcc.gnu.org/ml/gcc/2014-01/msg00261.html Related issues: PR 45631 PR 45632 PR 47413 (PR 56551)