【问题标题】:clang: export symbols of implicitly instantiated functions with O3clang:使用 O3 导出隐式实例化函数的符号
【发布时间】:2018-09-06 20:01:30
【问题描述】:

TL,DR:即使 -O3 处于活动状态,我如何强制 clang 导出隐式实例化函数的符号?

让我们看下面的代码:

#include <iostream>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/RTDyldMemoryManager.h>

template <typename T>
__attribute__((noinline))
int twice(const T& t) {
    return t * 2;
}

int thrice(const int& t) {
    return t * 3;
}

int main() {
    std::cout << twice(5) << std::endl;
    std::cout << thrice(5) << std::endl;

    llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);  // Make symbols from current process visible
    std::cout << "address of twice: " << llvm::RTDyldMemoryManager::getSymbolAddressInProcess("__Z5twiceIiEiRKT_") << std::endl;
    std::cout << "address of thrice: " << llvm::RTDyldMemoryManager::getSymbolAddressInProcess("__Z6thriceRKi") << std::endl;
}

有两个功能,两次和三次。第一个是模板,第二个不是。我首先定期给他们打电话,然后尝试使用 libLLVM 获取他们的地址。将其视为超级简化的 JIT 编译器的一部分(它有一个带有名称的 mangler)。

使用clang++ -O0 -I/usr/local/opt/llvm/include -L/usr/local/opt/llvm/lib/ jit.cpp -lLLVM(OS X 上的clang 版本6.0.0),输出如预期:

10
15
address of twice: 4350763184
address of thrice: 4350762224

如果我启用优化,twice 的符号将不再导出,如 nm a.out | grep twice 所示:

00000001000010b0 T __Z5twiceIiEiRKT_ (with -O0)
00000001000009c0 t __Z5twiceIiEiRKT_ (with -O3)

因此,libLLVM 不再找到该函数:

10
15
address of twice: 0
address of thrice: 4315621072

使用 gcc,符号被导出。

如果我明确地实例化它,我可以让 clang 导出符号:

template int twice<int>(const int& t);

然而,这并不是一个真正的选择,因为我们不知道 JIT 引擎将调用哪些实例化。

我知道this post,但它只处理显式实例化。

【问题讨论】:

    标签: c++ linker clang llvm llvm-c++-api


    【解决方案1】:

    添加属性used,像这样:

    template <typename T>
    __attribute__((used))
    int twice(const T& t) {
        return t * 2;
    }
    

    这将强制 Clang 导出符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      相关资源
      最近更新 更多