C++ inline function & context specific optimization
c++, compiler-optimization, inline-functions, optimization
Solution
I don't think "context specific optimization" is a defined term, but I think it basically means the compiler can analyse the call site and the code around it and use this information to optimise the function.
Here's an example. It's contrived, of course, but it should demonstrate the idea:
Function:
int foo(int i)
{
if (i < 0) throw std::invalid_argument("");
return -i;
}
Call site:
int bar()
{
int i = 5;
return foo(i);
}
If `foo` is compiled separately, it must contain a comparison and exception-throwing code. If it's inlined in `bar`, the compiler sees this code:
int bar()
{
int i = 5;
if (i < 0) throw std::invalid_argument("");
return -i;
}
Any sane optimiser will evaluate this as
int bar()
{
return -5;
}
Problem
I have read in Scott Meyers' Effective C++ book that: When you inline a function you may enable the compiler to perform context specific optimizations on the body of function. Such optimization would be impossible for normal function calls. Now the question is: what is context specific optimization and why it is necessary?