banach-space / llvm-tutor

A collection of out-of-tree LLVM passes for teaching and learning
MIT License
2.99k stars 396 forks source link

How to add a plugin when compiling an entire codebase #58

Open vjpr opened 2 years ago

vjpr commented 2 years ago

Related

I am trying to instrument all function calls in an existing codebase.

I don't want to have to modify existing makefile scripts too extensively.


The solution is to use the legacy pass manager.

clang++ -flegacy-pass-manager -Xclang -load -Xclang ./libmypass.so input.cpp

It seems that the new pass manager doesn't allow this yet.

You must take care to choose the correct extension point. See here are the extension points. See [here] (https://github.com/rdadolf/clangtool/blob/353b80061ce30c3062bbe4752dbaa2a1c84cc9c8/clangtool.cpp#L42-L49) for an explanation of which ones to use.


This information should be added to the readme.md.

banach-space commented 2 years ago

Hello @vjpr , thanks for creating this issue and for your extensive research on this matter :)

The solution is to use the legacy pass manager.

Unfortunately, the Legacy PM will be removed after LLVM 14?

This information should be added to the readme.md.

Good point! Do you have the bandwidth to create a PR? This would have to be added with the caveat that it will stop working once LLVM 15 is released. Sadly :(

dothyt commented 6 months ago

looks like it's never been resolved even though it's pretty old. I would like to add some of my finding

I ran into the same issue while handling one of my recent project. After going through some of the recent llvm documentation, I figured out how to load a custom pass with the new pass manager to the default compilation pipeline

the general command would look like this

clang-17 -fpass-plugin=<pass plugin so> -fplugin=<pass plugin so> -mllvm -arg1=<val> src.cpp -o obj

To explain what happened in the command above, pass-plugin loads the library of the pass to the new pass manager. However, afaik, the new pass manager doesn't have the ability to pass a command line argument. so we need to use the plugin to load the library again and use -mllvm for additional custom command line options, refer to CommandLine 2.0 Library Manual for how to add a command line option in llvm pass code.

Lastly, as the original post mentioned, the correct entry point needed to be used (e.g. registerPipelineStartEPCallback, registerOptimizerEarlyEPCallback, etc.). These entry points will be affected whether the program is compiled with -O3 or -O0