More cosmetic tweaks for llvmc docs.
[oota-llvm.git] / tools / llvmc / doc / LLVMC-Reference.rst
1 ===================================
2 Customizing LLVMC: Reference Manual
3 ===================================
4
5 .. contents::
6
7 .. raw:: html
8
9    <div class="doc_author">
10    <p>Written by <a href="mailto:foldr@codedgers.com">Mikhail Glushenkov</a></p>
11    </div>
12
13 Introduction
14 ============
15
16 LLVMC is a generic compiler driver, designed to be customizable and
17 extensible. It plays the same role for LLVM as the ``gcc`` program
18 does for GCC - LLVMC's job is essentially to transform a set of input
19 files into a set of targets depending on configuration rules and user
20 options. What makes LLVMC different is that these transformation rules
21 are completely customizable - in fact, LLVMC knows nothing about the
22 specifics of transformation (even the command-line options are mostly
23 not hard-coded) and regards the transformation structure as an
24 abstract graph. The structure of this graph is completely determined
25 by plugins, which can be either statically or dynamically linked. This
26 makes it possible to easily adapt LLVMC for other purposes - for
27 example, as a build tool for game resources.
28
29 Because LLVMC employs TableGen_ as its configuration language, you
30 need to be familiar with it to customize LLVMC.
31
32 .. _TableGen: http://llvm.cs.uiuc.edu/docs/TableGenFundamentals.html
33
34
35 Compiling with LLVMC
36 ====================
37
38 LLVMC tries hard to be as compatible with ``gcc`` as possible,
39 although there are some small differences. Most of the time, however,
40 you shouldn't be able to notice them::
41
42      $ # This works as expected:
43      $ llvmc -O3 -Wall hello.cpp
44      $ ./a.out
45      hello
46
47 One nice feature of LLVMC is that one doesn't have to distinguish
48 between different compilers for different languages (think ``g++`` and
49 ``gcc``) - the right toolchain is chosen automatically based on input
50 language names (which are, in turn, determined from file
51 extensions). If you want to force files ending with ".c" to compile as
52 C++, use the ``-x`` option, just like you would do it with ``gcc``::
53
54       $ # hello.c is really a C++ file
55       $ llvmc -x c++ hello.c
56       $ ./a.out
57       hello
58
59 On the other hand, when using LLVMC as a linker to combine several C++
60 object files you should provide the ``--linker`` option since it's
61 impossible for LLVMC to choose the right linker in that case::
62
63     $ llvmc -c hello.cpp
64     $ llvmc hello.o
65     [A lot of link-time errors skipped]
66     $ llvmc --linker=c++ hello.o
67     $ ./a.out
68     hello
69
70 By default, LLVMC uses ``llvm-gcc`` to compile the source code. It is
71 also possible to choose the work-in-progress ``clang`` compiler with
72 the ``-clang`` option.
73
74
75 Predefined options
76 ==================
77
78 LLVMC has some built-in options that can't be overridden in the
79 configuration libraries:
80
81 * ``-o FILE`` - Output file name.
82
83 * ``-x LANGUAGE`` - Specify the language of the following input files
84   until the next -x option.
85
86 * ``-load PLUGIN_NAME`` - Load the specified plugin DLL. Example:
87   ``-load $LLVM_DIR/Release/lib/LLVMCSimple.so``.
88
89 * ``-v`` - Enable verbose mode, i.e. print out all executed commands.
90
91 * ``--view-graph`` - Show a graphical representation of the compilation
92   graph. Requires that you have ``dot`` and ``gv`` programs
93   installed. Hidden option, useful for debugging.
94
95 * ``--write-graph`` - Write a ``compilation-graph.dot`` file in the
96   current directory with the compilation graph description in the
97   Graphviz format. Hidden option, useful for debugging.
98
99 * ``--save-temps`` - Write temporary files to the current directory
100   and do not delete them on exit. Hidden option, useful for debugging.
101
102 * ``--help``, ``--help-hidden``, ``--version`` - These options have
103   their standard meaning.
104
105
106 Compiling LLVMC plugins
107 =======================
108
109 It's easiest to start working on your own LLVMC plugin by copying the
110 skeleton project which lives under ``$LLVMC_DIR/plugins/Simple``::
111
112    $ cd $LLVMC_DIR/plugins
113    $ cp -r Simple MyPlugin
114    $ cd MyPlugin
115    $ ls
116    Makefile PluginMain.cpp Simple.td
117
118 As you can see, our basic plugin consists of only two files (not
119 counting the build script). ``Simple.td`` contains TableGen
120 description of the compilation graph; its format is documented in the
121 following sections. ``PluginMain.cpp`` is just a helper file used to
122 compile the auto-generated C++ code produced from TableGen source. It
123 can also contain hook definitions (see `below`__).
124
125 __ hooks_
126
127 The first thing that you should do is to change the ``LLVMC_PLUGIN``
128 variable in the ``Makefile`` to avoid conflicts (since this variable
129 is used to name the resulting library)::
130
131    LLVMC_PLUGIN=MyPlugin
132
133 It is also a good idea to rename ``Simple.td`` to something less
134 generic::
135
136    $ mv Simple.td MyPlugin.td
137
138 Note that the plugin source directory must be placed under
139 ``$LLVMC_DIR/plugins`` to make use of the existing build
140 infrastructure. To build a version of the LLVMC executable called
141 ``mydriver`` with your plugin compiled in, use the following command::
142
143    $ cd $LLVMC_DIR
144    $ make BUILTIN_PLUGINS=MyPlugin DRIVER_NAME=mydriver
145
146 To build your plugin as a dynamic library, just ``cd`` to its source
147 directory and run ``make``. The resulting file will be called
148 ``LLVMC$(LLVMC_PLUGIN).$(DLL_EXTENSION)`` (in our case,
149 ``LLVMCMyPlugin.so``). This library can be then loaded in with the
150 ``-load`` option. Example::
151
152     $ cd $LLVMC_DIR/plugins/Simple
153     $ make
154     $ llvmc -load $LLVM_DIR/Release/lib/LLVMCSimple.so
155
156 Sometimes, you will want a 'bare-bones' version of LLVMC that has no
157 built-in plugins. It can be compiled with the following command::
158
159     $ cd $LLVMC_DIR
160     $ make BUILTIN_PLUGINS=""
161
162
163 Customizing LLVMC: the compilation graph
164 ========================================
165
166 Each TableGen configuration file should include the common
167 definitions::
168
169    include "llvm/CompilerDriver/Common.td"
170
171 Internally, LLVMC stores information about possible source
172 transformations in form of a graph. Nodes in this graph represent
173 tools, and edges between two nodes represent a transformation path. A
174 special "root" node is used to mark entry points for the
175 transformations. LLVMC also assigns a weight to each edge (more on
176 this later) to choose between several alternative edges.
177
178 The definition of the compilation graph (see file
179 ``plugins/Base/Base.td`` for an example) is just a list of edges::
180
181     def CompilationGraph : CompilationGraph<[
182         Edge<"root", "llvm_gcc_c">,
183         Edge<"root", "llvm_gcc_assembler">,
184         ...
185
186         Edge<"llvm_gcc_c", "llc">,
187         Edge<"llvm_gcc_cpp", "llc">,
188         ...
189
190         OptionalEdge<"llvm_gcc_c", "opt", (case (switch_on "opt"),
191                                           (inc_weight))>,
192         OptionalEdge<"llvm_gcc_cpp", "opt", (case (switch_on "opt"),
193                                                   (inc_weight))>,
194         ...
195
196         OptionalEdge<"llvm_gcc_assembler", "llvm_gcc_cpp_linker",
197             (case (input_languages_contain "c++"), (inc_weight),
198                   (or (parameter_equals "linker", "g++"),
199                       (parameter_equals "linker", "c++")), (inc_weight))>,
200         ...
201
202         ]>;
203
204 As you can see, the edges can be either default or optional, where
205 optional edges are differentiated by an additional ``case`` expression
206 used to calculate the weight of this edge. Notice also that we refer
207 to tools via their names (as strings). This makes it possible to add
208 edges to an existing compilation graph in plugins without having to
209 know about all tool definitions used in the graph.
210
211 The default edges are assigned a weight of 1, and optional edges get a
212 weight of 0 + 2*N where N is the number of tests that evaluated to
213 true in the ``case`` expression. It is also possible to provide an
214 integer parameter to ``inc_weight`` and ``dec_weight`` - in this case,
215 the weight is increased (or decreased) by the provided value instead
216 of the default 2. It is also possible to change the default weight of
217 an optional edge by using the ``default`` clause of the ``case``
218 construct.
219
220 When passing an input file through the graph, LLVMC picks the edge
221 with the maximum weight. To avoid ambiguity, there should be only one
222 default edge between two nodes (with the exception of the root node,
223 which gets a special treatment - there you are allowed to specify one
224 default edge *per language*).
225
226 When multiple plugins are loaded, their compilation graphs are merged
227 together. Since multiple edges that have the same end nodes are not
228 allowed (i.e. the graph is not a multigraph), an edge defined in
229 several plugins will be replaced by the definition from the plugin
230 that was loaded last. Plugin load order can be controlled by using the
231 plugin priority feature described above.
232
233 To get a visual representation of the compilation graph (useful for
234 debugging), run ``llvmc --view-graph``. You will need ``dot`` and
235 ``gsview`` installed for this to work properly.
236
237 Describing options
238 ==================
239
240 Command-line options that the plugin supports are defined by using an
241 ``OptionList``::
242
243     def Options : OptionList<[
244     (switch_option "E", (help "Help string")),
245     (alias_option "quiet", "q")
246     ...
247     ]>;
248
249 As you can see, the option list is just a list of DAGs, where each DAG
250 is an option description consisting of the option name and some
251 properties. A plugin can define more than one option list (they are
252 all merged together in the end), which can be handy if one wants to
253 separate option groups syntactically.
254
255 * Possible option types:
256
257    - ``switch_option`` - a simple boolean switch, for example ``-time``.
258
259    - ``parameter_option`` - option that takes an argument, for example
260      ``-std=c99``;
261
262    - ``parameter_list_option`` - same as the above, but more than one
263      occurence of the option is allowed.
264
265    - ``prefix_option`` - same as the parameter_option, but the option name
266      and parameter value are not separated.
267
268    - ``prefix_list_option`` - same as the above, but more than one
269      occurence of the option is allowed; example: ``-lm -lpthread``.
270
271    - ``alias_option`` - a special option type for creating
272      aliases. Unlike other option types, aliases are not allowed to
273      have any properties besides the aliased option name. Usage
274      example: ``(alias_option "preprocess", "E")``
275
276
277 * Possible option properties:
278
279    - ``help`` - help string associated with this option. Used for
280      ``--help`` output.
281
282    - ``required`` - this option is obligatory.
283
284    - ``hidden`` - this option should not appear in the ``--help``
285      output (but should appear in the ``--help-hidden`` output).
286
287    - ``really_hidden`` - the option should not appear in any help
288      output.
289
290    - ``extern`` - this option is defined in some other plugin, see below.
291
292 External options
293 ----------------
294
295 Sometimes, when linking several plugins together, one plugin needs to
296 access options defined in some other plugin. Because of the way
297 options are implemented, such options should be marked as
298 ``extern``. This is what the ``extern`` option property is
299 for. Example::
300
301      ...
302      (switch_option "E", (extern))
303      ...
304
305 See also the section on plugin `priorities`__.
306
307 __ priorities_
308
309 .. _case:
310
311 Conditional evaluation
312 ======================
313
314 The 'case' construct is the main means by which programmability is
315 achieved in LLVMC. It can be used to calculate edge weights, program
316 actions and modify the shell commands to be executed. The 'case'
317 expression is designed after the similarly-named construct in
318 functional languages and takes the form ``(case (test_1), statement_1,
319 (test_2), statement_2, ... (test_N), statement_N)``. The statements
320 are evaluated only if the corresponding tests evaluate to true.
321
322 Examples::
323
324     // Edge weight calculation
325
326     // Increases edge weight by 5 if "-A" is provided on the
327     // command-line, and by 5 more if "-B" is also provided.
328     (case
329         (switch_on "A"), (inc_weight 5),
330         (switch_on "B"), (inc_weight 5))
331
332
333     // Tool command line specification
334
335     // Evaluates to "cmdline1" if the option "-A" is provided on the
336     // command line; to "cmdline2" if "-B" is provided;
337     // otherwise to "cmdline3".
338
339     (case
340         (switch_on "A"), "cmdline1",
341         (switch_on "B"), "cmdline2",
342         (default), "cmdline3")
343
344 Note the slight difference in 'case' expression handling in contexts
345 of edge weights and command line specification - in the second example
346 the value of the ``"B"`` switch is never checked when switch ``"A"`` is
347 enabled, and the whole expression always evaluates to ``"cmdline1"`` in
348 that case.
349
350 Case expressions can also be nested, i.e. the following is legal::
351
352     (case (switch_on "E"), (case (switch_on "o"), ..., (default), ...)
353           (default), ...)
354
355 You should, however, try to avoid doing that because it hurts
356 readability. It is usually better to split tool descriptions and/or
357 use TableGen inheritance instead.
358
359 * Possible tests are:
360
361   - ``switch_on`` - Returns true if a given command-line switch is
362     provided by the user. Example: ``(switch_on "opt")``.
363
364   - ``parameter_equals`` - Returns true if a command-line parameter equals
365     a given value.
366     Example: ``(parameter_equals "W", "all")``.
367
368   - ``element_in_list`` - Returns true if a command-line parameter
369     list contains a given value.
370     Example: ``(parameter_in_list "l", "pthread")``.
371
372   - ``input_languages_contain`` - Returns true if a given language
373     belongs to the current input language set.
374     Example: ``(input_languages_contain "c++")``.
375
376   - ``in_language`` - Evaluates to true if the input file language
377     equals to the argument. At the moment works only with ``cmd_line``
378     and ``actions`` (on non-join nodes).
379     Example: ``(in_language "c++")``.
380
381   - ``not_empty`` - Returns true if a given option (which should be
382     either a parameter or a parameter list) is set by the
383     user.
384     Example: ``(not_empty "o")``.
385
386   - ``default`` - Always evaluates to true. Should always be the last
387     test in the ``case`` expression.
388
389   - ``and`` - A standard logical combinator that returns true iff all
390     of its arguments return true. Used like this: ``(and (test1),
391     (test2), ... (testN))``. Nesting of ``and`` and ``or`` is allowed,
392     but not encouraged.
393
394   - ``or`` - Another logical combinator that returns true only if any
395     one of its arguments returns true. Example: ``(or (test1),
396     (test2), ... (testN))``.
397
398
399 Writing a tool description
400 ==========================
401
402 As was said earlier, nodes in the compilation graph represent tools,
403 which are described separately. A tool definition looks like this
404 (taken from the ``include/llvm/CompilerDriver/Tools.td`` file)::
405
406   def llvm_gcc_cpp : Tool<[
407       (in_language "c++"),
408       (out_language "llvm-assembler"),
409       (output_suffix "bc"),
410       (cmd_line "llvm-g++ -c $INFILE -o $OUTFILE -emit-llvm"),
411       (sink)
412       ]>;
413
414 This defines a new tool called ``llvm_gcc_cpp``, which is an alias for
415 ``llvm-g++``. As you can see, a tool definition is just a list of
416 properties; most of them should be self-explanatory. The ``sink``
417 property means that this tool should be passed all command-line
418 options that aren't mentioned in the option list.
419
420 The complete list of all currently implemented tool properties follows.
421
422 * Possible tool properties:
423
424   - ``in_language`` - input language name. Can be either a string or a
425     list, in case the tool supports multiple input languages.
426
427   - ``out_language`` - output language name. Tools are not allowed to
428     have multiple output languages.
429
430   - ``output_suffix`` - output file suffix. Can also be changed
431     dynamically, see documentation on actions.
432
433   - ``cmd_line`` - the actual command used to run the tool. You can
434     use ``$INFILE`` and ``$OUTFILE`` variables, output redirection
435     with ``>``, hook invocations (``$CALL``), environment variables
436     (via ``$ENV``) and the ``case`` construct.
437
438   - ``join`` - this tool is a "join node" in the graph, i.e. it gets a
439     list of input files and joins them together. Used for linkers.
440
441   - ``sink`` - all command-line options that are not handled by other
442     tools are passed to this tool.
443
444   - ``actions`` - A single big ``case`` expression that specifies how
445     this tool reacts on command-line options (described in more detail
446     below).
447
448 Actions
449 -------
450
451 A tool often needs to react to command-line options, and this is
452 precisely what the ``actions`` property is for. The next example
453 illustrates this feature::
454
455   def llvm_gcc_linker : Tool<[
456       (in_language "object-code"),
457       (out_language "executable"),
458       (output_suffix "out"),
459       (cmd_line "llvm-gcc $INFILE -o $OUTFILE"),
460       (join),
461       (actions (case (not_empty "L"), (forward "L"),
462                      (not_empty "l"), (forward "l"),
463                      (not_empty "dummy"),
464                                [(append_cmd "-dummy1"), (append_cmd "-dummy2")])
465       ]>;
466
467 The ``actions`` tool property is implemented on top of the omnipresent
468 ``case`` expression. It associates one or more different *actions*
469 with given conditions - in the example, the actions are ``forward``,
470 which forwards a given option unchanged, and ``append_cmd``, which
471 appends a given string to the tool execution command. Multiple actions
472 can be associated with a single condition by using a list of actions
473 (used in the example to append some dummy options). The same ``case``
474 construct can also be used in the ``cmd_line`` property to modify the
475 tool command line.
476
477 The "join" property used in the example means that this tool behaves
478 like a linker.
479
480 The list of all possible actions follows.
481
482 * Possible actions:
483
484    - ``append_cmd`` - append a string to the tool invocation
485      command.
486      Example: ``(case (switch_on "pthread"), (append_cmd "-lpthread"))``
487
488    - ``forward`` - forward an option unchanged.
489      Example: ``(forward "Wall")``.
490
491    - ``forward_as`` - Change the name of an option, but forward the
492      argument unchanged.
493      Example: ``(forward_as "O0" "--disable-optimization")``.
494
495    - ``output_suffix`` - modify the output suffix of this
496      tool.
497      Example: ``(output_suffix "i")``.
498
499    - ``stop_compilation`` - stop compilation after this tool processes
500      its input. Used without arguments.
501
502    - ``unpack_values`` - used for for splitting and forwarding
503      comma-separated lists of options, e.g. ``-Wa,-foo=bar,-baz`` is
504      converted to ``-foo=bar -baz`` and appended to the tool invocation
505      command.
506      Example: ``(unpack_values "Wa,")``.
507
508 Language map
509 ============
510
511 If you are adding support for a new language to LLVMC, you'll need to
512 modify the language map, which defines mappings from file extensions
513 to language names. It is used to choose the proper toolchain(s) for a
514 given input file set. Language map definition looks like this::
515
516     def LanguageMap : LanguageMap<
517         [LangToSuffixes<"c++", ["cc", "cp", "cxx", "cpp", "CPP", "c++", "C"]>,
518          LangToSuffixes<"c", ["c"]>,
519          ...
520         ]>;
521
522 For example, without those definitions the following command wouldn't work::
523
524     $ llvmc hello.cpp
525     llvmc: Unknown suffix: cpp
526
527 The language map entries should be added only for tools that are
528 linked with the root node. Since tools are not allowed to have
529 multiple output languages, for nodes "inside" the graph the input and
530 output languages should match. This is enforced at compile-time.
531
532
533 More advanced topics
534 ====================
535
536 .. _hooks:
537
538 Hooks and environment variables
539 -------------------------------
540
541 Normally, LLVMC executes programs from the system ``PATH``. Sometimes,
542 this is not sufficient: for example, we may want to specify tool names
543 in the configuration file. This can be achieved via the mechanism of
544 hooks - to write your own hooks, just add their definitions to the
545 ``PluginMain.cpp`` or drop a ``.cpp`` file into the
546 ``$LLVMC_DIR/driver`` directory. Hooks should live in the ``hooks``
547 namespace and have the signature ``std::string hooks::MyHookName
548 (void)``. They can be used from the ``cmd_line`` tool property::
549
550     (cmd_line "$CALL(MyHook)/path/to/file -o $CALL(AnotherHook)")
551
552 It is also possible to use environment variables in the same manner::
553
554    (cmd_line "$ENV(VAR1)/path/to/file -o $ENV(VAR2)")
555
556 To change the command line string based on user-provided options use
557 the ``case`` expression (documented `above`__)::
558
559     (cmd_line
560       (case
561         (switch_on "E"),
562            "llvm-g++ -E -x c $INFILE -o $OUTFILE",
563         (default),
564            "llvm-g++ -c -x c $INFILE -o $OUTFILE -emit-llvm"))
565
566 __ case_
567
568 .. _priorities:
569
570 How plugins are loaded
571 ----------------------
572
573 It is possible for LLVMC plugins to depend on each other. For example,
574 one can create edges between nodes defined in some other plugin. To
575 make this work, however, that plugin should be loaded first. To
576 achieve this, the concept of plugin priority was introduced. By
577 default, every plugin has priority zero; to specify the priority
578 explicitly, put the following line in your plugin's TableGen file::
579
580     def Priority : PluginPriority<$PRIORITY_VALUE>;
581     # Where PRIORITY_VALUE is some integer > 0
582
583 Plugins are loaded in order of their (increasing) priority, starting
584 with 0. Therefore, the plugin with the highest priority value will be
585 loaded last.
586
587 Debugging
588 ---------
589
590 When writing LLVMC plugins, it can be useful to get a visual view of
591 the resulting compilation graph. This can be achieved via the command
592 line option ``--view-graph``. This command assumes that Graphviz_ and
593 Ghostview_ are installed. There is also a ``--dump-graph`` option that
594 creates a Graphviz source file (``compilation-graph.dot``) in the
595 current directory.
596
597 .. _Graphviz: http://www.graphviz.org/
598 .. _Ghostview: http://pages.cs.wisc.edu/~ghost/
599
600 .. raw:: html
601
602    <hr />
603    <address>
604    <a href="http://jigsaw.w3.org/css-validator/check/referer">
605    <img src="http://jigsaw.w3.org/css-validator/images/vcss-blue"
606       alt="Valid CSS" /></a>
607    <a href="http://validator.w3.org/check?uri=referer">
608    <img src="http://www.w3.org/Icons/valid-xhtml10-blue"
609       alt="Valid XHTML 1.0 Transitional"/></a>
610
611    <a href="mailto:foldr@codedgers.com">Mikhail Glushenkov</a><br />
612    <a href="http://llvm.org">LLVM Compiler Infrastructure</a><br />
613
614    Last modified: $Date: 2008-12-11 11:34:48 -0600 (Thu, 11 Dec 2008) $
615    </address>