Does g++ empty function removal work recursively?

To the best of my knowledge, g++ with optimization turned on will remove the function call to bar entirely in the following case:

int bar() { }    
int foo() { bar(); }

However, consider the following two cases, with bar defined as above:

Case 1:

int foo(int a, int b) {
    if (a > b) bar();
}

Case 2:

int foo() { bar(); }
int foo2() {foo(); }

In Case 1, will the if statement also be removed, since it executes dead code even if the condition is true?

In Case 2:, will the call to foo inside foo2 be removed?

Answers


Following the suggestions in the comments, I tried this myself and it appears that the empty function calls are indeed removed recursively and completely in both cases I described, at least for gcc 4.8.1 and g++ 4.8.1.

I compiled the following two programs, first with gcc -S and then with gcc -S -O2.

Program 1:

int bar() { }
int foo() { bar(); }
int main() {
    foo();
}

Program 2:

int bar() { }

int foo(int a, int b) {
    if (a > b) bar();
}

int main() {
    foo(2,1);
}

I also tried with foo's arguments passed in from the command line, to make sure the removal was not because of constants passed to foo.

int main(int argc, char** argv) {
    foo(argc,1);
}

The compiler doesn't remove entire functions, the linker does.

If you're building an executable (or the functions are not exported out of a library), then the linker will remove all the orphan functions. If it doesn't, it's a bug :).

BTW, storing the address of a function (e.g. in a variable or passing it to another function) guaranties that the function will stay.

Edit Just, to be clear, the optimizing compiler will inline functions, effectively removing the function calls where it deems necessary. In the above case (super simple functions) there's no doubt it will inline them. BTW, STL implementations (and boost) depend on this feature heavily.


Need Your Help

Nagios notification client for mac?

osx apple nagios

I recently switched to a mac and am currently looking for a Nagios client that displays the Nagios notifications & alerts.

How to resolve Microsoft JScript runtime error: '$' is undefined

javascript jquery asp.net

I have a live site and I open it on Internet explorer and right click on page and click on view source and copy all code from it and paste it on vs2010->Newwebsite and when i run my site on vs2010 an

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.