Some Name
Some Name

Reputation: 9540

Can GCC optimize code size for functions with the same body?

I'm debugging a C++ program with GDB and faced that different functions turned out to be the same. Here is what I mean by that:

some.hpp

class Base{
   virtual bool foo() const;
   virtual bool bar() const;
}

some.cpp

bool Base::foo() const {
  return false;
}

bool Base::bar() const {
  return false;
}

The problem is that in gdb I see the following:

(gdb) p someBaseObject->foo
$1 = {bool (const Base * const)} 0xdeadf00d <Base::foo() const>
(gdb) p someBaseObject->bar
$2 = {bool (const Base * const)} 0xdeadf00d <Base::foo() const>

I suppose GCC optimizes those two functions to save code size. Does it? This complicates debugging though...

Upvotes: 0

Views: 390

Answers (1)

Seriously
Seriously

Reputation: 1000

If you wonder how something is compiled it is often very helpful to have a look at the compiler explorer.

Here is your code (with calls to both functions) https://gcc.godbolt.org/z/g2hfcA

When enabling the compiler flag for "inter-procedural optimization Identical Code Folding" -fipa-icf you allow the compiler to replace identical functions. This leads to bar disappearing in the assembly. If you compile with -O3 this gets activated too.

GCC doc on -fipa-icf:

-fipa-icf:

Perform Identical Code Folding for functions and read-only variables. The optimization reduces code size and may disturb unwind stacks by replacing a function by equivalent one with a different name. The optimization works more effectively with link-time optimization enabled.

Although the behavior is similar to the Gold Linker’s ICF optimization, GCC ICF works on different levels and thus the optimizations are not same - there are equivalences that are found only by GCC and equivalences found only by Gold.

This flag is enabled by default at -O2 and -Os.

Upvotes: 3

Related Questions