Tuesday, March 25, 2008

Forcing Cpp Functions To Be Called Non-inlined

Can you think of a way to force a function (usually a very small one) from not being inlined by a compiler for optimization purpose.
Often such little functions are auto-inlined by the optimizer, when compiling in release/optimized mode. Although there is a way to prevent function from inlining by prototyping it with the _cdecl keyword, sometimes all you need just specific calls to be non-inlined.
Here is the macro:
#define NON_INLINED_CALL(a) (((int)(a)+1)?(a):(0))

Now, by forcing some fake calculation (int(a)+1) we stop the compiler from optimizing given line, also by using v ? (a) : (0), we are forcing the compiler to use the _cdecl way of calling the function.
Example:

static int test(int a, int b, int c)
{
return a*b*c;
}
#define NON_INLINED_CALL(a) (((int)(a)+1)?(a):(0))
extern int results[2];

extern int a, b, c;
extern int d, e, f;
void test2( void )

{
results[0] = test(a,b,c); // Eventually with good optimizations this will be inlined
results[1] = NON_INLINED_CALL(test)(d,e,f); // No inlining here
}

Under MSVC we can construct simple and faster macro
#define NON_INLINED_CALL_MSVC(a) ((a) ? (a) : 0)

but the latter will not stop GCC optimizer, and we'll not get the results we wanted to.

P.S. I didn't test any other compilers - only GCC 2.99(ps2-ee one), and MSVC6.00