Next: , Previous: Type Information, Up: Top

23 Plugins

23.1 Loading Plugins

Plugins are supported on platforms that support -ldl -rdynamic. They are loaded by the compiler using dlopen and invoked at pre-determined locations in the compilation process.

Plugins are loaded with

-fplugin=/path/to/ -fplugin-arg-name-key1[=value1]

The plugin arguments are parsed by GCC and passed to respective plugins as key-value pairs. Multiple plugins can be invoked by specifying multiple -fplugin arguments.

A plugin can be simply given by its short name (no dots or slashes). When simply passing -fplugin=name, the plugin is loaded from the plugin directory, so -fplugin=name is the same as -fplugin=`gcc -print-file-name=plugin`/, using backquote shell syntax to query the plugin directory.

23.2 Plugin API

Plugins are activated by the compiler at specific events as defined in gcc-plugin.h. For each event of interest, the plugin should call register_callback specifying the name of the event and address of the callback function that will handle that event.

The header gcc-plugin.h must be the first gcc header to be included.

23.2.1 Plugin license check

Every plugin should define the global symbol plugin_is_GPL_compatible to assert that it has been licensed under a GPL-compatible license. If this symbol does not exist, the compiler will emit a fatal error and exit with the error message:

     fatal error: plugin name is not licensed under a GPL-compatible license
     name: undefined symbol: plugin_is_GPL_compatible
     compilation terminated

The declared type of the symbol should be int, to match a forward declaration in gcc-plugin.h that suppresses C++ mangling. It does not need to be in any allocated section, though. The compiler merely asserts that the symbol exists in the global scope. Something like this is enough:

     int plugin_is_GPL_compatible;

23.2.2 Plugin initialization

Every plugin should export a function called plugin_init that is called right after the plugin is loaded. This function is responsible for registering all the callbacks required by the plugin and do any other required initialization.

This function is called from compile_file right before invoking the parser. The arguments to plugin_init are:

The plugin_info struct is defined as follows:

     struct plugin_name_args
       char *base_name;              /* Short name of the plugin
                                        (filename without .so suffix). */
       const char *full_name;        /* Path to the plugin as specified with
                                        -fplugin=. */
       int argc;                     /* Number of arguments specified with
                                        -fplugin-arg-.... */
       struct plugin_argument *argv; /* Array of ARGC key-value pairs. */
       const char *version;          /* Version string provided by plugin. */
       const char *help;             /* Help string provided by plugin. */

If initialization fails, plugin_init must return a non-zero value. Otherwise, it should return 0.

The version of the GCC compiler loading the plugin is described by the following structure:

     struct plugin_gcc_version
       const char *basever;
       const char *datestamp;
       const char *devphase;
       const char *revision;
       const char *configuration_arguments;

The function plugin_default_version_check takes two pointers to such structure and compare them field by field. It can be used by the plugin's plugin_init function.

The version of GCC used to compile the plugin can be found in the symbol gcc_version defined in the header plugin-version.h. The recommended version check to perform looks like

     #include "plugin-version.h"
     plugin_init (struct plugin_name_args *plugin_info,
                  struct plugin_gcc_version *version)
       if (!plugin_default_version_check (version, &gcc_version))
         return 1;

but you can also check the individual fields if you want a less strict check.

23.2.3 Plugin callbacks

Callback functions have the following prototype:

     /* The prototype for a plugin callback function.
          gcc_data  - event-specific data provided by GCC
          user_data - plugin-specific data provided by the plug-in.  */
     typedef void (*plugin_callback_func)(void *gcc_data, void *user_data);

