How can you tell what will or what won't be made inline by the compiler?
You cannot, in general.
You may want to read the Inline Redux article by Herb Sutter. It exposes a number of technologies to explain when inlining may happen, knowing that the latter it happens... the more information you have.
For example, in a JIT environment, you could look at a loop, realize the whole of its body is executed on a single object which appears to be frequently of type Foo
, specialize the whole body for Foo
, which allows full inlining of virtual methods, and now check at the top of the loop if the object is a Foo
and if so switch to the fully inlined body version instead of the generic one with virtual calls.
So what can be inlined ? It depends when...
In general C++ compilers feature:
- Compile time inlining (historical)
- Link time inlining (part of the so called LTO optimization package)
This means that they can only base their optimizations on static (known at compile-time) information.
At compile-time, this means that if the static type a virtual call might be devirtualized (first step of inlining: guessing the actual function called ;) ). It means that any function which definition is visible can also be inlined.
At link-time for a library, you basically expose new function definitions which allows to inline a few calls.
At link-time for an executable, WPA (Whole Program Analysis) can kick off to add some devirtualization by realizing that some classes are never derived from, and thus can be considered final
as far as this executable is concerned. Neither GCC nor LLVM (and I doubt VC++ can) may perform this optimization though because they do not have a byte code that keeps class hierarchies around.
And compilers could, if they wished, dump the intermediate representation they have (bytecode in a way) and wait for the installation to inline OS-specific calls. Though I know of none (for C++) that do this.
Runtime changes is quite tricky in C++ because memory (for example function addresses) is accessible to the programmer so it would be difficult to make only safe transformations...