inline functions

Chatting with Hal, one of our summer students, we came across a bevy of interesting things to do with inlining code.

  • C99 6.7.4 tells us that inline can only be considered a hint, by the standard. gcc may choose not to inline things marked inline for a number of reasons.

  • The gcc attribute `always_inline <http://gcc.gnu.org/onlinedocs/gcc-4.0.2/gcc/Function-Attributes.html#Function-Attributes>`_ only applies to functions that are already declared with the inline function specifier.

  • always_inline will inline even with optimisation turned off. The kernel wants this on all the time so has

    #define inline                  inline          __attribute__((always_inline))
    
  • Without optimisation turned on (-O) -finline-functions does nothing. This is because gcc doesn't have enough information to analyse the functions and decide whether to put things inline or not.

  • Code bloat is an obvious issue with inlining large amounts of code; C++ can be particularly bad with excessive inlining (and is one reason why gcc might choose to ignore inline directives).

  • Particularly relevant to the kernel is stack bloat -- if you join two functions together that separately use half the available stack when inlined, gcc may not be able to figure out the scope of variables is different, and they will all get separate stack space. For example

    static inline void stack_user1(void)
    {
        int blah[1000];
    }
    
    static inline void stack_user2(void)
    {
        int blah[1000];
    }
    
    /* we use a lot of stack without realising it */
    int caller(void)
    {
        stack_user1();
        stack_user2();
    }
    
  • Documenation on using inline as a macro with the advantage of type checking.