xref: /llvm-project/flang/docs/FlangDriver.md (revision 06eb10dadfaeaadc5d0d95d38bea4bfb5253e077)
1<!--===- docs/FlangDriver.md
2
3   Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4   See https://llvm.org/LICENSE.txt for license information.
5   SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7-->
8
9# Flang drivers
10
11```{contents}
12---
13local:
14---
15```
16
17There are two main drivers in Flang:
18* the compiler driver, `flang`
19* the frontend driver, `flang -fc1`
20
21The **compiler driver** will allow you to control all compilation phases (e.g.
22preprocessing, semantic checks, code-generation, code-optimisation, lowering
23and linking). For frontend specific tasks, the compiler driver creates a
24Fortran compilation job and delegates it to `flang -fc1`, the frontend
25driver. For linking, it creates a linker job and calls an external linker (e.g.
26LLVM's [`lld`](https://lld.llvm.org/)). It can also call other tools such as
27external assemblers (e.g. [`as`](https://www.gnu.org/software/binutils/)). In
28Clang, the compiler driver can also link the generated binaries with LLVM's
29static analysis/sanitizer libraries (e.g.
30[MemorySanitizer](https://clang.llvm.org/docs/MemorySanitizer.html)). This is
31not yet available in Flang, but will be relatively easy to support once such
32libraries become available. Flang's compiler driver is intended for Flang's
33end-users - its interface needs to remain stable. Otherwise, Flang's users will
34have to adjust their build scripts every time a compiler flag is changed.
35
36| ![Compiler Driver](compiler_driver.png) |
37|:--:|
38| *Flang’s compiler driver and the **tools** that it runs* |
39
40The **frontend driver** glues together and drives all of the Flang's frontend
41libraries. As such, it provides an easy-to-use and intuitive interface to the
42frontend. It uses MLIR and LLVM for code-generation and can be viewed as a
43driver for Flang, LLVM and MLIR libraries. Contrary to the compiler driver, it
44is not capable of calling any external tools (including linkers).  It is aware
45of all the frontend internals that are "hidden" from the compiler driver. It
46accepts many frontend-specific options not available in `flang` and as such
47it provides a finer control over the frontend. Note that this tool is mostly
48intended for Flang developers. In particular, there are no guarantees about the
49stability of its interface and compiler developers can use it to experiment
50with new flags.
51
52| ![Frontend Driver](frontend_driver.png) |
53|:-:|
54| *Flang's frontend driver and the **libraries** that it drives* |
55
56Note that similarly to `-Xclang` in `clang`, you can use `-Xflang` to forward a
57frontend specific flag from the _compiler_ directly to the _frontend_ driver,
58e.g.:
59
60```bash
61flang -Xflang -fdebug-dump-parse-tree input.f95
62```
63
64In the invocation above, `-fdebug-dump-parse-tree` is forwarded to `flang
65-fc1`. Without the forwarding flag, `-Xflang`, you would see the following
66warning:
67
68```bash
69flang: warning: argument unused during compilation:
70```
71
72As `-fdebug-dump-parse-tree` is only supported by `flang -fc1`, `flang`
73will ignore it when used without `Xflang`.
74
75## Why Do We Need Two Drivers?
76As hinted above, `flang` and `flang -fc1` are two separate tools. The
77fact that these tools are accessed through one binary, `flang`, is just an
78implementation detail. Each tool has a separate list of options, albeit defined
79in the same file: `clang/include/clang/Driver/Options.td`.
80
81The separation helps us split various tasks and allows us to implement more
82specialised tools. In particular, `flang` is not aware of various
83compilation phases within the frontend (e.g. scanning, parsing or semantic
84checks). It does not have to be. Conversely, the frontend driver, `flang
85-fc1`, needs not to be concerned with linkers or other external tools like
86assemblers. Nor does it need to know where to look for various systems
87libraries, which is usually OS and platform specific.
88
89One helpful way of differentiating these tools is to keep in mind that:
90
91* the compiler driver is an end-user tool
92* frontend driver is a compiler developer tool with many additional options,
93
94Also, Since the compiler driver can call external tools, e.g. linkers, it can
95be used to generate **executables**. The frontend driver cannot call external
96tools and hence can only generate **object files**. A similar model is
97implemented in Clang (`clang` vs `clang -cc1` vs `clang -cc1as`), which is
98based on the [architecture of
99GCC](https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture).
100In fact, Flang needs to adhere to this model in order to be able to re-use
101Clang's driver library. If you are more familiar with the [architecture of
102GFortran](https://gcc.gnu.org/onlinedocs/gcc-4.7.4/gfortran/About-GNU-Fortran.html)
103than Clang, then `flang` corresponds to `gfortran` and `flang -fc1` to
104`f951`.
105
106## Compiler Driver
107The main entry point for Flang's compiler driver is implemented in
108`flang/tools/flang-driver/driver.cpp`.  Flang's compiler driver is implemented
109in terms of Clang's driver library, `clangDriver`. This approach allows us to:
110* benefit from Clang's support for various targets, platforms and operating systems
111* leverage Clang's ability to drive various backends available in LLVM, as well
112  as linkers and assemblers.
113One implication of this dependency on Clang is that all of Flang's compiler
114options are defined alongside Clang's options in
115`clang/include/clang/Driver/Options.td`. For options that are common for both
116Flang and Clang, the corresponding definitions are shared.
117
118Internally, a `clangDriver` based compiler driver works by creating actions
119that correspond to various compilation phases, e.g. `PreprocessJobClass`,
120`CompileJobClass`, `BackendJobClass` or `LinkJobClass` from the
121`clang::driver::Action::ActionClass` enum. There are also other, more
122specialised actions, e.g. `MigrateJobClass` or `InputClass`, that do not map
123directly to common compilation steps. The actions to run are determined from
124the supplied compiler flags, e.g.
125
126* `-E` for `PreprocessJobClass`,
127* `-c` for `CompileJobClass`.
128
129In most cases, the driver creates a chain of actions/jobs/phases where the
130output from one action is the input for the subsequent one. You can use the
131`-ccc-print-phases` flag to see the sequence of actions that the driver will
132create for your compiler invocation:
133```bash
134flang -ccc-print-phases -E file.f
135+- 0: input, "file.f", f95-cpp-input
1361: preprocessor, {0}, f95
137```
138As you can see, for `-E` the driver creates only two jobs and stops immediately
139after preprocessing. The first job simply prepares the input. For `-c`, the
140pipeline of the created jobs is more complex:
141```bash
142flang -ccc-print-phases -c file.f
143         +- 0: input, "file.f", f95-cpp-input
144      +- 1: preprocessor, {0}, f95
145   +- 2: compiler, {1}, ir
146+- 3: backend, {2}, assembler
1474: assembler, {3}, object
148```
149The other phases are printed nonetheless when using `-ccc-print-phases`, as
150that reflects what `clangDriver`, the library, will try to create and run.
151
152For actions specific to the frontend (e.g. preprocessing or code generation), a
153command to call the frontend driver is generated (more specifically, an
154instance of `clang::driver::Command`). Every command is bound to an instance of
155`clang::driver::Tool`. For Flang we introduced a specialisation of this class:
156`clang::driver::Flang`. This class implements the logic to either translate or
157forward compiler options to the frontend driver, `flang -fc1`.
158
159You can read more on the design of `clangDriver` in Clang's [Driver Design &
160Internals](https://clang.llvm.org/docs/DriverInternals.html).
161
162## Linker Driver
163When used as a linker, Flang's frontend driver assembles the command line for an
164external linker command (e.g., LLVM's `lld`) and invokes it to create the final
165executable by linking static and shared libraries together with all the
166translation units supplied as object files.
167
168By default, the Flang linker driver adds several libraries to the linker
169invocation to make sure that all entrypoints for program start
170(Fortran's program unit) and runtime routines can be resolved by the linker.
171
172An abridged example (only showing the Fortran specific linker flags, omission
173indicated by `[...]`) for such a linker invocation on a Linux system would look
174like this:
175
176```
177$ flang -v -o example example.o
178"/usr/bin/ld" [...] example.o [...] "-lFortranRuntime" "-lFortranDecimal" [...]
179```
180
181The automatically added libraries are:
182
183* `FortranRuntime`: Provides most of the Flang runtime library.
184* `FortranDecimal`: Provides operations for decimal numbers.
185
186If the code is C/C++ based and invokes Fortran routines, one can either use Clang
187or Flang as the linker driver.  If Clang is used, it will automatically all
188required runtime libraries needed by C++ (e.g., for STL) to the linker invocation.
189In this case, one has to explicitly provide the Fortran runtime libraries
190`FortranRuntime` and/or `FortranDecimal`.  An alternative is to use Flang to link.
191In this case, it may be required to explicitly supply C++ runtime libraries.
192
193On Darwin, the logical root where the system libraries are located (sysroot)
194must be specified. This can be done with the CMake build flag `DEFAULT_SYSROOT`
195or by using the `-isysroot` flag when linking a binary. On other targets
196`-isysroot` doesn't change the linker command line (it only affects the header
197search path). While with Clang `-isysroot` also changes the sysroot for
198includes, with Flang (and Fortran in general) it only affects Darwin libraries'
199sysroot.
200
201## Frontend Driver
202Flang's frontend driver is the main interface between compiler developers and
203the Flang frontend. The high-level design is similar to Clang's frontend
204driver, `clang -cc1` and consists of the following classes:
205* `CompilerInstance`, which is a helper class that encapsulates and manages
206  various objects that are always required by the frontend (e.g. `AllSources`,
207  `AllCookedSources, `Parsing`, `CompilerInvocation`, etc.). In most cases
208  `CompilerInstance` owns these objects, but it also can share them with its
209  clients when required. It also implements utility methods to construct and
210  manipulate them.
211* `CompilerInvocation` encapsulates the configuration of the current
212  invocation of the compiler as derived from the command-line options and the
213  input files (in particular, file extensions). Among other things, it holds an
214  instance of `FrontendOptions`. Like `CompilerInstance`, it owns the objects
215  that it manages. It can share them with its clients that want to access them
216  even after the corresponding `CompilerInvocation` has been destructed.
217* `FrontendOptions` holds options that control the behaviour of the frontend,
218  as well as e.g. the list of the input files. These options come either
219  directly from the users (through command-line flags) or are derived from
220  e.g. the host system configuration.
221* `FrontendAction` and `FrontendActions` (the former being the base class for
222  the latter) implement the actual actions to perform by the frontend. Usually
223  there is one specialisation of `FrontendActions` for every compiler action flag
224  (e.g. `-E`, `-fdebug-unparse`). These classes also contain various hooks that
225  allow you to e.g. fine-tune the configuration of the frontend based on the
226  input.
227
228This list is not exhaustive and only covers the main classes that implement the
229driver. The main entry point for the frontend driver, `fc1_main`, is
230implemented in `flang/tools/flang-driver/driver.cpp`. It can be accessed by
231invoking the compiler driver, `flang`, with the `-fc1` flag.
232
233The frontend driver will only run one action at a time. If you specify multiple
234action flags, only the last one will be taken into account. The default action
235is `ParseSyntaxOnlyAction`, which corresponds to `-fsyntax-only`. In other
236words, `flang -fc1 <input-file>` is equivalent to `flang -fc1 -fsyntax-only
237<input-file>`.
238
239## Adding new Compiler Options
240Adding a new compiler option in Flang consists of two steps:
241* define the new option in a dedicated TableGen file,
242* parse and implement the option in the relevant drivers that support it.
243
244### Option Definition
245All of Flang's compiler and frontend driver options are defined in
246`clang/include/clang/Driver/Options.td` in Clang. When adding a new option to
247Flang, you will either:
248  * extend the existing definition for an option that is already available
249    in one of Clang's drivers (e.g.  `clang`), but not yet available in Flang, or
250  * add a completely new definition if the option that you are adding has not
251    been defined yet.
252
253There are many predefined TableGen classes and records that you can use to fine
254tune your new option. The list of available configurations can be overwhelming
255at times. Sometimes the easiest approach is to find an existing option that has
256similar semantics to your new option and start by copying that.
257
258For every new option, you will also have to define the visibility of the new
259option. This is controlled through the `Visibility` field. You can use the
260following Flang specific visibility flags to control this:
261  * `FlangOption` - this option will be available in the `flang` compiler driver,
262  * `FC1Option` - this option will be available in the `flang -fc1` frontend driver,
263
264Options that are supported by clang should explicitly specify `ClangOption` in
265`Visibility`, and options that are only supported in Flang should not specify
266`ClangOption`.
267
268When deciding what `OptionGroup` to use when defining a new option in the
269`Options.td` file, many new options fall into one of the following two
270categories:
271  * `Action_Group` - options that define an action to run (e.g.
272    `-fsyntax-only`, `-E`)
273  * `f_Group` - target independent compiler flags (e.g. `-ffixed-form`,
274    `-fopenmp`)
275There are also other groups and occasionally you will use them instead of the
276groups listed above.
277
278### Option Implementation
279First, every option needs to be parsed. Flang compiler options are parsed in
280two different places, depending on which driver they belong to:
281
282* frontend driver: `flang/lib/Frontend/CompilerInvocation.cpp`,
283* compiler driver: `clang/lib/Driver/ToolChains/Flang.cpp`.
284
285The parsing will depend on the semantics encoded in the TableGen definition.
286
287When adding a compiler driver option (i.e. an option that contains
288`FlangOption` among in it's `Visibility`) that you also intend to be understood
289by the frontend, make sure that it is either forwarded to `flang -fc1` or
290translated into some other option that is accepted by the frontend driver. In
291the case of options that contain both `FlangOption` and `FC1Option` among its
292flags, we usually just forward from `flang` to `flang -fc1`. This is
293then tested in `flang/test/Driver/frontend-forward.F90`.
294
295What follows is usually very dependant on the meaning of the corresponding
296option. In general, regular compiler flags (e.g. `-ffree-form`) are mapped to
297some state within the driver. A lot of this state is stored within an instance
298of `FrontendOptions`, but there are other more specialised classes too. Action
299flags (e.g. `-fsyntax-only`) are usually more complex overall, but also more
300structured in terms of the implementation.
301
302### Action Options
303For options that correspond to an action (i.e. marked as `Action_Group`), you
304will have to define a dedicated instance of `FrontendActions` in
305`flang/include/flang/Frontend/FrontendOptions.h`. For example, for
306`-fsyntax-only` we defined:
307```cpp
308class ParseSyntaxOnlyAction : public PrescanAndSemaAction {
309  void ExecuteAction() override;
310};
311```
312Command line options are mapped to frontend actions through the
313`Fortran::frontend::ActionKind` enum.  For every new action option that you
314add, you will have to add a dedicated entry in that enum (e.g.
315`ParseSyntaxOnly` for `-fsyntax-only`) and a corresponding `case` in
316`ParseFrontendArgs` function in the `CompilerInvocation.cpp` file, e.g.:
317```cpp
318    case clang::driver::options::OPT_fsyntax_only:
319      opts.programAction = ParseSyntaxOnly;
320      break;
321```
322Note that this simply sets the program/frontend action within the frontend
323driver. You still have make sure that the corresponding frontend action class
324is instantiated when your new action option is used. The relevant `switch`
325statement is implemented in `Fortran::frontend::CreatedFrontendBaseAction` in
326the `ExecuteCompilerInvocation.cpp` file. Here's an example for
327`-fsyntax-only`:
328```cpp
329  case ParseSyntaxOnly:
330    return std::make_unique<ParseSyntaxOnlyAction>();
331```
332At this point you should be able to trigger that frontend action that you have
333just added using your new frontend option.
334
335
336## CMake Support
337As of [#7246](https://gitlab.kitware.com/cmake/cmake/-/merge_requests/7246)
338(CMake 3.28.0), `cmake` can detect `flang` as a
339supported Fortran compiler. You can configure your CMake projects to use
340`flang` as follows:
341```bash
342cmake -DCMAKE_Fortran_COMPILER=<path/to/flang> <src/dir>
343```
344You should see the following in the output:
345```
346-- The Fortran compiler identification is LLVMFlang <version>
347```
348where `<version>` corresponds to the LLVM Flang version.
349
350## Testing
351In LIT, we define two variables that you can use to invoke Flang's drivers:
352* `%flang` is expanded as `flang` (i.e. the compiler driver)
353* `%flang_fc1` is expanded as `flang -fc1` (i.e. the frontend driver)
354
355For most regression tests for the frontend, you will want to use `%flang_fc1`.
356In some cases, the observable behaviour will be identical regardless of whether
357`%flang` or `%flang_fc1` is used. However, when you are using `%flang` instead
358of `%flang_fc1`, the compiler driver will add extra flags to the frontend
359driver invocation (i.e. `flang -fc1 -<extra-flags>`). In some cases that might
360be exactly what you want to test.  In fact, you can check these additional
361flags by using the `-###` compiler driver command line option.
362
363Lastly, you can use `! REQUIRES: <feature>` for tests that will only work when
364`<feature>` is available. For example, you can use`! REQUIRES: shell` to mark a
365test as only available on Unix-like systems (i.e. systems that contain a Unix
366shell). In practice this means that the corresponding test is skipped on
367Windows.
368
369## Frontend Driver Plugins
370Plugins are an extension to the frontend driver that make it possible to run
371extra user defined frontend actions, in the form of a specialization of a
372`PluginParseTreeAction`. These actions are run during compilation, after
373semantic checks. Similarly to Clang, Flang leverages `LoadLibraryPermanently`
374from LLVM's `llvm::sys::DynamicLibrary` to load dynamic objects that implement
375plugins. The process for using plugins includes:
376* [Creating a plugin](#creating-a-plugin)
377* [Loading and running a plugin](#loading-and-running-a-plugin)
378
379Flang plugins are limited to `flang -fc1` and are currently only available /
380been tested on Linux.
381
382### Creating a Plugin
383There are three parts required for plugins to work:
3841. [`PluginParseTreeAction` subclass](#a-pluginparsetreeaction-subclass)
3851. [Implementation of `ExecuteAction`](#implementation-of-executeaction)
3861. [Plugin registration](#plugin-registration)
387
388There is an example plugin located in `flang/example/PrintFlangFunctionNames`
389that demonstrates these points by using the `ParseTree` API to print out
390function and subroutine names declared in the input file.
391
392#### A `PluginParseTreeAction` Subclass
393This subclass will wrap everything together and represent the `FrontendAction`
394corresponding to your plugin. It will need to inherit from
395`PluginParseTreeAction` (defined in `flang/include/flang/FrontendActions.h`), in
396order to have access to the parse tree post semantic checks, and also so that it
397can be registered, e.g.
398```cpp
399class PrintFunctionNamesAction : public PluginParseTreeAction
400```
401
402#### Implementation of `ExecuteAction`
403Like in other frontend actions, the driver looks for an `ExecuteAction` function
404to run, so in order for your plugin to do something, you will need to implement
405the `ExecuteAction` method in your plugin class. This method will contain the
406implementation of what the plugin actually does, for example:
407```cpp
408// Forward declaration
409struct ParseTreeVisitor;
410
411void ExecuteAction() override {
412  ParseTreeVisitor visitor;
413  Fortran::parser::Walk(getParsing().parseTree(), visitor);
414}
415```
416In the example plugin, the `ExecuteAction` method first creates an instance of
417`visitor` struct, before passing it together with the parse tree to the
418`Fortran::parser::Walk` function that will traverse the parse tree. The parse
419tree will normally be generated by the frontend driver and can be retrieved in
420your plugin through the `getParsing()` member method. Implementation and
421details of the `Walk` function can be found in
422`flang/include/flang/Parser/parse-tree-visitor.h`.
423
424You will have to define your own `visitor` struct. It should define different
425`Pre` and `Post` functions that take the type of a specific `ParseTree` node as
426an argument. When the `Walk` function is traversing the parse tree, these
427functions will be run before/after a node of that type is visited. Template
428functions for `Pre`/`Post` are defined so that when a node is visited that you
429have not defined a function for, it will still be able to continue. `Pre`
430returns a `bool` indicating whether to visit that node's children or not. For
431example:
432```cpp
433struct ParseTreeVisitor {
434  template <typename A> bool Pre(const A&) { return true; }
435  template <typename A> void Post(const A&) {}
436  void Post(const Fortran::parser::FunctionStmt &f) {
437    llvm::outs() << std::get<Fortran::parser::Name>(f.t).ToString() << "\n" ;
438  }
439}
440```
441The different types of nodes and also what each node structure contains are
442defined in `flang/include/flang/Parser/parse-tree.h`. In the example, there is a
443`Post` function, with a line that gets the `Name` element from a tuple `t` in
444the `FunctionStmt` struct and prints it. This function will be run after every
445`FunctionStmt` node is visited in the parse tree.
446
447#### Plugin Registration
448A plugin registry is used to store names and descriptions of a collection of
449plugins. The Flang plugin registry, defined in
450`flang/include/flang/Frontend/FrontendPluginRegistry.h`, is an alias of
451`llvm::Registry` of type `PluginParseTreeAction`.
452
453The plugin will need to be registered, which will add the Plugin to the registry
454and allow it to be used. The format is as follows, with `print-fns` being the
455plugin name that is used later to call the plugin and `Print Function names`
456being the description:
457```cpp
458static FrontendPluginRegistry::Add<PrintFunctionNamesAction> X(
459    "print-fns", "Print Function names");
460```
461
462### Loading and Running a Plugin
463In order to use plugins, there are 2 command line options made available to the
464frontend driver, `flang -fc1`:
465* [`-load <dsopath>`](#the--load-dsopath-option) for loading the dynamic shared
466  object of the plugin
467* [`-plugin <name>`](#the--plugin-name-option) for calling the registered plugin
468
469Invocation of the example plugin is done through:
470```bash
471flang -fc1 -load flangPrintFunctionNames.so -plugin print-fns file.f90
472```
473
474Both these options are parsed in `flang/lib/Frontend/CompilerInvocation.cpp` and
475fulfil their actions in
476`flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp`
477
478#### The `-load <dsopath>` option
479This loads the plugin shared object library, with the path given at `<dsopath>`,
480using `LoadLibraryPermantly` from LLVM's `llvm::sys::DynamicLibrary`, which
481itself uses `dlopen`. During this stage, the plugin is registered with the
482registration line from the plugin, storing the name and description.
483
484#### The `-plugin <name>` option
485This sets `frontend::ActionKind programAction` in `FrontendOptions` to
486`PluginAction`, through which it searches the plugin registry for the plugin
487name from `<name>`. If found, it returns the instantiated plugin, otherwise it
488reports an error diagnostic and returns `nullptr`.
489
490### Enabling In-Tree Plugins
491For in-tree plugins, there is the CMake flag `FLANG_PLUGIN_SUPPORT`, enabled by
492default, that controls the exporting of executable symbols from `flang`,
493which plugins need access to. Additionally, there is the CMake flag
494`LLVM_BUILD_EXAMPLES`, turned off by default, that is used to control if the
495example programs are built. This includes plugins that are in the
496`flang/example` directory and added as a `sub_directory` to the
497`flang/examples/CMakeLists.txt`, for example, the `PrintFlangFunctionNames`
498plugin. It is also possible to develop plugins out-of-tree.
499
500### Limitations
501Note that the traversal API presented here is under active development and
502might change in the future. We expect it to evolve as support for new
503language features are added. This document and the examples will be updated
504accordingly.
505
506The current `ParseTree` structure is not suitable for modifications. The
507copy constructors are not available and hence duplicating code might not be
508trivial. Please take this into consideration when designing your plugin. In
509particular, creating a transformation plugin will be noticeably harder than
510analysis plugins that just consume (rather than edit) `ParseTree`.
511
512Lastly, if `ParseTree` modifications are performed, then it might be necessary
513to re-analyze expressions and modify scope or symbols. You can check
514[Semantics.md](Semantics.md) for more details on how `ParseTree` is edited
515e.g. during the semantic checks.
516
517## FIR Optimizer Pass Pipeline Extension Points
518
519The default FIR optimizer pass pipeline `createDefaultFIROptimizerPassPipeline`
520in `flang/lib/Optimizer/Passes/Pipelines.cpp` contains extension point callback
521invocations `invokeFIROptEarlyEPCallbacks`, `invokeFIRInlinerCallback`, and
522`invokeFIROptLastEPCallbacks` for Flang drivers to be able to insert additonal
523passes at different points of the default pass pipeline. An example use of these
524extension point callbacks is shown in `registerDefaultInlinerPass` to invoke the
525default inliner pass in `flang`.
526
527## LLVM Pass Plugins
528
529Pass plugins are dynamic shared objects that consist of one or more LLVM IR
530passes. The `-fpass-plugin` option enables these passes to be passed to the
531middle-end where they are added to the optimization pass pipeline and run after
532lowering to LLVM IR.The exact position of the pass in the pipeline will depend
533on how it has been registered with the `llvm::PassBuilder`. See the
534documentation for
535[`llvm::PassBuilder`](https://llvm.org/doxygen/classllvm_1_1PassBuilder.html)
536for details.
537
538The framework to enable pass plugins in `flang` uses the exact same
539machinery as that used by `clang` and thus has the same capabilities and
540limitations.
541
542In order to use a pass plugin, the pass(es) must be compiled into a dynamic
543shared object which is then loaded using the `-fpass-plugin` option.
544
545```
546flang -fpass-plugin=/path/to/plugin.so <file.f90>
547```
548
549This option is available in both the compiler driver and the frontend driver.
550Note that LLVM plugins are not officially supported on Windows.
551
552## LLVM Pass Extensions
553
554Pass extensions are similar to plugins, except that they can also be linked
555statically. Setting `-DLLVM_${NAME}_LINK_INTO_TOOLS` to `ON` in the cmake
556command turns the project into a statically linked extension. An example would
557be Polly, e.g., using `-DLLVM_POLLY_LINK_INTO_TOOLS=ON` would link Polly passes
558into `flang` as built-in middle-end passes.
559
560See the
561[`WritingAnLLVMNewPMPass`](https://llvm.org/docs/WritingAnLLVMNewPMPass.html#id9)
562documentation for more details.
563
564## Ofast and Fast Math
565`-Ofast` in Flang means `-O3 -ffast-math -fstack-arrays`.
566
567`-ffast-math` means the following:
568 - `-fno-honor-infinities`
569 - `-fno-honor-nans`
570 - `-fassociative-math`
571 - `-freciprocal-math`
572 - `-fapprox-func`
573 - `-fno-signed-zeros`
574 - `-ffp-contract=fast`
575
576These correspond to LLVM IR Fast Math attributes:
577https://llvm.org/docs/LangRef.html#fast-math-flags
578
579When `-ffast-math` is specified, any linker steps generated by the compiler
580driver will also link to `crtfastmath.o`, which adds a static constructor
581that sets the FTZ/DAZ bits in MXCSR, affecting not only the current only the
582current compilation unit but all static and shared libraries included in the
583program. Setting these bits causes denormal floating point numbers to be flushed
584to zero.
585
586### Comparison with GCC/GFortran
587GCC/GFortran translate `-Ofast` to
588`-O3 -ffast-math -fstack-arrays -fno-semantic-interposition`.
589`-fno-semantic-interposition` is not used because Clang does not enable this as
590part of `-Ofast` as the default behaviour is similar.
591
592GCC/GFortran has a wider definition of `-ffast-math`: also including
593`-fno-trapping-math`,  `-fno-rounding-math`, and  `-fsignaling-nans`; these
594aren't included in Flang because Flang currently has no support for strict
595floating point and so always acts as though these flags were specified.
596
597GCC/GFortran will also set flush-to-zero mode: linking `crtfastmath.o`, the same
598as Flang.
599
600The only GCC/GFortran warning option currently supported is `-Werror`.  Passing
601any unsupported GCC/GFortran warning flags into Flang's compiler driver will
602result in warnings being emitted.
603
604### Comparison with nvfortran
605nvfortran defines `-fast` as
606`-O2 -Munroll=c:1 -Mnoframe -Mlre -Mpre -Mvect=simd -Mcache_align -Mflushz -Mvect`.
607 - `-O2 -Munroll=c:1 -Mlre -Mautoinline -Mpre -Mvect-simd` affect code
608   optimization. `flang -O3` should enable all optimizations for execution time,
609   similarly to `clang -O3`. The `-O3` pipeline has passes that perform
610   transformations like inlining, vectorisation, unrolling, etc. Additionally,
611   the GVN and LICM passes perform redundancy elimination like `Mpre` and `Mlre`
612 - `-Mnoframe`: the equivalent flag would be `-fomit-frame-pointer`. This flag
613   is not yet supported in Flang and so Flang follows GFortran in not including
614   this in `-Ofast`. There is no plan to include this flag as part of `-Ofast`.
615 - `-Mcache_align`: there is no equivalent flag in Flang or Clang.
616 - `-Mflushz`: flush-to-zero mode - when `-ffast-math` is specified, Flang will
617   link to `crtfastmath.o` to ensure denormal numbers are flushed to zero.
618