PerformanceTips.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. =====================================
  2. Performance Tips for Frontend Authors
  3. =====================================
  4. .. contents::
  5. :local:
  6. :depth: 2
  7. Abstract
  8. ========
  9. The intended audience of this document is developers of language frontends
  10. targeting LLVM IR. This document is home to a collection of tips on how to
  11. generate IR that optimizes well.
  12. IR Best Practices
  13. =================
  14. As with any optimizer, LLVM has its strengths and weaknesses. In some cases,
  15. surprisingly small changes in the source IR can have a large effect on the
  16. generated code.
  17. Beyond the specific items on the list below, it's worth noting that the most
  18. mature frontend for LLVM is Clang. As a result, the further your IR gets from
  19. what Clang might emit, the less likely it is to be effectively optimized. It
  20. can often be useful to write a quick C program with the semantics you're trying
  21. to model and see what decisions Clang's IRGen makes about what IR to emit.
  22. Studying Clang's CodeGen directory can also be a good source of ideas. Note
  23. that Clang and LLVM are explicitly version locked so you'll need to make sure
  24. you're using a Clang built from the same svn revision or release as the LLVM
  25. library you're using. As always, it's *strongly* recommended that you track
  26. tip of tree development, particularly during bring up of a new project.
  27. The Basics
  28. ^^^^^^^^^^^
  29. #. Make sure that your Modules contain both a data layout specification and
  30. target triple. Without these pieces, non of the target specific optimization
  31. will be enabled. This can have a major effect on the generated code quality.
  32. #. For each function or global emitted, use the most private linkage type
  33. possible (private, internal or linkonce_odr preferably). Doing so will
  34. make LLVM's inter-procedural optimizations much more effective.
  35. #. Avoid high in-degree basic blocks (e.g. basic blocks with dozens or hundreds
  36. of predecessors). Among other issues, the register allocator is known to
  37. perform badly with confronted with such structures. The only exception to
  38. this guidance is that a unified return block with high in-degree is fine.
  39. Use of allocas
  40. ^^^^^^^^^^^^^^
  41. An alloca instruction can be used to represent a function scoped stack slot,
  42. but can also represent dynamic frame expansion. When representing function
  43. scoped variables or locations, placing alloca instructions at the beginning of
  44. the entry block should be preferred. In particular, place them before any
  45. call instructions. Call instructions might get inlined and replaced with
  46. multiple basic blocks. The end result is that a following alloca instruction
  47. would no longer be in the entry basic block afterward.
  48. The SROA (Scalar Replacement Of Aggregates) and Mem2Reg passes only attempt
  49. to eliminate alloca instructions that are in the entry basic block. Given
  50. SSA is the canonical form expected by much of the optimizer; if allocas can
  51. not be eliminated by Mem2Reg or SROA, the optimizer is likely to be less
  52. effective than it could be.
  53. Avoid loads and stores of large aggregate type
  54. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  55. LLVM currently does not optimize well loads and stores of large :ref:`aggregate
  56. types <t_aggregate>` (i.e. structs and arrays). As an alternative, consider
  57. loading individual fields from memory.
  58. Aggregates that are smaller than the largest (performant) load or store
  59. instruction supported by the targeted hardware are well supported. These can
  60. be an effective way to represent collections of small packed fields.
  61. Prefer zext over sext when legal
  62. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  63. On some architectures (X86_64 is one), sign extension can involve an extra
  64. instruction whereas zero extension can be folded into a load. LLVM will try to
  65. replace a sext with a zext when it can be proven safe, but if you have
  66. information in your source language about the range of a integer value, it can
  67. be profitable to use a zext rather than a sext.
  68. Alternatively, you can :ref:`specify the range of the value using metadata
  69. <range-metadata>` and LLVM can do the sext to zext conversion for you.
  70. Zext GEP indices to machine register width
  71. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  72. Internally, LLVM often promotes the width of GEP indices to machine register
  73. width. When it does so, it will default to using sign extension (sext)
  74. operations for safety. If your source language provides information about
  75. the range of the index, you may wish to manually extend indices to machine
  76. register width using a zext instruction.
  77. When to specify alignment
  78. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  79. LLVM will always generate correct code if you don’t specify alignment, but may
  80. generate inefficient code. For example, if you are targeting MIPS (or older
  81. ARM ISAs) then the hardware does not handle unaligned loads and stores, and
  82. so you will enter a trap-and-emulate path if you do a load or store with
  83. lower-than-natural alignment. To avoid this, LLVM will emit a slower
  84. sequence of loads, shifts and masks (or load-right + load-left on MIPS) for
  85. all cases where the load / store does not have a sufficiently high alignment
  86. in the IR.
  87. The alignment is used to guarantee the alignment on allocas and globals,
  88. though in most cases this is unnecessary (most targets have a sufficiently
  89. high default alignment that they’ll be fine). It is also used to provide a
  90. contract to the back end saying ‘either this load/store has this alignment, or
  91. it is undefined behavior’. This means that the back end is free to emit
  92. instructions that rely on that alignment (and mid-level optimizers are free to
  93. perform transforms that require that alignment). For x86, it doesn’t make
  94. much difference, as almost all instructions are alignment-independent. For
  95. MIPS, it can make a big difference.
  96. Note that if your loads and stores are atomic, the backend will be unable to
  97. lower an under aligned access into a sequence of natively aligned accesses.
  98. As a result, alignment is mandatory for atomic loads and stores.
  99. Other Things to Consider
  100. ^^^^^^^^^^^^^^^^^^^^^^^^
  101. #. Use ptrtoint/inttoptr sparingly (they interfere with pointer aliasing
  102. analysis), prefer GEPs
  103. #. Prefer globals over inttoptr of a constant address - this gives you
  104. dereferencability information. In MCJIT, use getSymbolAddress to provide
  105. actual address.
  106. #. Be wary of ordered and atomic memory operations. They are hard to optimize
  107. and may not be well optimized by the current optimizer. Depending on your
  108. source language, you may consider using fences instead.
  109. #. If calling a function which is known to throw an exception (unwind), use
  110. an invoke with a normal destination which contains an unreachable
  111. instruction. This form conveys to the optimizer that the call returns
  112. abnormally. For an invoke which neither returns normally or requires unwind
  113. code in the current function, you can use a noreturn call instruction if
  114. desired. This is generally not required because the optimizer will convert
  115. an invoke with an unreachable unwind destination to a call instruction.
  116. #. Use profile metadata to indicate statically known cold paths, even if
  117. dynamic profiling information is not available. This can make a large
  118. difference in code placement and thus the performance of tight loops.
  119. #. When generating code for loops, try to avoid terminating the header block of
  120. the loop earlier than necessary. If the terminator of the loop header
  121. block is a loop exiting conditional branch, the effectiveness of LICM will
  122. be limited for loads not in the header. (This is due to the fact that LLVM
  123. may not know such a load is safe to speculatively execute and thus can't
  124. lift an otherwise loop invariant load unless it can prove the exiting
  125. condition is not taken.) It can be profitable, in some cases, to emit such
  126. instructions into the header even if they are not used along a rarely
  127. executed path that exits the loop. This guidance specifically does not
  128. apply if the condition which terminates the loop header is itself invariant,
  129. or can be easily discharged by inspecting the loop index variables.
  130. #. In hot loops, consider duplicating instructions from small basic blocks
  131. which end in highly predictable terminators into their successor blocks.
  132. If a hot successor block contains instructions which can be vectorized
  133. with the duplicated ones, this can provide a noticeable throughput
  134. improvement. Note that this is not always profitable and does involve a
  135. potentially large increase in code size.
  136. #. When checking a value against a constant, emit the check using a consistent
  137. comparison type. The GVN pass *will* optimize redundant equalities even if
  138. the type of comparison is inverted, but GVN only runs late in the pipeline.
  139. As a result, you may miss the opportunity to run other important
  140. optimizations. Improvements to EarlyCSE to remove this issue are tracked in
  141. Bug 23333.
  142. #. Avoid using arithmetic intrinsics unless you are *required* by your source
  143. language specification to emit a particular code sequence. The optimizer
  144. is quite good at reasoning about general control flow and arithmetic, it is
  145. not anywhere near as strong at reasoning about the various intrinsics. If
  146. profitable for code generation purposes, the optimizer will likely form the
  147. intrinsics itself late in the optimization pipeline. It is *very* rarely
  148. profitable to emit these directly in the language frontend. This item
  149. explicitly includes the use of the :ref:`overflow intrinsics <int_overflow>`.
  150. #. Avoid using the :ref:`assume intrinsic <int_assume>` until you've
  151. established that a) there's no other way to express the given fact and b)
  152. that fact is critical for optimization purposes. Assumes are a great
  153. prototyping mechanism, but they can have negative effects on both compile
  154. time and optimization effectiveness. The former is fixable with enough
  155. effort, but the later is fairly fundamental to their designed purpose.
  156. Describing Language Specific Properties
  157. =======================================
  158. When translating a source language to LLVM, finding ways to express concepts
  159. and guarantees available in your source language which are not natively
  160. provided by LLVM IR will greatly improve LLVM's ability to optimize your code.
  161. As an example, C/C++'s ability to mark every add as "no signed wrap (nsw)" goes
  162. a long way to assisting the optimizer in reasoning about loop induction
  163. variables and thus generating more optimal code for loops.
  164. The LLVM LangRef includes a number of mechanisms for annotating the IR with
  165. additional semantic information. It is *strongly* recommended that you become
  166. highly familiar with this document. The list below is intended to highlight a
  167. couple of items of particular interest, but is by no means exhaustive.
  168. Restricted Operation Semantics
  169. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  170. #. Add nsw/nuw flags as appropriate. Reasoning about overflow is
  171. generally hard for an optimizer so providing these facts from the frontend
  172. can be very impactful.
  173. #. Use fast-math flags on floating point operations if legal. If you don't
  174. need strict IEEE floating point semantics, there are a number of additional
  175. optimizations that can be performed. This can be highly impactful for
  176. floating point intensive computations.
  177. Describing Aliasing Properties
  178. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  179. #. Add noalias/align/dereferenceable/nonnull to function arguments and return
  180. values as appropriate
  181. #. Use pointer aliasing metadata, especially tbaa metadata, to communicate
  182. otherwise-non-deducible pointer aliasing facts
  183. #. Use inbounds on geps. This can help to disambiguate some aliasing queries.
  184. Modeling Memory Effects
  185. ^^^^^^^^^^^^^^^^^^^^^^^^
  186. #. Mark functions as readnone/readonly/argmemonly or noreturn/nounwind when
  187. known. The optimizer will try to infer these flags, but may not always be
  188. able to. Manual annotations are particularly important for external
  189. functions that the optimizer can not analyze.
  190. #. Use the lifetime.start/lifetime.end and invariant.start/invariant.end
  191. intrinsics where possible. Common profitable uses are for stack like data
  192. structures (thus allowing dead store elimination) and for describing
  193. life times of allocas (thus allowing smaller stack sizes).
  194. #. Mark invariant locations using !invariant.load and TBAA's constant flags
  195. Pass Ordering
  196. ^^^^^^^^^^^^^
  197. One of the most common mistakes made by new language frontend projects is to
  198. use the existing -O2 or -O3 pass pipelines as is. These pass pipelines make a
  199. good starting point for an optimizing compiler for any language, but they have
  200. been carefully tuned for C and C++, not your target language. You will almost
  201. certainly need to use a custom pass order to achieve optimal performance. A
  202. couple specific suggestions:
  203. #. For languages with numerous rarely executed guard conditions (e.g. null
  204. checks, type checks, range checks) consider adding an extra execution or
  205. two of LoopUnswith and LICM to your pass order. The standard pass order,
  206. which is tuned for C and C++ applications, may not be sufficient to remove
  207. all dischargeable checks from loops.
  208. #. If you language uses range checks, consider using the IRCE pass. It is not
  209. currently part of the standard pass order.
  210. #. A useful sanity check to run is to run your optimized IR back through the
  211. -O2 pipeline again. If you see noticeable improvement in the resulting IR,
  212. you likely need to adjust your pass order.
  213. I Still Can't Find What I'm Looking For
  214. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  215. If you didn't find what you were looking for above, consider proposing an piece
  216. of metadata which provides the optimization hint you need. Such extensions are
  217. relatively common and are generally well received by the community. You will
  218. need to ensure that your proposal is sufficiently general so that it benefits
  219. others if you wish to contribute it upstream.
  220. You should also consider describing the problem you're facing on `llvm-dev
  221. <http://lists.llvm.org/mailman/listinfo/llvm-dev>`_ and asking for advice.
  222. It's entirely possible someone has encountered your problem before and can
  223. give good advice. If there are multiple interested parties, that also
  224. increases the chances that a metadata extension would be well received by the
  225. community as a whole.
  226. Adding to this document
  227. =======================
  228. If you run across a case that you feel deserves to be covered here, please send
  229. a patch to `llvm-commits
  230. <http://lists.llvm.org/mailman/listinfo/llvm-commits>`_ for review.
  231. If you have questions on these items, please direct them to `llvm-dev
  232. <http://lists.llvm.org/mailman/listinfo/llvm-dev>`_. The more relevant
  233. context you are able to give to your question, the more likely it is to be
  234. answered.