[cfe-dev] Adding a new attribute: no_extern_template

Louis Dionne via cfe-dev cfe-dev at lists.llvm.org
Tue Aug 21 14:44:07 PDT 2018


This message is related to solving the issue explained at [1], and indirectly, the usage of __always_inline__ in libc++ as explained at [2].

I've been looking to add an attribute (tentatively called no_extern_template) which would prevent member functions in a template from getting available_externally linkage even when there is a matching extern template declaration. In other words, given the following code:

    template <class T>
    struct Foo { void func() { } };
    extern template struct Foo<int>;

    void use() {
      Foo<int> f;

it is possible for Clang to emit a call to the extern function `Foo<int>::func()`, because the extern template declaration promises that it exists somewhere else in the program. Clang could also decide to inline the function and generate no extern call, but it does not _have_ to. What I want is an attribute that inhibits generating an external call, i.e. that makes sure `Foo<int>::func()` is either emitted in this TU despite the extern template declaration, or inlined (in which case a definition is obviously not needed). If the function is emitted, it should be emitted with proper linkage, in this case linkonce_odr (IIUC). The attribute would be applied to the member function that should be opted-out of the extern template declaration, like so:

    template <class T>
    struct Foo { __attribute__((no_extern_template)) void func() { } };
    extern template struct Foo<int>;

I'd like to have some feedback on this idea, specifically:

- What entities does it make sense to apply this attribute to? Currently, I'm thinking only static and non-static member functions of templates, for lack of imagination and other use cases. Does it make sense to apply it to static data members? To the vtable and RTTI somehow?

- What other attributes would be mutually exclusive with this one? Right now I can only think of `internal_linkage`, but is there anything else?

Finally, I'd also welcome any guidance on how to best achieve this in Clang. So far, I've achieved something that "works" by forcing declarations with `GVA_AvailableExternally` linkage to have `GVA_DiscardableODR` linkage (in `adjustGVALinkageForAttributes`). I think this is probably the wrong approach but I’m a Clang beginner, so I’m looking for advice if somebody has some. I'll soon publish an early code review on Phabricator to ease the process of getting feedback on the code itself.


[1]: http://lists.llvm.org/pipermail/cfe-dev/2018-July/058460.html
[2]: http://lists.llvm.org/pipermail/cfe-dev/2018-July/058419.html

More information about the cfe-dev mailing list