Documentation update.
[oota-llvm.git] / tools / llvmc2 / doc / LLVMC-Reference.rst
1 ===================================
2 Customizing LLVMC: Reference Manual
3 ===================================
4
5 LLVMC is a generic compiler driver, designed to be customizable and
6 extensible. It plays the same role for LLVM as the ``gcc`` program
7 does for GCC - LLVMC's job is essentially to transform a set of input
8 files into a set of targets depending on configuration rules and user
9 options. What makes LLVMC different is that these transformation rules
10 are completely customizable - in fact, LLVMC knows nothing about the
11 specifics of transformation (even the command-line options are mostly
12 not hard-coded) and regards the transformation structure as an
13 abstract graph. This makes it possible to adapt LLVMC for other
14 purposes - for example, as a build tool for game resources.
15
16 Because LLVMC employs TableGen [1]_ as its configuration language, you
17 need to be familiar with it to customize LLVMC.
18
19
20 .. contents::
21
22
23 Compiling with LLVMC
24 ====================
25
26 LLVMC tries hard to be as compatible with ``gcc`` as possible,
27 although there are some small differences. Most of the time, however,
28 you shouldn't be able to notice them::
29
30      $ # This works as expected:
31      $ llvmc2 -O3 -Wall hello.cpp
32      $ ./a.out
33      hello
34
35 One nice feature of LLVMC is that one doesn't have to distinguish
36 between different compilers for different languages (think ``g++`` and
37 ``gcc``) - the right toolchain is chosen automatically based on input
38 language names (which are, in turn, determined from file
39 extensions). If you want to force files ending with ".c" to compile as
40 C++, use the ``-x`` option, just like you would do it with ``gcc``::
41
42       $ llvmc2 -x c hello.cpp
43       $ # hello.cpp is really a C file
44       $ ./a.out
45       hello
46
47 On the other hand, when using LLVMC as a linker to combine several C++
48 object files you should provide the ``--linker`` option since it's
49 impossible for LLVMC to choose the right linker in that case::
50
51     $ llvmc2 -c hello.cpp
52     $ llvmc2 hello.o
53     [A lot of link-time errors skipped]
54     $ llvmc2 --linker=c++ hello.o
55     $ ./a.out
56     hello
57
58 Predefined options
59 ==================
60
61 LLVMC has some built-in options that can't be overridden in the
62 configuration files:
63
64 * ``-o FILE`` - Output file name.
65
66 * ``-x LANGUAGE`` - Specify the language of the following input files
67   until the next -x option.
68
69 * ``-v`` - Enable verbose mode, i.e. print out all executed commands.
70
71 * ``--view-graph`` - Show a graphical representation of the compilation
72   graph. Requires that you have ``dot`` and ``gv`` commands
73   installed. Hidden option, useful for debugging.
74
75 * ``--write-graph`` - Write a ``compilation-graph.dot`` file in the
76   current directory with the compilation graph description in the
77   Graphviz format. Hidden option, useful for debugging.
78
79
80 Customizing LLVMC: the compilation graph
81 ========================================
82
83 At the time of writing LLVMC does not support on-the-fly reloading of
84 configuration, so to customize LLVMC you'll have to recompile the
85 source code (which lives under ``$LLVM_DIR/tools/llvmc2``). The
86 default configuration files are ``Common.td`` (contains common
87 definitions, don't forget to ``include`` it in your configuration
88 files), ``Tools.td`` (tool descriptions) and ``Graph.td`` (compilation
89 graph definition).
90
91 To compile LLVMC with your own configuration file (say,``MyGraph.td``),
92 run ``make`` like this::
93
94     $ cd $LLVM_DIR/tools/llvmc2
95     $ make GRAPH=MyGraph.td TOOLNAME=my_llvmc
96
97 This will build an executable named ``my_llvmc``. There are also
98 several sample configuration files in the ``llvmc2/examples``
99 subdirectory that should help to get you started.
100
101 Internally, LLVMC stores information about possible source
102 transformations in form of a graph. Nodes in this graph represent
103 tools, and edges between two nodes represent a transformation path. A
104 special "root" node is used to mark entry points for the
105 transformations. LLVMC also assigns a weight to each edge (more on
106 this later) to choose between several alternative edges.
107
108 The definition of the compilation graph (see file ``Graph.td``) is
109 just a list of edges::
110
111     def CompilationGraph : CompilationGraph<[
112         Edge<root, llvm_gcc_c>,
113         Edge<root, llvm_gcc_assembler>,
114         ...
115
116         Edge<llvm_gcc_c, llc>,
117         Edge<llvm_gcc_cpp, llc>,
118         ...
119
120         OptionalEdge<llvm_gcc_c, opt, [(switch_on "opt")]>,
121         OptionalEdge<llvm_gcc_cpp, opt, [(switch_on "opt")]>,
122         ...
123
124         OptionalEdge<llvm_gcc_assembler, llvm_gcc_cpp_linker,
125             (case (input_languages_contain "c++"), (inc_weight),
126                   (or (parameter_equals "linker", "g++"),
127                       (parameter_equals "linker", "c++")), (inc_weight))>,
128         ...
129
130         ]>;
131
132 As you can see, the edges can be either default or optional, where
133 optional edges are differentiated by sporting a ``case`` expression
134 used to calculate the edge's weight.
135
136 The default edges are assigned a weight of 1, and optional edges get a
137 weight of 0 + 2*N where N is the number of tests that evaluated to
138 true in the ``case`` expression. It is also possible to provide an
139 integer parameter to ``inc_weight`` and ``dec_weight`` - in this case,
140 the weight is increased (or decreased) by the provided value instead
141 of the default 2.
142
143 When passing an input file through the graph, LLVMC picks the edge
144 with the maximum weight. To avoid ambiguity, there should be only one
145 default edge between two nodes (with the exception of the root node,
146 which gets a special treatment - there you are allowed to specify one
147 default edge *per language*).
148
149 To get a visual representation of the compilation graph (useful for
150 debugging), run ``llvmc2 --view-graph``. You will need ``dot`` and
151 ``gsview`` installed for this to work properly.
152
153
154 Writing a tool description
155 ==========================
156
157 As was said earlier, nodes in the compilation graph represent tools,
158 which are described separately. A tool definition looks like this
159 (taken from the ``Tools.td`` file)::
160
161   def llvm_gcc_cpp : Tool<[
162       (in_language "c++"),
163       (out_language "llvm-assembler"),
164       (output_suffix "bc"),
165       (cmd_line "llvm-g++ -c $INFILE -o $OUTFILE -emit-llvm"),
166       (sink)
167       ]>;
168
169 This defines a new tool called ``llvm_gcc_cpp``, which is an alias for
170 ``llvm-g++``. As you can see, a tool definition is just a list of
171 properties; most of them should be self-explanatory. The ``sink``
172 property means that this tool should be passed all command-line
173 options that lack explicit descriptions.
174
175 The complete list of the currently implemented tool properties follows:
176
177 * Possible tool properties:
178
179   - ``in_language`` - input language name.
180
181   - ``out_language`` - output language name.
182
183   - ``output_suffix`` - output file suffix.
184
185   - ``cmd_line`` - the actual command used to run the tool. You can
186     use ``$INFILE`` and ``$OUTFILE`` variables, output redirection
187     with ``>``, hook invocations (``$CALL``), environment variables
188     (via ``$ENV``) and the ``case`` construct (more on this below).
189
190   - ``join`` - this tool is a "join node" in the graph, i.e. it gets a
191     list of input files and joins them together. Used for linkers.
192
193   - ``sink`` - all command-line options that are not handled by other
194     tools are passed to this tool.
195
196 The next tool definition is slightly more complex::
197
198   def llvm_gcc_linker : Tool<[
199       (in_language "object-code"),
200       (out_language "executable"),
201       (output_suffix "out"),
202       (cmd_line "llvm-gcc $INFILE -o $OUTFILE"),
203       (join),
204       (prefix_list_option "L", (forward),
205                           (help "add a directory to link path")),
206       (prefix_list_option "l", (forward),
207                           (help "search a library when linking")),
208       (prefix_list_option "Wl", (unpack_values),
209                           (help "pass options to linker"))
210       ]>;
211
212 This tool has a "join" property, which means that it behaves like a
213 linker. This tool also defines several command-line options: ``-l``,
214 ``-L`` and ``-Wl`` which have their usual meaning. An option has two
215 attributes: a name and a (possibly empty) list of properties. All
216 currently implemented option types and properties are described below:
217
218 * Possible option types:
219
220    - ``switch_option`` - a simple boolean switch, for example ``-time``.
221
222    - ``parameter_option`` - option that takes an argument, for example
223      ``-std=c99``;
224
225    - ``parameter_list_option`` - same as the above, but more than one
226      occurence of the option is allowed.
227
228    - ``prefix_option`` - same as the parameter_option, but the option name
229      and parameter value are not separated.
230
231    - ``prefix_list_option`` - same as the above, but more than one
232      occurence of the option is allowed; example: ``-lm -lpthread``.
233
234
235 * Possible option properties:
236
237    - ``append_cmd`` - append a string to the tool invocation command.
238
239    - ``forward`` - forward this option unchanged.
240
241    - ``output_suffix`` - modify the output suffix of this
242      tool. Example : ``(switch "E", (output_suffix "i")``.
243
244    - ``stop_compilation`` - stop compilation after this phase.
245
246    - ``unpack_values`` - used for for splitting and forwarding
247      comma-separated lists of options, e.g. ``-Wa,-foo=bar,-baz`` is
248      converted to ``-foo=bar -baz`` and appended to the tool invocation
249      command.
250
251    - ``help`` - help string associated with this option. Used for
252      ``--help`` output.
253
254    - ``required`` - this option is obligatory.
255
256
257 Using hooks and environment variables in the ``cmd_line`` property
258 ==================================================================
259
260 Normally, LLVMC executes programs from the system ``PATH``. Sometimes,
261 this is not sufficient: for example, we may want to specify tool names
262 in the configuration file. This can be achieved via the mechanism of
263 hooks - to compile LLVMC with your hooks, just drop a .cpp file into
264 ``tools/llvmc2`` directory. Hooks should live in the ``hooks``
265 namespace and have the signature ``std::string hooks::MyHookName
266 (void)``. They can be used from the ``cmd_line`` tool property::
267
268     (cmd_line "$CALL(MyHook)/path/to/file -o $CALL(AnotherHook)")
269
270 It is also possible to use environment variables in the same manner::
271
272    (cmd_line "$ENV(VAR1)/path/to/file -o $ENV(VAR2)")
273
274 To change the command line string based on user-provided options use
275 the ``case`` expression (documented below)::
276
277     (cmd_line
278       (case
279         (switch_on "E"),
280            "llvm-g++ -E -x c $INFILE -o $OUTFILE",
281         (default),
282            "llvm-g++ -c -x c $INFILE -o $OUTFILE -emit-llvm"))
283
284 Conditional evaluation: the ``case`` expression
285 ===============================================
286
287 The 'case' construct can be used to calculate weights of the optional
288 edges and to choose between several alternative command line strings
289 in the ``cmd_line`` tool property. It is designed after the
290 similarly-named construct in functional languages and takes the form
291 ``(case (test_1), statement_1, (test_2), statement_2, ... (test_N),
292 statement_N)``. The statements are evaluated only if the corresponding
293 tests evaluate to true.
294
295 Examples::
296
297     // Increases edge weight by 5 if "-A" is provided on the
298     // command-line, and by 5 more if "-B" is also provided.
299     (case
300         (switch_on "A"), (inc_weight 5),
301         (switch_on "B"), (inc_weight 5))
302
303     // Evaluates to "cmdline1" if option "-A" is provided on the
304     // command line, otherwise to "cmdline2"
305     (case
306         (switch_on "A"), "cmdline1",
307         (switch_on "B"), "cmdline2",
308         (default), "cmdline3")
309
310 Note the slight difference in 'case' expression handling in contexts
311 of edge weights and command line specification - in the second example
312 the value of the ``"B"`` switch is never checked when switch ``"A"`` is
313 enabled, and the whole expression always evaluates to ``"cmdline1"`` in
314 that case.
315
316 Case expressions can also be nested, i.e. the following is legal::
317
318     (case (switch_on "E"), (case (switch_on "o"), ..., (default), ...)
319           (default), ...)
320
321 You should, however, try to avoid doing that because it hurts
322 readability. It is usually better to split tool descriptions and/or
323 use TableGen inheritance instead.
324
325 * Possible tests are:
326
327   - ``switch_on`` - Returns true if a given command-line option is
328     provided by the user. Example: ``(switch_on "opt")``. Note that
329     you have to define all possible command-line options separately in
330     the tool descriptions. See the next section for the discussion of
331     different kinds of command-line options.
332
333   - ``parameter_equals`` - Returns true if a command-line parameter equals
334     a given value. Example: ``(parameter_equals "W", "all")``.
335
336   - ``element_in_list`` - Returns true if a command-line parameter list
337     includes a given value. Example: ``(parameter_in_list "l", "pthread")``.
338
339   - ``input_languages_contain`` - Returns true if a given language
340     belongs to the current input language set. Example:
341     ```(input_languages_contain "c++")``.
342
343   - ``in_language`` - Evaluates to true if the language of the input
344     file equals to the argument. Valid only when using ``case``
345     expression in a ``cmd_line`` tool property. Example:
346     ```(in_language "c++")``.
347
348   - ``not_empty`` - Returns true if a given option (which should be
349     either a parameter or a parameter list) is set by the
350     user. Example: ```(not_empty "o")``.
351
352   - ``default`` - Always evaluates to true. Should always be the last
353     test in the ``case`` expression.
354
355   - ``and`` - A standard logical combinator that returns true iff all
356     of its arguments return true. Used like this: ``(and (test1),
357     (test2), ... (testN))``. Nesting of ``and`` and ``or`` is allowed,
358     but not encouraged.
359
360   - ``or`` - Another logical combinator that returns true only if any
361     one of its arguments returns true. Example: ``(or (test1),
362     (test2), ... (testN))``.
363
364
365 Language map
366 ============
367
368 One last thing that you will need to modify when adding support for a
369 new language to LLVMC is the language map, which defines mappings from
370 file extensions to language names. It is used to choose the proper
371 toolchain(s) for a given input file set. Language map definition is
372 located in the file ``Tools.td`` and looks like this::
373
374     def LanguageMap : LanguageMap<
375         [LangToSuffixes<"c++", ["cc", "cp", "cxx", "cpp", "CPP", "c++", "C"]>,
376          LangToSuffixes<"c", ["c"]>,
377          ...
378         ]>;
379
380
381 References
382 ==========
383
384 .. [1] TableGen Fundamentals
385        http://llvm.cs.uiuc.edu/docs/TableGenFundamentals.html