Callbacks can be invoked at the following pre-determined events:

     enum plugin_event
       PLUGIN_PASS_MANAGER_SETUP,    /* To hook into pass manager.  */
       PLUGIN_FINISH_TYPE,           /* After finishing parsing a type.  */
       PLUGIN_FINISH_UNIT,           /* Useful for summary processing.  */
       PLUGIN_PRE_GENERICIZE,        /* Allows to see low level AST in C and C++ frontends.  */
       PLUGIN_FINISH,                /* Called before GCC exits.  */
       PLUGIN_INFO,                  /* Information about the plugin. */
       PLUGIN_GGC_START,             /* Called at start of GCC Garbage Collection. */
       PLUGIN_GGC_MARKING,           /* Extend the GGC marking. */
       PLUGIN_GGC_END,               /* Called at end of GGC. */
       PLUGIN_REGISTER_GGC_ROOTS,    /* Register an extra GGC root table. */
       PLUGIN_REGISTER_GGC_CACHES,   /* Register an extra GGC cache table. */
       PLUGIN_ATTRIBUTES,            /* Called during attribute registration */
       PLUGIN_START_UNIT,            /* Called before processing a translation unit.  */
       PLUGIN_PRAGMAS,               /* Called during pragma registration. */
       /* Called before first pass from all_passes.  */
       /* Called after last pass from all_passes.  */
       /* Called before first ipa pass.  */
       /* Called after last ipa pass.  */
       /* Allows to override pass gate decision for current_pass.  */
       /* Called before executing a pass.  */
       /* Called before executing subpasses of a GIMPLE_PASS in
          execute_ipa_pass_list.  */
       /* Called after executing subpasses of a GIMPLE_PASS in
          execute_ipa_pass_list.  */
       /* Called when a pass is first instantiated.  */
       PLUGIN_EVENT_FIRST_DYNAMIC    /* Dummy event used for indexing callback
                                        array.  */

In addition, plugins can also look up the enumerator of a named event, and / or generate new events dynamically, by calling the function get_named_event_id.

To register a callback, the plugin calls register_callback with the arguments:

For the PLUGIN_PASS_MANAGER_SETUP, PLUGIN_INFO, PLUGIN_REGISTER_GGC_ROOTS and PLUGIN_REGISTER_GGC_CACHES pseudo-events the callback should be null, and the user_data is specific.

When the PLUGIN_PRAGMAS event is triggered (with a null pointer as data from GCC), plugins may register their own pragmas using functions like c_register_pragma or c_register_pragma_with_expansion.

23.3 Interacting with the pass manager

There needs to be a way to add/reorder/remove passes dynamically. This is useful for both analysis plugins (plugging in after a certain pass such as CFG or an IPA pass) and optimization plugins.

Basic support for inserting new passes or replacing existing passes is provided. A plugin registers a new pass with GCC by calling register_callback with the PLUGIN_PASS_MANAGER_SETUP event and a pointer to a struct register_pass_info object defined as follows

     enum pass_positioning_ops
       PASS_POS_INSERT_AFTER,  // Insert after the reference pass.
       PASS_POS_INSERT_BEFORE, // Insert before the reference pass.
       PASS_POS_REPLACE        // Replace the reference pass.
     struct register_pass_info
       struct opt_pass *pass;            /* New pass provided by the plugin.  */
       const char *reference_pass_name;  /* Name of the reference pass for hooking
                                            up the new pass.  */
       int ref_pass_instance_number;     /* Insert the pass at the specified
                                            instance number of the reference pass.  */
                                         /* Do it for every instance if it is 0.  */
       enum pass_positioning_ops pos_op; /* how to insert the new pass.  */
     /* Sample plugin code that registers a new pass.  */
     plugin_init (struct plugin_name_args *plugin_info,
                  struct plugin_gcc_version *version)
       struct register_pass_info pass_info;
       /* Code to fill in the pass_info object with new pass information.  */
       /* Register the new pass.  */
       register_callback (plugin_info->base_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &pass_info);

23.4 Interacting with the GCC Garbage Collector

Some plugins may want to be informed when GGC (the GCC Garbage Collector) is running. They can register callbacks for the PLUGIN_GGC_START and PLUGIN_GGC_END events (for which the callback is called with a null gcc_data) to be notified of the start or end of the GCC garbage collection.

Some plugins may need to have GGC mark additional data. This can be done by registering a callback (called with a null gcc_data) for the PLUGIN_GGC_MARKING event. Such callbacks can call the ggc_set_mark routine, preferably thru the ggc_mark macro (and conversely, these routines should usually not be used in plugins outside of the PLUGIN_GGC_MARKING event).

Some plugins may need to add extra GGC root tables, e.g. to handle their own GTY-ed data. This can be done with the PLUGIN_REGISTER_GGC_ROOTS pseudo-event with a null callback and the extra root table (of type struct ggc_root_tab*) as user_data. Plugins that want to use the if_marked hash table option can add the extra GGC cache tables generated by gengtype using the PLUGIN_REGISTER_GGC_CACHES pseudo-event with a null callback and the extra cache table (of type struct ggc_cache_tab*) as user_data. Running the gengtype -p source-dir file-list plugin*.c ... utility generates these extra root tables.

You should understand the details of memory management inside GCC before using PLUGIN_GGC_MARKING, PLUGIN_REGISTER_GGC_ROOTS or PLUGIN_REGISTER_GGC_CACHES.

