SourceBasedCodeCoverage.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. ==========================
  2. Source-based Code Coverage
  3. ==========================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document explains how to use clang's source-based code coverage feature.
  9. It's called "source-based" because it operates on AST and preprocessor
  10. information directly. This allows it to generate very precise coverage data.
  11. Clang ships two other code coverage implementations:
  12. * :doc:`SanitizerCoverage` - A low-overhead tool meant for use alongside the
  13. various sanitizers. It can provide up to edge-level coverage.
  14. * gcov - A GCC-compatible coverage implementation which operates on DebugInfo.
  15. This is enabled by ``-ftest-coverage`` or ``--coverage``.
  16. From this point onwards "code coverage" will refer to the source-based kind.
  17. The code coverage workflow
  18. ==========================
  19. The code coverage workflow consists of three main steps:
  20. * Compiling with coverage enabled.
  21. * Running the instrumented program.
  22. * Creating coverage reports.
  23. The next few sections work through a complete, copy-'n-paste friendly example
  24. based on this program:
  25. .. code-block:: cpp
  26. % cat <<EOF > foo.cc
  27. #define BAR(x) ((x) || (x))
  28. template <typename T> void foo(T x) {
  29. for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  30. }
  31. int main() {
  32. foo<int>(0);
  33. foo<float>(0);
  34. return 0;
  35. }
  36. EOF
  37. Compiling with coverage enabled
  38. ===============================
  39. To compile code with coverage enabled, pass ``-fprofile-instr-generate
  40. -fcoverage-mapping`` to the compiler:
  41. .. code-block:: console
  42. # Step 1: Compile with coverage enabled.
  43. % clang++ -fprofile-instr-generate -fcoverage-mapping foo.cc -o foo
  44. Note that linking together code with and without coverage instrumentation is
  45. supported. Uninstrumented code simply won't be accounted for in reports.
  46. Running the instrumented program
  47. ================================
  48. The next step is to run the instrumented program. When the program exits it
  49. will write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE``
  50. environment variable. If that variable does not exist, the profile is written
  51. to ``default.profraw`` in the current directory of the program. If
  52. ``LLVM_PROFILE_FILE`` contains a path to a non-existent directory, the missing
  53. directory structure will be created. Additionally, the following special
  54. **pattern strings** are rewritten:
  55. * "%p" expands out to the process ID.
  56. * "%h" expands out to the hostname of the machine running the program.
  57. * "%Nm" expands out to the instrumented binary's signature. When this pattern
  58. is specified, the runtime creates a pool of N raw profiles which are used for
  59. on-line profile merging. The runtime takes care of selecting a raw profile
  60. from the pool, locking it, and updating it before the program exits. If N is
  61. not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. N must
  62. be between 1 and 9. The merge pool specifier can only occur once per filename
  63. pattern.
  64. .. code-block:: console
  65. # Step 2: Run the program.
  66. % LLVM_PROFILE_FILE="foo.profraw" ./foo
  67. Creating coverage reports
  68. =========================
  69. Raw profiles have to be **indexed** before they can be used to generate
  70. coverage reports. This is done using the "merge" tool in ``llvm-profdata``
  71. (which can combine multiple raw profiles and index them at the same time):
  72. .. code-block:: console
  73. # Step 3(a): Index the raw profile.
  74. % llvm-profdata merge -sparse foo.profraw -o foo.profdata
  75. There are multiple different ways to render coverage reports. The simplest
  76. option is to generate a line-oriented report:
  77. .. code-block:: console
  78. # Step 3(b): Create a line-oriented coverage report.
  79. % llvm-cov show ./foo -instr-profile=foo.profdata
  80. This report includes a summary view as well as dedicated sub-views for
  81. templated functions and their instantiations. For our example program, we get
  82. distinct views for ``foo<int>(...)`` and ``foo<float>(...)``. If
  83. ``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line
  84. region counts (even in macro expansions):
  85. .. code-block:: none
  86. 1| 20|#define BAR(x) ((x) || (x))
  87. ^20 ^2
  88. 2| 2|template <typename T> void foo(T x) {
  89. 3| 22| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  90. ^22 ^20 ^20^20
  91. 4| 2|}
  92. ------------------
  93. | void foo<int>(int):
  94. | 2| 1|template <typename T> void foo(T x) {
  95. | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  96. | ^11 ^10 ^10^10
  97. | 4| 1|}
  98. ------------------
  99. | void foo<float>(int):
  100. | 2| 1|template <typename T> void foo(T x) {
  101. | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  102. | ^11 ^10 ^10^10
  103. | 4| 1|}
  104. ------------------
  105. To generate a file-level summary of coverage statistics instead of a
  106. line-oriented report, try:
  107. .. code-block:: console
  108. # Step 3(c): Create a coverage summary.
  109. % llvm-cov report ./foo -instr-profile=foo.profdata
  110. Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover
  111. --------------------------------------------------------------------------------------------------------------------------------------
  112. /tmp/foo.cc 13 0 100.00% 3 0 100.00% 13 0 100.00%
  113. --------------------------------------------------------------------------------------------------------------------------------------
  114. TOTAL 13 0 100.00% 3 0 100.00% 13 0 100.00%
  115. The ``llvm-cov`` tool supports specifying a custom demangler, writing out
  116. reports in a directory structure, and generating html reports. For the full
  117. list of options, please refer to the `command guide
  118. <https://llvm.org/docs/CommandGuide/llvm-cov.html>`_.
  119. A few final notes:
  120. * The ``-sparse`` flag is optional but can result in dramatically smaller
  121. indexed profiles. This option should not be used if the indexed profile will
  122. be reused for PGO.
  123. * Raw profiles can be discarded after they are indexed. Advanced use of the
  124. profile runtime library allows an instrumented program to merge profiling
  125. information directly into an existing raw profile on disk. The details are
  126. out of scope.
  127. * The ``llvm-profdata`` tool can be used to merge together multiple raw or
  128. indexed profiles. To combine profiling data from multiple runs of a program,
  129. try e.g:
  130. .. code-block:: console
  131. % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata
  132. Exporting coverage data
  133. =======================
  134. Coverage data can be exported into JSON using the ``llvm-cov export``
  135. sub-command. There is a comprehensive reference which defines the structure of
  136. the exported data at a high level in the llvm-cov source code.
  137. Interpreting reports
  138. ====================
  139. There are four statistics tracked in a coverage summary:
  140. * Function coverage is the percentage of functions which have been executed at
  141. least once. A function is considered to be executed if any of its
  142. instantiations are executed.
  143. * Instantiation coverage is the percentage of function instantiations which
  144. have been executed at least once. Template functions and static inline
  145. functions from headers are two kinds of functions which may have multiple
  146. instantiations.
  147. * Line coverage is the percentage of code lines which have been executed at
  148. least once. Only executable lines within function bodies are considered to be
  149. code lines.
  150. * Region coverage is the percentage of code regions which have been executed at
  151. least once. A code region may span multiple lines (e.g in a large function
  152. body with no control flow). However, it's also possible for a single line to
  153. contain multiple code regions (e.g in "return x || y && z").
  154. Of these four statistics, function coverage is usually the least granular while
  155. region coverage is the most granular. The project-wide totals for each
  156. statistic are listed in the summary.
  157. Format compatibility guarantees
  158. ===============================
  159. * There are no backwards or forwards compatibility guarantees for the raw
  160. profile format. Raw profiles may be dependent on the specific compiler
  161. revision used to generate them. It's inadvisable to store raw profiles for
  162. long periods of time.
  163. * Tools must retain **backwards** compatibility with indexed profile formats.
  164. These formats are not forwards-compatible: i.e, a tool which uses format
  165. version X will not be able to understand format version (X+k).
  166. * Tools must also retain **backwards** compatibility with the format of the
  167. coverage mappings emitted into instrumented binaries. These formats are not
  168. forwards-compatible.
  169. * The JSON coverage export format has a (major, minor, patch) version triple.
  170. Only a major version increment indicates a backwards-incompatible change. A
  171. minor version increment is for added functionality, and patch version
  172. increments are for bugfixes.
  173. Using the profiling runtime without static initializers
  174. =======================================================
  175. By default the compiler runtime uses a static initializer to determine the
  176. profile output path and to register a writer function. To collect profiles
  177. without using static initializers, do this manually:
  178. * Export a ``int __llvm_profile_runtime`` symbol from each instrumented shared
  179. library and executable. When the linker finds a definition of this symbol, it
  180. knows to skip loading the object which contains the profiling runtime's
  181. static initializer.
  182. * Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it
  183. once from each instrumented executable. This function parses
  184. ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files
  185. at that path. To get the same behavior without truncating existing files,
  186. pass a filename pattern string to ``void __llvm_profile_set_filename(char
  187. *)``. These calls can be placed anywhere so long as they precede all calls
  188. to ``__llvm_profile_write_file``.
  189. * Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write
  190. out a profile. This function returns 0 when it succeeds, and a non-zero value
  191. otherwise. Calling this function multiple times appends profile data to an
  192. existing on-disk raw profile.
  193. In C++ files, declare these as ``extern "C"``.
  194. Collecting coverage reports for the llvm project
  195. ================================================
  196. To prepare a coverage report for llvm (and any of its sub-projects), add
  197. ``-DLLVM_BUILD_INSTRUMENTED_COVERAGE=On`` to the cmake configuration. Raw
  198. profiles will be written to ``$BUILD_DIR/profiles/``. To prepare an html
  199. report, run ``llvm/utils/prepare-code-coverage-artifact.py``.
  200. To specify an alternate directory for raw profiles, use
  201. ``-DLLVM_PROFILE_DATA_DIR``. To change the size of the profile merge pool, use
  202. ``-DLLVM_PROFILE_MERGE_POOL_SIZE``.
  203. Drawbacks and limitations
  204. =========================
  205. * Prior to version 2.26, the GNU binutils BFD linker is not able link programs
  206. compiled with ``-fcoverage-mapping`` in its ``--gc-sections`` mode. Possible
  207. workarounds include disabling ``--gc-sections``, upgrading to a newer version
  208. of BFD, or using the Gold linker.
  209. * Code coverage does not handle unpredictable changes in control flow or stack
  210. unwinding in the presence of exceptions precisely. Consider the following
  211. function:
  212. .. code-block:: cpp
  213. int f() {
  214. may_throw();
  215. return 0;
  216. }
  217. If the call to ``may_throw()`` propagates an exception into ``f``, the code
  218. coverage tool may mark the ``return`` statement as executed even though it is
  219. not. A call to ``longjmp()`` can have similar effects.