blob: 822196ccf47a7d6a6ba810f776e71a3843b40d8b [file] [log] [blame]
Bill Wendlinga3a2eb02012-06-20 10:08:02 +00001.. _lto:
2
3======================================================
4LLVM Link Time Optimization: Design and Implementation
5======================================================
6
7.. contents::
8 :local:
9
10Description
11===========
12
13LLVM features powerful intermodular optimizations which can be used at link
14time. Link Time Optimization (LTO) is another name for intermodular
15optimization when performed during the link stage. This document describes the
16interface and design between the LTO optimizer and the linker.
17
18Design Philosophy
19=================
20
21The LLVM Link Time Optimizer provides complete transparency, while doing
22intermodular optimization, in the compiler tool chain. Its main goal is to let
23the developer take advantage of intermodular optimizations without making any
24significant changes to the developer's makefiles or build system. This is
25achieved through tight integration with the linker. In this model, the linker
26treates LLVM bitcode files like native object files and allows mixing and
27matching among them. The linker uses `libLTO`_, a shared object, to handle LLVM
28bitcode files. This tight integration between the linker and LLVM optimizer
29helps to do optimizations that are not possible in other models. The linker
30input allows the optimizer to avoid relying on conservative escape analysis.
31
Sean Silva34c6b7e2012-10-04 03:56:23 +000032.. _libLTO-example:
33
Bill Wendlinga3a2eb02012-06-20 10:08:02 +000034Example of link time optimization
35---------------------------------
36
37The following example illustrates the advantages of LTO's integrated approach
38and clean interface. This example requires a system linker which supports LTO
39through the interface described in this document. Here, clang transparently
40invokes system linker.
41
42* Input source file ``a.c`` is compiled into LLVM bitcode form.
43* Input source file ``main.c`` is compiled into native object code.
44
45.. code-block:: c++
46
47 --- a.h ---
48 extern int foo1(void);
49 extern void foo2(void);
50 extern void foo4(void);
51
52 --- a.c ---
53 #include "a.h"
54
55 static signed int i = 0;
56
57 void foo2(void) {
58 i = -1;
59 }
60
61 static int foo3() {
62 foo4();
63 return 10;
64 }
65
66 int foo1(void) {
67 int data = 0;
68
69 if (i < 0)
70 data = foo3();
71
72 data = data + 42;
73 return data;
74 }
75
76 --- main.c ---
77 #include <stdio.h>
78 #include "a.h"
79
80 void foo4(void) {
81 printf("Hi\n");
82 }
83
84 int main() {
85 return foo1();
86 }
87
Dmitri Gribenko44581af2012-12-12 16:58:13 +000088To compile, run:
Bill Wendlinga3a2eb02012-06-20 10:08:02 +000089
Dmitri Gribenko44581af2012-12-12 16:58:13 +000090.. code-block:: console
91
Bill Wendlinga3a2eb02012-06-20 10:08:02 +000092 % clang -emit-llvm -c a.c -o a.o # <-- a.o is LLVM bitcode file
93 % clang -c main.c -o main.o # <-- main.o is native object file
94 % clang a.o main.o -o main # <-- standard link command without modifications
95
96* In this example, the linker recognizes that ``foo2()`` is an externally
97 visible symbol defined in LLVM bitcode file. The linker completes its usual
98 symbol resolution pass and finds that ``foo2()`` is not used
99 anywhere. This information is used by the LLVM optimizer and it
Dmitri Gribenko44581af2012-12-12 16:58:13 +0000100 removes ``foo2()``.
Bill Wendlinga3a2eb02012-06-20 10:08:02 +0000101
102* As soon as ``foo2()`` is removed, the optimizer recognizes that condition ``i
103 < 0`` is always false, which means ``foo3()`` is never used. Hence, the
104 optimizer also removes ``foo3()``.
105
106* And this in turn, enables linker to remove ``foo4()``.
107
108This example illustrates the advantage of tight integration with the
109linker. Here, the optimizer can not remove ``foo3()`` without the linker's
110input.
111
112Alternative Approaches
113----------------------
114
115**Compiler driver invokes link time optimizer separately.**
116 In this model the link time optimizer is not able to take advantage of
117 information collected during the linker's normal symbol resolution phase.
118 In the above example, the optimizer can not remove ``foo2()`` without the
119 linker's input because it is externally visible. This in turn prohibits the
120 optimizer from removing ``foo3()``.
121
122**Use separate tool to collect symbol information from all object files.**
123 In this model, a new, separate, tool or library replicates the linker's
124 capability to collect information for link time optimization. Not only is
125 this code duplication difficult to justify, but it also has several other
126 disadvantages. For example, the linking semantics and the features provided
127 by the linker on various platform are not unique. This means, this new tool
128 needs to support all such features and platforms in one super tool or a
129 separate tool per platform is required. This increases maintenance cost for
130 link time optimizer significantly, which is not necessary. This approach
131 also requires staying synchronized with linker developements on various
132 platforms, which is not the main focus of the link time optimizer. Finally,
133 this approach increases end user's build time due to the duplication of work
134 done by this separate tool and the linker itself.
135
136Multi-phase communication between ``libLTO`` and linker
137=======================================================
138
139The linker collects information about symbol defininitions and uses in various
140link objects which is more accurate than any information collected by other
141tools during typical build cycles. The linker collects this information by
142looking at the definitions and uses of symbols in native .o files and using
143symbol visibility information. The linker also uses user-supplied information,
144such as a list of exported symbols. LLVM optimizer collects control flow
145information, data flow information and knows much more about program structure
146from the optimizer's point of view. Our goal is to take advantage of tight
147integration between the linker and the optimizer by sharing this information
148during various linking phases.
149
150Phase 1 : Read LLVM Bitcode Files
151---------------------------------
152
153The linker first reads all object files in natural order and collects symbol
154information. This includes native object files as well as LLVM bitcode files.
155To minimize the cost to the linker in the case that all .o files are native
156object files, the linker only calls ``lto_module_create()`` when a supplied
157object file is found to not be a native object file. If ``lto_module_create()``
158returns that the file is an LLVM bitcode file, the linker then iterates over the
159module using ``lto_module_get_symbol_name()`` and
160``lto_module_get_symbol_attribute()`` to get all symbols defined and referenced.
161This information is added to the linker's global symbol table.
162
163
164The lto* functions are all implemented in a shared object libLTO. This allows
165the LLVM LTO code to be updated independently of the linker tool. On platforms
166that support it, the shared object is lazily loaded.
167
168Phase 2 : Symbol Resolution
169---------------------------
170
171In this stage, the linker resolves symbols using global symbol table. It may
172report undefined symbol errors, read archive members, replace weak symbols, etc.
173The linker is able to do this seamlessly even though it does not know the exact
174content of input LLVM bitcode files. If dead code stripping is enabled then the
175linker collects the list of live symbols.
176
177Phase 3 : Optimize Bitcode Files
178--------------------------------
179
180After symbol resolution, the linker tells the LTO shared object which symbols
181are needed by native object files. In the example above, the linker reports
182that only ``foo1()`` is used by native object files using
183``lto_codegen_add_must_preserve_symbol()``. Next the linker invokes the LLVM
184optimizer and code generators using ``lto_codegen_compile()`` which returns a
185native object file creating by merging the LLVM bitcode files and applying
186various optimization passes.
187
188Phase 4 : Symbol Resolution after optimization
189----------------------------------------------
190
191In this phase, the linker reads optimized a native object file and updates the
192internal global symbol table to reflect any changes. The linker also collects
193information about any changes in use of external symbols by LLVM bitcode
194files. In the example above, the linker notes that ``foo4()`` is not used any
195more. If dead code stripping is enabled then the linker refreshes the live
196symbol information appropriately and performs dead code stripping.
197
198After this phase, the linker continues linking as if it never saw LLVM bitcode
199files.
200
201.. _libLTO:
202
203``libLTO``
204==========
205
206``libLTO`` is a shared object that is part of the LLVM tools, and is intended
207for use by a linker. ``libLTO`` provides an abstract C interface to use the LLVM
208interprocedural optimizer without exposing details of LLVM's internals. The
209intention is to keep the interface as stable as possible even when the LLVM
210optimizer continues to evolve. It should even be possible for a completely
211different compilation technology to provide a different libLTO that works with
212their object files and the standard linker tool.
213
214``lto_module_t``
215----------------
216
217A non-native object file is handled via an ``lto_module_t``. The following
218functions allow the linker to check if a file (on disk or in a memory buffer) is
219a file which libLTO can process:
220
221.. code-block:: c
222
223 lto_module_is_object_file(const char*)
224 lto_module_is_object_file_for_target(const char*, const char*)
225 lto_module_is_object_file_in_memory(const void*, size_t)
226 lto_module_is_object_file_in_memory_for_target(const void*, size_t, const char*)
227
228If the object file can be processed by ``libLTO``, the linker creates a
229``lto_module_t`` by using one of:
230
231.. code-block:: c
232
233 lto_module_create(const char*)
234 lto_module_create_from_memory(const void*, size_t)
235
236and when done, the handle is released via
237
238.. code-block:: c
239
240 lto_module_dispose(lto_module_t)
241
242
243The linker can introspect the non-native object file by getting the number of
244symbols and getting the name and attributes of each symbol via:
245
246.. code-block:: c
247
248 lto_module_get_num_symbols(lto_module_t)
249 lto_module_get_symbol_name(lto_module_t, unsigned int)
250 lto_module_get_symbol_attribute(lto_module_t, unsigned int)
251
252The attributes of a symbol include the alignment, visibility, and kind.
253
254``lto_code_gen_t``
255------------------
256
257Once the linker has loaded each non-native object files into an
258``lto_module_t``, it can request ``libLTO`` to process them all and generate a
259native object file. This is done in a couple of steps. First, a code generator
260is created with:
261
262.. code-block:: c
263
264 lto_codegen_create()
265
266Then, each non-native object file is added to the code generator with:
267
268.. code-block:: c
269
270 lto_codegen_add_module(lto_code_gen_t, lto_module_t)
271
272The linker then has the option of setting some codegen options. Whether or not
273to generate DWARF debug info is set with:
274
275.. code-block:: c
276
277 lto_codegen_set_debug_model(lto_code_gen_t)
278
279Which kind of position independence is set with:
280
281.. code-block:: c
282
283 lto_codegen_set_pic_model(lto_code_gen_t)
284
285And each symbol that is referenced by a native object file or otherwise must not
286be optimized away is set with:
287
288.. code-block:: c
289
290 lto_codegen_add_must_preserve_symbol(lto_code_gen_t, const char*)
291
292After all these settings are done, the linker requests that a native object file
293be created from the modules with the settings using:
294
295.. code-block:: c
296
297 lto_codegen_compile(lto_code_gen_t, size*)
298
299which returns a pointer to a buffer containing the generated native object file.
300The linker then parses that and links it with the rest of the native object
301files.