23.5 Giving information about a plugin

A plugin should give some information to the user about itself. This uses the following structure:

     struct plugin_info
       const char *version;
       const char *help;

Such a structure is passed as the user_data by the plugin's init routine using register_callback with the PLUGIN_INFO pseudo-event and a null callback.

23.6 Registering custom attributes or pragmas

For analysis (or other) purposes it is useful to be able to add custom attributes or pragmas.

The PLUGIN_ATTRIBUTES callback is called during attribute registration. Use the register_attribute function to register custom attributes.

     /* Attribute handler callback */
     static tree
     handle_user_attribute (tree *node, tree name, tree args,
                            int flags, bool *no_add_attrs)
       return NULL_TREE;
     /* Attribute definition */
     static struct attribute_spec user_attr =
       { "user", 1, 1, false,  false, false, handle_user_attribute };
     /* Plugin callback called during attribute registration.
     Registered with register_callback (plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL)
     static void
     register_attributes (void *event_data, void *data)
       warning (0, G_("Callback to register attributes"));
       register_attribute (&user_attr);

The PLUGIN_PRAGMAS callback is called during pragmas registration. Use the c_register_pragma or c_register_pragma_with_expansion functions to register custom pragmas.

     /* Plugin callback called during pragmas registration. Registered with
          register_callback (plugin_name, PLUGIN_PRAGMAS,
                             register_my_pragma, NULL);
     static void
     register_my_pragma (void *event_data, void *data)
       warning (0, G_("Callback to register pragmas"));
       c_register_pragma ("GCCPLUGIN", "sayhello", handle_pragma_sayhello);

It is suggested to pass "GCCPLUGIN" (or a short name identifying your plugin) as the “space” argument of your pragma.

23.7 Recording information about pass execution

The event PLUGIN_PASS_EXECUTION passes the pointer to the executed pass (the same as current_pass) as gcc_data to the callback. You can also inspect cfun to find out about which function this pass is executed for. Note that this event will only be invoked if the gate check (if applicable, modified by PLUGIN_OVERRIDE_GATE) succeeds. You can use other hooks, like PLUGIN_ALL_PASSES_START, PLUGIN_ALL_PASSES_END, PLUGIN_ALL_IPA_PASSES_START, PLUGIN_ALL_IPA_PASSES_END, PLUGIN_EARLY_GIMPLE_PASSES_START, and/or PLUGIN_EARLY_GIMPLE_PASSES_END to manipulate global state in your plugin(s) in order to get context for the pass execution.

23.8 Controlling which passes are being run

After the original gate function for a pass is called, its result - the gate status - is stored as an integer. Then the event PLUGIN_OVERRIDE_GATE is invoked, with a pointer to the gate status in the gcc_data parameter to the callback function. A nonzero value of the gate status means that the pass is to be executed. You can both read and write the gate status via the passed pointer.

23.9 Keeping track of available passes

When your plugin is loaded, you can inspect the various pass lists to determine what passes are available. However, other plugins might add new passes. Also, future changes to GCC might cause generic passes to be added after plugin loading. When a pass is first added to one of the pass lists, the event PLUGIN_NEW_PASS is invoked, with the callback parameter gcc_data pointing to the new pass.

23.10 Building GCC plugins

If plugins are enabled, GCC installs the headers needed to build a plugin (somewhere in the installation tree, e.g. under /usr/local). In particular a plugin/include directory is installed, containing all the header files needed to build plugins.

On most systems, you can query this plugin directory by invoking gcc -print-file-name=plugin (replace if needed gcc with the appropriate program path).

Inside plugins, this plugin directory name can be queried by calling default_plugin_dir_name ().

The following GNU Makefile excerpt shows how to build a simple plugin:

     PLUGIN_SOURCE_FILES= plugin1.c plugin2.c
     PLUGIN_OBJECT_FILES= $(patsubst %.c,%.o,$(PLUGIN_SOURCE_FILES))
     GCCPLUGINS_DIR:= $(shell $(GCC) -print-file-name=plugin)
     CFLAGS+= -I$(GCCPLUGINS_DIR)/include -fPIC -O2
        $(GCC) -shared $^ -o $@

A single source file plugin may be built with gcc -I`gcc -print-file-name=plugin`/include -fPIC -shared -O2 plugin.c -o, using backquote shell syntax to query the plugin directory.

Plugins needing to use gengtype require a GCC build directory for the same version of GCC that they will be linked against.