想做个llvm的pass,实现替换所有函数调用,实现热更新功能。

写了pass后,发现无法删除原来的函数调用。 如果要将所有函数调用到某个函数all_function_entry,all_function_entry函数原型如何实现,参数如何传递?请大神赐教,感激不尽。

我不是这方面的专家,但是我可以给你一段示例代码

#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace {
  struct HotSwapPass : public FunctionPass {
    static char ID;
    HotSwapPass() : FunctionPass(ID) {}

    virtual bool runOnFunction(Function &F) {
      for (auto &BB : F) {
        for (auto &I : BB) {
          if (auto *callInst = dyn_cast<CallInst>(&I)) {
            // 获取原始函数的指针
            Function *oldFunc = callInst->getCalledFunction();
            // 创建一个新的函数指针
            Function *newFunc = F.getParent()->getFunction("newFunctionName");
            if (newFunc) {
              // 创建一个新的调用指令
              CallInst *newCall = CallInst::Create(newFunc);
              // 替换原始调用指令
              ReplaceInstWithInst(callInst, newCall);
            }
          }
        }
      }
      return true;
    }
  };
}

char HotSwapPass::ID = 0;

// 注册Pass
static void registerHotSwapPass(const PassManagerBuilder &,
                         legacy::PassManagerBase &PM) {
  PM.add(new HotSwapPass());
}
static RegisterStandardPasses
  RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
                 registerHotSwapPass);

如果这段代码无法运行,那么正如我开头所说,我不是这方面的专家

1 个赞

非常感谢大佬提供的代码。 :+1: