Joseph Garvin
Joseph Garvin

Reputation: 21984

Does GCC have a way to specify whether to inline at the call site?

GCC has function attributes always_inline, noinline, and flatten which let you control inlining behavior when defining a function. I'm wondering if there is a way to customize inlining behavior where the function is called, rather than setting a global inlining behavior for it like the attributes normally do.

For noinline, I can wrap a call inside a lambda with the noinline attribute and call the lambda immediately. For flatten I can wrap the function inside a template function that has true/false specializations that call the underlying function, one with flatten and one without.

But for always_inline I have no such hack. Does one exist? To be clear, I'm looking to be able to say that a specific call to f() should be inlined, not cause it to always be inlined everywhere.

Upvotes: 6

Views: 1499

Answers (1)

Ambroz Bizjak
Ambroz Bizjak

Reputation: 8115

You can define the original function as inline with attribute always_inline, and then define another function with attribute noinline which calls the former (or without noinline if you want to still allow inlining). Call the first function when you want the call to be inlined, otherwise call the second function.

Example (godbolt):

#include <stdio.h>

__attribute__((always_inline))
inline void function_inlined()
{
    puts("Hello");
}

__attribute__((noinline))
void function()
{
    return function_inlined();
}

void test()
{
    function_inlined();
    function();
}

Upvotes: 3

Related Questions