Based on LLVM 20.1.4
- Legacy Version of Pass
- C++ class that inherits the
Pass
class in LLVM- Implement functionality by overriding virtual methods
- e.g.,
runOnModule
orrunOnFunction
- C++ class that inherits the
- New Version of Pass
- C++ class that inherits the
PassInfoMixIn
struct inllvm/IR/PassManager.h
- Implement
PreservedAnalyses run (Module &M, ModuleAnalysisManager &AM);
- C++ class that inherits the
- Define the Module Pass in a Header File
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
struct HelloModulePass : llvm::PassInfoMixin<HelloModulePass> {
static llvm::PreservedAnalyses run(
const llvm::Module &M,
llvm::ModuleAnalysisManager &MAM);
};
- Write the source for the module pass
llvm::PreservedAnalyses HelloModulePass::run(const llvm::Module &M, llvm::ModuleAnalysisManager &MAM) {
/** Some Code */
return llvm::PreservedAnalyses::all(); /**If Editing IR, return PreservedAnalyses::None() */
}
- Register Pass
extern "C" llvm::PassPluginLibraryInfo llvmGetPassPluginInfo() {
return {
LLVM_PLUGIN_API_VERSION,
"HelloPass",
LLVM_VERSION_STRING,
[](llvm::PassBuilder &PB) {
PB.registerPipelineParsingCallback(
[](const llvm::StringRef name, llvm::ModulePassManager &MPM,
llvm::ArrayRef<llvm::PassBuilder::PipelineElement>) {
if (name == "HelloModulePass") {
MPM.addPass(HelloModulePass());
return true;
}
return false;
}
);
}
};
}
- Compile a pass and make it a shared-library
clang++ -fPIC -fno-rtti -shared \
HelloModule.cpp \
`llvm-config --cxxflags --ldflags --libs core support passes` \
-o [OUTPUT.so]
- Run the LLVM pass using opt
opt -load-pass-plugin [OUTPUT.so] -passes=HelloModulePass [GENERATED_BITCODE] -o [OUTPUT]