-
Ehsan Akhgari authored
This builds on the support being added to LLVM to import and export registries from DLLs. This will allow us to pick up the registry entries added in the DLL's copy of FrontendPluginRegistry. This will allow us to use plugins on Windows using: $ clang-cl -Xclang -load -Xclang plugin.dll \ -Xclang -add-plugin -Xclang foo git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@260265 91177308-0d34-0410-b5e6-96231b3b80d8
Ehsan Akhgari authoredThis builds on the support being added to LLVM to import and export registries from DLLs. This will allow us to pick up the registry entries added in the DLL's copy of FrontendPluginRegistry. This will allow us to use plugins on Windows using: $ clang-cl -Xclang -load -Xclang plugin.dll \ -Xclang -add-plugin -Xclang foo git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@260265 91177308-0d34-0410-b5e6-96231b3b80d8
Clang Plugins
Clang Plugins make it possible to run extra user defined actions during a compilation. This document will provide a basic walkthrough of how to write and run a Clang Plugin.
Introduction
Clang Plugins run FrontendActions over code. See the :doc:`FrontendAction
tutorial <RAVFrontendAction>` on how to write a FrontendAction
using the
RecursiveASTVisitor
. In this tutorial, we'll demonstrate how to write a
simple clang plugin.
Writing a PluginASTAction
The main difference from writing normal FrontendActions
is that you can
handle plugin command line options. The PluginASTAction
base class declares
a ParseArgs
method which you have to implement in your plugin.
bool ParseArgs(const CompilerInstance &CI,
const std::vector<std::string>& args) {
for (unsigned i = 0, e = args.size(); i != e; ++i) {
if (args[i] == "-some-arg") {
// Handle the command line argument.
}
}
return true;
}
Registering a plugin
A plugin is loaded from a dynamic library at runtime by the compiler. To
register a plugin in a library, use FrontendPluginRegistry::Add<>
.
On Windows, you also need to export your plugin registry using
LLVM_EXPORT_REGISTRY
. Here is an example:
static FrontendPluginRegistry::Add<MyPlugin> X("my-plugin-name", "my plugin description");
LLVM_EXPORT_REGISTRY(FrontendPluginRegistry)
Putting it all together
Let's look at an example plugin that prints top-level function names. This example is checked into the clang repository; please take a look at the latest version of PrintFunctionNames.cpp.
Running the plugin
To run a plugin, the dynamic library containing the plugin registry must be loaded via the :option:`-load` command line option. This will load all plugins that are registered, and you can select the plugins to run by specifying the :option:`-plugin` option. Additional parameters for the plugins can be passed with :option:`-plugin-arg-<plugin-name>`.
Note that those options must reach clang's cc1 process. There are two ways to do so: