gpt4 book ai didi

c++ - 如何链接两个 LLVM 位码模块?

转载 作者:行者123 更新时间:2023-11-30 05:11:04 26 4
gpt4 key购买 nike

我有一个简单的 LLVM pass,它重命名当前翻译单元中定义的每个函数(即:有问题的源文件,在所有预处理步骤都发生之后 - 请参阅 here)。我的通行证如下:

#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/GlobalValue.h"

using namespace llvm;

namespace {

struct FunctionRename : public ModulePass {
static char ID; // Pass identification
FunctionRename() : ModulePass(ID) {}

bool runOnModule(Module &M) override {
// Rename all functions
for (auto &F : M) {
StringRef Name = F.getName();
// Leave library functions alone because their presence or absence
// could affect the behaviour of other passes.
if (F.isDeclaration())
continue;
F.setLinkage(GlobalValue::LinkOnceAnyLinkage);
F.setName(Name + "_renamed");
}
return true;
}
};
}

char FunctionRename::ID = 0;
static RegisterPass<FunctionRename> X("functionrename", "Function Rename Pass");
// ===-------------------------------------------------------==//
//
// Function Renamer - Renames all functions
//

在对位码文件运行传递后,file.bc , 我将结果输出到一个新文件 file_renamed.bc ,如下

opt -load /path/to/libFunctionRenamePass.so -functionrename < file.bc > file_renamed.bc

然后我尝试按如下方式链接这两个文件

llvm-link file.bc file_renamed.bc -o file_linked.bc

但是,对于涉及构造函数和析构函数的 C++ 源文件(从中生成初始位码文件),我仍然遇到符号冲突。我的期望是这条线

F.setLinkage(GlobalValue::LinkOnceAnyLinkage)

将防止 file.bc 中定义的任何符号发生符号冲突和 file_renamed.bc .

我做错了什么?

最佳答案

当我尝试在示例位码文件上运行您的代码时,llvm-link 步骤因全局变量而失败:

ERROR: Linking globals named 'my_global': symbol multiply defined!

在向 RunOnModule 例程添加第二个循环以处理全局变量后,llvm-link 成功,然后代码最终链接。

for (auto git = M.global_begin(), get = M.global_end(); git != get; ++git)
{
GlobalValue* gv = &*git;
gv->setLinkage(GlobalValue::LinkOnceAnyLinkage);
}

但是,我对带有构造函数的 C++ 代码的简单测试在有和没有这种变化的情况下都有效。

关于c++ - 如何链接两个 LLVM 位码模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45300815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com