Debian Codegraph @

clang/docs/SourceBasedCodeCoverage.rst

raw
1 ==========================
2 Source-based Code Coverage
3 ==========================
4
5 .. contents::
6 :local:
7
8 Introduction
9 ============
10
11 This document explains how to use clang's source-based code coverage feature.
12 It's called "source-based" because it operates on AST and preprocessor
13 information directly. This allows it to generate very precise coverage data.
14
15 Clang ships two other code coverage implementations:
16
17 * :doc:`SanitizerCoverage` - A low-overhead tool meant for use alongside the
18 various sanitizers. It can provide up to edge-level coverage.
19
20 * gcov - A GCC-compatible coverage implementation which operates on DebugInfo.
21 This is enabled by ``-ftest-coverage`` or ``--coverage``.
22
23 From this point onwards "code coverage" will refer to the source-based kind.
24
25 The code coverage workflow
26 ==========================
27
28 The code coverage workflow consists of three main steps:
29
30 * Compiling with coverage enabled.
31
32 * Running the instrumented program.
33
34 * Creating coverage reports.
35
36 The next few sections work through a complete, copy-'n-paste friendly example
37 based on this program:
38
39 .. code-block:: cpp
40
41 % cat <<EOF > foo.cc
42 #define BAR(x) ((x) || (x))
43 template <typename T> void foo(T x) {
44 for (unsigned I = 0; I < 10; ++I) { BAR(I); }
45 }
46 int main() {
47 foo<int>(0);
48 foo<float>(0);
49 return 0;
50 }
51 EOF
52
53 Compiling with coverage enabled
54 ===============================
55
56 To compile code with coverage enabled, pass ``-fprofile-instr-generate
57 -fcoverage-mapping`` to the compiler:
58
59 .. code-block:: console
60
61 # Step 1: Compile with coverage enabled.
62 % clang++ -fprofile-instr-generate -fcoverage-mapping foo.cc -o foo
63
64 Note that linking together code with and without coverage instrumentation is
65 supported. Uninstrumented code simply won't be accounted for in reports.
66
67 To compile code with Modified Condition/Decision Coverage (MC/DC) enabled,
68 pass ``-fcoverage-mcdc`` in addition to the clang options specified above.
69 MC/DC is an advanced form of code coverage most applicable to the embedded
70 space.
71
72 Running the instrumented program
73 ================================
74
75 The next step is to run the instrumented program. When the program exits, it
76 will write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE``
77 environment variable. If that variable does not exist, the profile is written
78 to ``default.profraw`` in the current directory of the program. If
79 ``LLVM_PROFILE_FILE`` specifies a path to a non-existent directory, the missing
80 directory structure will be created. Additionally, the following special
81 **pattern strings** are rewritten:
82
83 * "%p" expands out to the process ID.
84
85 * "%h" expands out to the hostname of the machine running the program.
86
87 * "%t" expands out to the value of the ``TMPDIR`` environment variable. On
88 Darwin, this is typically set to a temporary scratch directory.
89
90 * "%Nm" expands out to the instrumented binary's signature. When this pattern
91 is specified, the runtime creates a pool of N raw profiles which are used for
92 on-line profile merging. The runtime takes care of selecting a raw profile
93 from the pool, locking it, and updating it before the program exits. If N is
94 not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. The
95 merge pool specifier can only occur once per filename pattern.
96
97 * "%b" expands out to the binary ID (build ID). It can be used with "%Nm" to
98 avoid binary signature collisions. To use it, the program should be compiled
99 with the build ID linker option (``--build-id`` for GNU ld or LLD,
100 ``/build-id`` for lld-link on Windows). Linux, Windows, and AIX are supported.
101
102 * "%c" expands out to nothing, but enables a mode in which profile counter
103 updates are continuously synced to a file. This means that if the
104 instrumented program crashes, or is killed by a signal, perfect coverage
105 information can still be recovered. Continuous mode does not support value
106 profiling for PGO, and is only supported on Darwin at the moment. Support for
107 Linux may be mostly complete but requires testing, and support for Windows
108 may require more extensive changes: please get involved if you are interested
109 in porting this feature.
110
111 .. code-block:: console
112
113 # Step 2: Run the program.
114 % LLVM_PROFILE_FILE="foo.profraw" ./foo
115
116 Note that continuous mode is also used on Fuchsia where it's the only supported
117 mode, but the implementation is different. The Darwin and Linux implementation
118 relies on padding and the ability to map a file over the existing memory
119 mapping which is generally only available on POSIX systems and isn't suitable
120 for other platforms.
121
122 On Fuchsia, we rely on the ability to relocate counters at runtime using a
123 level of indirection. On every counter access, we add a bias to the counter
124 address. This bias is stored in ``__llvm_profile_counter_bias`` symbol that's
125 provided by the profile runtime and is initially set to zero, meaning no
126 relocation. The runtime can map the profile into memory at arbitrary locations,
127 and set bias to the offset between the original and the new counter location,
128 at which point every subsequent counter access will be to the new location,
129 which allows updating profile directly akin to the continuous mode.
130
131 The advantage of this approach is that it doesn't require any special OS support.
132 The disadvantage is the extra overhead due to additional instructions required
133 for each counter access (overhead both in terms of binary size and performance)
134 plus duplication of counters (i.e. one copy in the binary itself and another
135 copy that's mapped into memory). This implementation can be also enabled for
136 other platforms by passing the ``-runtime-counter-relocation`` option to the
137 backend during compilation.
138
139 For a program such as the `Lit <https://llvm.org/docs/CommandGuide/lit.html>`_
140 testing tool, which invokes other programs, it may be necessary to set
141 ``LLVM_PROFILE_FILE`` for each invocation. The pattern strings "%p" or "%Nm"
142 may help to avoid corruption due to concurrency. Note that "%p" is also a Lit
143 token and needs to be escaped as "%%p".
144
145 .. code-block:: console
146
147 % clang++ -fprofile-instr-generate -fcoverage-mapping -mllvm -runtime-counter-relocation foo.cc -o foo
148
149 Creating coverage reports
150 =========================
151
152 Raw profiles must be **indexed** before they can be used to generate
153 coverage reports. This is done using the "merge" tool in ``llvm-profdata``
154 (which can combine multiple raw profiles and index them at the same time):
155
156 .. code-block:: console
157
158 # Step 3(a): Index the raw profile.
159 % llvm-profdata merge -sparse foo.profraw -o foo.profdata
160
161 For an example of merging multiple profiles created by testing,
162 see the LLVM `coverage build script <https://github.com/llvm/llvm-zorg/blob/main/zorg/jenkins/jobs/jobs/llvm-coverage>`_.
163
164 There are multiple different ways to render coverage reports. The simplest
165 option is to generate a line-oriented report:
166
167 .. code-block:: console
168
169 # Step 3(b): Create a line-oriented coverage report.
170 % llvm-cov show ./foo -instr-profile=foo.profdata
171
172 This report includes a summary view as well as dedicated sub-views for
173 templated functions and their instantiations. For our example program, we get
174 distinct views for ``foo<int>(...)`` and ``foo<float>(...)``. If
175 ``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line
176 region counts (even in macro expansions):
177
178 .. code-block:: none
179
180 1| 20|#define BAR(x) ((x) || (x))
181 ^20 ^2
182 2| 2|template <typename T> void foo(T x) {
183 3| 22| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
184 ^22 ^20 ^20^20
185 4| 2|}
186 ------------------
187 | void foo<int>(int):
188 | 2| 1|template <typename T> void foo(T x) {
189 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
190 | ^11 ^10 ^10^10
191 | 4| 1|}
192 ------------------
193 | void foo<float>(int):
194 | 2| 1|template <typename T> void foo(T x) {
195 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
196 | ^11 ^10 ^10^10
197 | 4| 1|}
198 ------------------
199
200 If ``--show-branches=count`` and ``--show-expansions`` are also enabled, the
201 sub-views will show detailed branch coverage information in addition to the
202 region counts:
203
204 .. code-block:: none
205
206 ------------------
207 | void foo<float>(int):
208 | 2| 1|template <typename T> void foo(T x) {
209 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
210 | ^11 ^10 ^10^10
211 | ------------------
212 | | | 1| 10|#define BAR(x) ((x) || (x))
213 | | | ^10 ^1
214 | | | ------------------
215 | | | | Branch (1:17): [True: 9, False: 1]
216 | | | | Branch (1:24): [True: 0, False: 1]
217 | | | ------------------
218 | ------------------
219 | | Branch (3:23): [True: 10, False: 1]
220 | ------------------
221 | 4| 1|}
222 ------------------
223
224 If the application was instrumented for Modified Condition/Decision Coverage
225 (MC/DC) using the clang option ``-fcoverage-mcdc``, an MC/DC subview can be
226 enabled using ``--show-mcdc`` that will show detailed MC/DC information for
227 each complex condition boolean expression containing at most six conditions.
228
229 To generate a file-level summary of coverage statistics instead of a
230 line-oriented report, try:
231
232 .. code-block:: console
233
234 # Step 3(c): Create a coverage summary.
235 % llvm-cov report ./foo -instr-profile=foo.profdata
236 Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover Branches Missed Branches Cover
237 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
238 /tmp/foo.cc 13 0 100.00% 3 0 100.00% 13 0 100.00% 12 2 83.33%
239 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
240 TOTAL 13 0 100.00% 3 0 100.00% 13 0 100.00% 12 2 83.33%
241
242 The ``llvm-cov`` tool supports specifying a custom demangler, writing out
243 reports in a directory structure, and generating HTML reports. For the full
244 list of options, please refer to the `command guide
245 <https://llvm.org/docs/CommandGuide/llvm-cov.html>`_.
246
247 A few final notes:
248
249 * The ``-sparse`` flag is optional but can produce dramatically smaller
250 indexed profiles. This option should not be used if the indexed profile will
251 be reused for PGO.
252
253 * Raw profiles can be discarded after they are indexed. Advanced use of the
254 profile runtime library allows an instrumented program to merge profiling
255 information directly into an existing raw profile on disk. The details are
256 out of scope.
257
258 * The ``llvm-profdata`` tool can be used to merge multiple raw or
259 indexed profiles. To combine profiling data from multiple runs of a program,
260 try e.g:
261
262 .. code-block:: console
263
264 % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata
265
266 Exporting coverage data
267 =======================
268
269 Coverage data can be exported into JSON using the ``llvm-cov export``
270 sub-command. There is a comprehensive reference which defines the structure of
271 the exported data at a high level in the llvm-cov source code.
272
273 Interpreting reports
274 ====================
275
276 There are six statistics tracked in a coverage summary:
277
278 * Function coverage is the percentage of functions which have been executed at
279 least once. A function is considered to be executed if any of its
280 instantiations are executed.
281
282 * Instantiation coverage is the percentage of function instantiations which
283 have been executed at least once. Template functions and static inline
284 functions from headers are two kinds of functions which may have multiple
285 instantiations. This statistic is hidden by default in reports, but can be
286 enabled via the ``-show-instantiation-summary`` option.
287
288 * Line coverage is the percentage of code lines which have been executed at
289 least once. Only executable lines within function bodies are considered to be
290 code lines.
291
292 * Region coverage is the percentage of code regions which have been executed at
293 least once. A code region may span multiple lines (e.g in a large function
294 body with no control flow). However, it's also possible for a single line to
295 contain multiple code regions (e.g in "return x || y && z").
296
297 * Branch coverage is the percentage of "true" and "false" branches that have
298 been taken at least once. Each branch is tied to individual conditions in the
299 source code that may each evaluate to either "true" or "false". These
300 conditions may comprise larger boolean expressions linked by boolean logical
301 operators. For example, "x = (y == 2) || (z < 10)" is a boolean expression
302 comprised of two individual conditions, each of which evaluates to
303 either true or false, producing four total branch outcomes.
304
305 * Modified Condition/Decision Coverage (MC/DC) is the percentage of individual
306 branch conditions that have been shown to independently affect the decision
307 outcome of the boolean expression they comprise. This is accomplished using
308 the analysis of executed control flow through the expression (i.e. test
309 vectors) to show that as a condition's outcome is varied between "true" and
310 false", the decision's outcome also varies between "true" and false", while
311 the outcome of all other conditions is held fixed (or they are masked out as
312 unevaluatable, as happens in languages whose logical operators have
313 short-circuit semantics). MC/DC builds on top of branch coverage and
314 requires that all code blocks and all execution paths have been tested. This
315 statistic is hidden by default in reports, but it can be enabled via the
316 ``-show-mcdc-summary`` option as long as code was also compiled using the
317 clang option ``-fcoverage-mcdc``.
318
319 * Boolean expressions comprised of only one condition (and therefore
320 have no logical operators) are not included in MC/DC analysis and are
321 trivially deducible using branch coverage.
322
323 Of these six statistics, function coverage is usually the least granular while
324 branch coverage (with MC/DC) is the most granular. 100% branch coverage for a
325 function implies 100% region coverage for a function. The project-wide totals
326 for each statistic are listed in the summary.
327
328 Format compatibility guarantees
329 ===============================
330
331 * There are no backwards or forwards compatibility guarantees for the raw
332 profile format. Raw profiles may be dependent on the specific compiler
333 revision used to generate them. It's inadvisable to store raw profiles for
334 long periods of time.
335
336 * Tools must retain **backwards** compatibility with indexed profile formats.
337 These formats are not forwards-compatible: i.e, a tool which uses format
338 version X will not be able to understand format version (X+k).
339
340 * Tools must also retain **backwards** compatibility with the format of the
341 coverage mappings emitted into instrumented binaries. These formats are not
342 forwards-compatible.
343
344 * The JSON coverage export format has a (major, minor, patch) version triple.
345 Only a major version increment indicates a backwards-incompatible change. A
346 minor version increment is for added functionality, and patch version
347 increments are for bugfixes.
348
349 Impact of llvm optimizations on coverage reports
350 ================================================
351
352 llvm optimizations (such as inlining or CFG simplification) should have no
353 impact on coverage report quality. This is due to the fact that the mapping
354 from source regions to profile counters is immutable, and is generated before
355 the llvm optimizer kicks in. The optimizer can't prove that profile counter
356 instrumentation is safe to delete (because it's not: it affects the profile the
357 program emits), and so leaves it alone.
358
359 Note that this coverage feature does not rely on information that can degrade
360 during the course of optimization, such as debug info line tables.
361
362 Using the profiling runtime without static initializers
363 =======================================================
364
365 By default the compiler runtime uses a static initializer to determine the
366 profile output path and to register a writer function. To collect profiles
367 without using static initializers, do this manually:
368
369 * Export an ``int __llvm_profile_runtime`` symbol from each instrumented shared
370 library and executable. When the linker finds a definition of this symbol, it
371 knows to skip loading the object which contains the profiling runtime's
372 static initializer.
373
374 * Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it
375 once from each instrumented executable. This function parses
376 ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files
377 at that path. To get the same behavior without truncating existing files,
378 pass a filename pattern string to ``void __llvm_profile_set_filename(char
379 *)``. These calls can be placed anywhere so long as they precede all calls
380 to ``__llvm_profile_write_file``.
381
382 * Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write
383 out a profile. This function returns 0 on success, and a non-zero value
384 otherwise. Calling this function multiple times appends profile data to an
385 existing on-disk raw profile.
386
387 In C++ files, declare these as ``extern "C"``.
388
389 Using the profiling runtime without a filesystem
390 ------------------------------------------------
391
392 The profiling runtime also supports freestanding environments that lack a
393 filesystem. The runtime ships as a static archive that's structured to make
394 dependencies on a hosted environment optional, depending on what features
395 the client application uses.
396
397 The first step is to export ``__llvm_profile_runtime``, as above, to disable
398 the default static initializers. Instead of calling the ``*_file()`` APIs
399 described above, use the following to save the profile directly to a buffer
400 under your control:
401
402 * Forward-declare ``uint64_t __llvm_profile_get_size_for_buffer(void)`` and
403 call it to determine the size of the profile. You'll need to allocate a
404 buffer of this size.
405
406 * Forward-declare ``int __llvm_profile_write_buffer(char *Buffer)`` and call it
407 to copy the current counters to ``Buffer``, which is expected to already be
408 allocated and big enough for the profile.
409
410 * Optionally, forward-declare ``void __llvm_profile_reset_counters(void)`` and
411 call it to reset the counters before entering a specific section to be
412 profiled. This is only useful if there is some setup that should be excluded
413 from the profile.
414
415 In C++ files, declare these as ``extern "C"``.
416
417 Collecting coverage reports for the llvm project
418 ================================================
419
420 To prepare a coverage report for llvm (and any of its sub-projects), add
421 ``-DLLVM_BUILD_INSTRUMENTED_COVERAGE=On`` to the CMake configuration. Raw
422 profiles will be written to ``$BUILD_DIR/profiles/``. To prepare an html
423 report, run ``llvm/utils/prepare-code-coverage-artifact.py``.
424
425 To specify an alternate directory for raw profiles, use
426 ``-DLLVM_PROFILE_DATA_DIR``. To change the size of the profile merge pool, use
427 ``-DLLVM_PROFILE_MERGE_POOL_SIZE``.
428
429 Drawbacks and limitations
430 =========================
431
432 * Prior to version 2.26, the GNU binutils BFD linker cannot link programs
433 compiled with ``-fcoverage-mapping`` in its ``--gc-sections`` mode. Possible
434 workarounds include disabling ``--gc-sections``, upgrading to a newer version
435 of BFD, or using the Gold linker.
436
437 * Code coverage does not handle unpredictable changes in control flow or stack
438 unwinding in the presence of exceptions precisely. Consider the following
439 function:
440
441 .. code-block:: cpp
442
443 int f() {
444 may_throw();
445 return 0;
446 }
447
448 If the call to ``may_throw()`` propagates an exception into ``f``, the code
449 coverage tool may mark the ``return`` statement as executed even though it is
450 not. A call to ``longjmp()`` can have similar effects.
451
452 Clang implementation details
453 ============================
454
455 This section may be of interest to those wishing to understand or improve
456 the clang code coverage implementation.
457
458 Gap regions
459 -----------
460
461 Gap regions are source regions with counts. A reporting tool cannot set a line
462 execution count to the count from a gap region unless that region is the only
463 one on a line.
464
465 Gap regions are used to eliminate unnatural artifacts in coverage reports, such
466 as red "unexecuted" highlights present at the end of an otherwise covered line,
467 or blue "executed" highlights present at the start of a line that is otherwise
468 not executed.
469
470 Branch regions
471 --------------
472 When viewing branch coverage details in source-based file-level sub-views using
473 ``--show-branches``, it is recommended that users show all macro expansions
474 (using option ``--show-expansions``) since macros may contain hidden branch
475 conditions. The coverage summary report will always include these macro-based
476 boolean expressions in the overall branch coverage count for a function or
477 source file.
478
479 Branch coverage is not tracked for constant folded branch conditions since
480 branches are not generated for these cases. In the source-based file-level
481 sub-view, these branches will simply be shown as ``[Folded - Ignored]`` so that
482 users are informed about what happened.
483
484 Branch coverage is tied directly to branch-generating conditions in the source
485 code. Users should not see hidden branches that aren't actually tied to the
486 source code.
487
488 MC/DC Instrumentation
489 ---------------------
490
491 When instrumenting for Modified Condition/Decision Coverage (MC/DC) using the
492 clang option ``-fcoverage-mcdc``, there are two hard limits.
493
494 The maximum number of terms is limited to 32767, which is practical for
495 handwritten expressions. To be more restrictive in order to enforce coding rules,
496 use ``-Xclang -fmcdc-max-conditions=n``. Expressions with exceeded condition
497 counts ``n`` will generate warnings and will be excluded in the MC/DC coverage.
498
499 The number of test vectors (the maximum number of possible combinations of
500 expressions) is limited to 2,147,483,646. In this case, approximately
501 256MiB (==2GiB/8) is used to record test vectors.
502
503 To reduce memory usage, users can limit the maximum number of test vectors per
504 expression with ``-Xclang -fmcdc-max-test-vectors=m``.
505 If the number of test vectors resulting from the analysis of an expression
506 exceeds ``m``, a warning will be issued and the expression will be excluded
507 from the MC/DC coverage.
508
509 The number of test vectors ``m``, for ``n`` terms in an expression, can be
510 ``m <= 2^n`` in the theoretical worst case, but is usually much smaller.
511 In simple cases, such as expressions consisting of a sequence of single
512 operators, ``m == n+1``. For example, ``(a && b && c && d && e && f && g)``
513 requires 8 test vectors.
514
515 Expressions such as ``((a0 && b0) || (a1 && b1) || ...)`` can cause the
516 number of test vectors to increase exponentially.
517
518 Also, if a boolean expression is embedded in the nest of another boolean
519 expression but separated by a non-logical operator, this is also not supported.
520 For example, in ``x = (a && b && c && func(d && f))``, the ``d && f`` case
521 starts a new boolean expression that is separated from the other conditions by
522 the operator ``func()``. When this is encountered, a warning will be generated
523 and the boolean expression will not be instrumented.
524
525 Switch statements
526 -----------------
527
528 The region mapping for a switch body consists of a gap region that covers the
529 entire body (starting from the '{' in 'switch (...) {', and terminating where the
530 last case ends). This gap region has a zero count: this causes "gap" areas in
531 between case statements, which contain no executable code, to appear uncovered.
532
533 When a switch case is visited, the parent region is extended: if the parent
534 region has no start location, its start location becomes the start of the case.
535 This is used to support switch statements without a ``CompoundStmt`` body, in
536 which the switch body and the single case share a count.
537
538 For switches with ``CompoundStmt`` bodies, a new region is created at the start
539 of each switch case.
540
541 Branch regions are also generated for each switch case, including the default
542 case. If there is no explicitly defined default case in the source code, a
543 branch region is generated to correspond to the implicit default case that is
544 generated by the compiler. The implicit branch region is tied to the line and
545 column number of the switch statement condition since no source code for the
546 implicit case exists.