How to extract functions from Module A and put them into Module B, and generate a new IR file?

Hi all,

This is Michael and very happy to share my question here!

My question is, is there a way to “extract” a function from Module A and write it into another Module B, and generate two new IR files? IRBuilder seems like a workable way but I have to create instructions one by one. I am new to LLVM so don’t know whether it is doable, here is my experimental code:

runOnModule(Module &M){

LLVMContext& context = getGlobalContext();

llvm::raw_fd_ostream osA(“A.bc”, “”, llvm::sys::fs::F_None);
llvm::raw_fd_ostream osB(“B.bc”, “”, llvm::sys::fs::F_None);

llvm::Module *ModuleA = new llvm::Module(“A”, context);
llvm::Module *ModuleB = new llvm::Module(“B”, context);



for (Function &F : M) {
if (F.getName() == “My Criterion”)


WriteBitcodeToFile(ModuleA, osA);
WriteBitcodeToFile(ModuleB, osB);


By doing this I can get two .bc files, but when I open it, for each function I can only get the declaration, but not the definition(function body).

Could you give me some comments on how to generate the function definitions? Or any other better ways for generating the IRs? Thanks very much!

Best regards,


Correctly moving functions between modules is tricky in general; I'd suggest using one of the existing utilities to do it. See include/llvm/Linker/Linker.h and include/llvm/Linker/IRMover.h.