Search code examples
c++llvmllvm-c++-api

How to run a module pass in LLVM


I'm trying to find a way to optimize away empty global constructors. Previous optimizations will turn constructors into functions that do nothing. I need to add a new pass to remove these functions from llvm.global_ctors.

First, I tried optimizeGlobalCtorsList but this function doesn't actually call the callback I give it even though llvm.global_ctors is populated.

Then I tried running GlobalOptPass. I tried this:

llvm::GlobalOptPass pass;
llvm::ModuleAnalysisManager MAM{true};
pass.run(module, MAM);

This ends up dereferencing a null pointer in AnalysisManager::lookupPass. I think I need to perform some sort of initialization or registration but I don't know how to do that. All the references on "llvm pass registration" talk about registering the pass with opt. I don't want to do that. I just want to run the pass.


Solution

  • Look in lib/Transforms/IPO/PassManagerBuilder.cpp (or lib/Passes/PassBuilder.cpp for the new pass manager) to see how opt sets up its pass pipeline. The code for opt is in tools/opt/opt.cpp and is very small, delegating almost all of its work to the core libraries.

    You could use opt as a template for your own tool, or you could hack on the pass building pipline to insert your pass where you want it.