LinkTimeOptimization.rst 11 KB

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