]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/coverage/debug.rs
Auto merge of #92570 - jsha:rustdoc-search-refactor, r=GuillaumeGomez
[rust.git] / compiler / rustc_mir_transform / src / coverage / debug.rs
1 //! The `InstrumentCoverage` MIR pass implementation includes debugging tools and options
2 //! to help developers understand and/or improve the analysis and instrumentation of a MIR.
3 //!
4 //! To enable coverage, include the rustc command line option:
5 //!
6 //!   * `-C instrument-coverage`
7 //!
8 //! MIR Dump Files, with additional `CoverageGraph` graphviz and `CoverageSpan` spanview
9 //! ------------------------------------------------------------------------------------
10 //!
11 //! Additional debugging options include:
12 //!
13 //!   * `-Z dump-mir=InstrumentCoverage` - Generate `.mir` files showing the state of the MIR,
14 //!     before and after the `InstrumentCoverage` pass, for each compiled function.
15 //!
16 //!   * `-Z dump-mir-graphviz` - If `-Z dump-mir` is also enabled for the current MIR node path,
17 //!     each MIR dump is accompanied by a before-and-after graphical view of the MIR, in Graphviz
18 //!     `.dot` file format (which can be visually rendered as a graph using any of a number of free
19 //!     Graphviz viewers and IDE extensions).
20 //!
21 //!     For the `InstrumentCoverage` pass, this option also enables generation of an additional
22 //!     Graphviz `.dot` file for each function, rendering the `CoverageGraph`: the control flow
23 //!     graph (CFG) of `BasicCoverageBlocks` (BCBs), as nodes, internally labeled to show the
24 //!     `CoverageSpan`-based MIR elements each BCB represents (`BasicBlock`s, `Statement`s and
25 //!     `Terminator`s), assigned coverage counters and/or expressions, and edge counters, as needed.
26 //!
27 //!     (Note the additional option, `-Z graphviz-dark-mode`, can be added, to change the rendered
28 //!     output from its default black-on-white background to a dark color theme, if desired.)
29 //!
30 //!   * `-Z dump-mir-spanview` - If `-Z dump-mir` is also enabled for the current MIR node path,
31 //!     each MIR dump is accompanied by a before-and-after `.html` document showing the function's
32 //!     original source code, highlighted by it's MIR spans, at the `statement`-level (by default),
33 //!     `terminator` only, or encompassing span for the `Terminator` plus all `Statement`s, in each
34 //!     `block` (`BasicBlock`).
35 //!
36 //!     For the `InstrumentCoverage` pass, this option also enables generation of an additional
37 //!     spanview `.html` file for each function, showing the aggregated `CoverageSpan`s that will
38 //!     require counters (or counter expressions) for accurate coverage analysis.
39 //!
40 //! Debug Logging
41 //! -------------
42 //!
43 //! The `InstrumentCoverage` pass includes debug logging messages at various phases and decision
44 //! points, which can be enabled via environment variable:
45 //!
46 //! ```shell
47 //! RUSTC_LOG=rustc_mir_transform::transform::coverage=debug
48 //! ```
49 //!
50 //! Other module paths with coverage-related debug logs may also be of interest, particularly for
51 //! debugging the coverage map data, injected as global variables in the LLVM IR (during rustc's
52 //! code generation pass). For example:
53 //!
54 //! ```shell
55 //! RUSTC_LOG=rustc_mir_transform::transform::coverage,rustc_codegen_ssa::coverageinfo,rustc_codegen_llvm::coverageinfo=debug
56 //! ```
57 //!
58 //! Coverage Debug Options
59 //! ---------------------------------
60 //!
61 //! Additional debugging options can be enabled using the environment variable:
62 //!
63 //! ```shell
64 //! RUSTC_COVERAGE_DEBUG_OPTIONS=<options>
65 //! ```
66 //!
67 //! These options are comma-separated, and specified in the format `option-name=value`. For example:
68 //!
69 //! ```shell
70 //! $ RUSTC_COVERAGE_DEBUG_OPTIONS=counter-format=id+operation,allow-unused-expressions=yes cargo build
71 //! ```
72 //!
73 //! Coverage debug options include:
74 //!
75 //!   * `allow-unused-expressions=yes` or `no` (default: `no`)
76 //!
77 //!     The `InstrumentCoverage` algorithms _should_ only create and assign expressions to a
78 //!     `BasicCoverageBlock`, or an incoming edge, if that expression is either (a) required to
79 //!     count a `CoverageSpan`, or (b) a dependency of some other required counter expression.
80 //!
81 //!     If an expression is generated that does not map to a `CoverageSpan` or dependency, this
82 //!     probably indicates there was a bug in the algorithm that creates and assigns counters
83 //!     and expressions.
84 //!
85 //!     When this kind of bug is encountered, the rustc compiler will panic by default. Setting:
86 //!     `allow-unused-expressions=yes` will log a warning message instead of panicking (effectively
87 //!     ignoring the unused expressions), which may be helpful when debugging the root cause of
88 //!     the problem.
89 //!
90 //!   * `counter-format=<choices>`, where `<choices>` can be any plus-separated combination of `id`,
91 //!     `block`, and/or `operation` (default: `block+operation`)
92 //!
93 //!     This option effects both the `CoverageGraph` (graphviz `.dot` files) and debug logging, when
94 //!     generating labels for counters and expressions.
95 //!
96 //!     Depending on the values and combinations, counters can be labeled by:
97 //!
98 //!       * `id` - counter or expression ID (ascending counter IDs, starting at 1, or descending
99 //!         expression IDs, starting at `u32:MAX`)
100 //!       * `block` - the `BasicCoverageBlock` label (for example, `bcb0`) or edge label (for
101 //!         example `bcb0->bcb1`), for counters or expressions assigned to count a
102 //!         `BasicCoverageBlock` or edge. Intermediate expressions (not directly associated with
103 //!         a BCB or edge) will be labeled by their expression ID, unless `operation` is also
104 //!         specified.
105 //!       * `operation` - applied to expressions only, labels include the left-hand-side counter
106 //!         or expression label (lhs operand), the operator (`+` or `-`), and the right-hand-side
107 //!         counter or expression (rhs operand). Expression operand labels are generated
108 //!         recursively, generating labels with nested operations, enclosed in parentheses
109 //!         (for example: `bcb2 + (bcb0 - bcb1)`).
110
111 use super::graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph};
112 use super::spans::CoverageSpan;
113
114 use itertools::Itertools;
115 use rustc_middle::mir::create_dump_file;
116 use rustc_middle::mir::generic_graphviz::GraphvizWriter;
117 use rustc_middle::mir::spanview::{self, SpanViewable};
118
119 use rustc_data_structures::fx::FxHashMap;
120 use rustc_middle::mir::coverage::*;
121 use rustc_middle::mir::{self, BasicBlock, TerminatorKind};
122 use rustc_middle::ty::TyCtxt;
123 use rustc_span::Span;
124
125 use std::iter;
126 use std::lazy::SyncOnceCell;
127
128 pub const NESTED_INDENT: &str = "    ";
129
130 const RUSTC_COVERAGE_DEBUG_OPTIONS: &str = "RUSTC_COVERAGE_DEBUG_OPTIONS";
131
132 pub(super) fn debug_options<'a>() -> &'a DebugOptions {
133     static DEBUG_OPTIONS: SyncOnceCell<DebugOptions> = SyncOnceCell::new();
134
135     &DEBUG_OPTIONS.get_or_init(DebugOptions::from_env)
136 }
137
138 /// Parses and maintains coverage-specific debug options captured from the environment variable
139 /// "RUSTC_COVERAGE_DEBUG_OPTIONS", if set.
140 #[derive(Debug, Clone)]
141 pub(super) struct DebugOptions {
142     pub allow_unused_expressions: bool,
143     counter_format: ExpressionFormat,
144 }
145
146 impl DebugOptions {
147     fn from_env() -> Self {
148         let mut allow_unused_expressions = true;
149         let mut counter_format = ExpressionFormat::default();
150
151         if let Ok(env_debug_options) = std::env::var(RUSTC_COVERAGE_DEBUG_OPTIONS) {
152             for setting_str in env_debug_options.replace(' ', "").replace('-', "_").split(',') {
153                 let (option, value) = match setting_str.split_once('=') {
154                     None => (setting_str, None),
155                     Some((k, v)) => (k, Some(v)),
156                 };
157                 match option {
158                     "allow_unused_expressions" => {
159                         allow_unused_expressions = bool_option_val(option, value);
160                         debug!(
161                             "{} env option `allow_unused_expressions` is set to {}",
162                             RUSTC_COVERAGE_DEBUG_OPTIONS, allow_unused_expressions
163                         );
164                     }
165                     "counter_format" => {
166                         match value {
167                             None => {
168                                 bug!(
169                                     "`{}` option in environment variable {} requires one or more \
170                                     plus-separated choices (a non-empty subset of \
171                                     `id+block+operation`)",
172                                     option,
173                                     RUSTC_COVERAGE_DEBUG_OPTIONS
174                                 );
175                             }
176                             Some(val) => {
177                                 counter_format = counter_format_option_val(val);
178                                 debug!(
179                                     "{} env option `counter_format` is set to {:?}",
180                                     RUSTC_COVERAGE_DEBUG_OPTIONS, counter_format
181                                 );
182                             }
183                         };
184                     }
185                     _ => bug!(
186                         "Unsupported setting `{}` in environment variable {}",
187                         option,
188                         RUSTC_COVERAGE_DEBUG_OPTIONS
189                     ),
190                 };
191             }
192         }
193
194         Self { allow_unused_expressions, counter_format }
195     }
196 }
197
198 fn bool_option_val(option: &str, some_strval: Option<&str>) -> bool {
199     if let Some(val) = some_strval {
200         if vec!["yes", "y", "on", "true"].contains(&val) {
201             true
202         } else if vec!["no", "n", "off", "false"].contains(&val) {
203             false
204         } else {
205             bug!(
206                 "Unsupported value `{}` for option `{}` in environment variable {}",
207                 option,
208                 val,
209                 RUSTC_COVERAGE_DEBUG_OPTIONS
210             )
211         }
212     } else {
213         true
214     }
215 }
216
217 fn counter_format_option_val(strval: &str) -> ExpressionFormat {
218     let mut counter_format = ExpressionFormat { id: false, block: false, operation: false };
219     let components = strval.splitn(3, '+');
220     for component in components {
221         match component {
222             "id" => counter_format.id = true,
223             "block" => counter_format.block = true,
224             "operation" => counter_format.operation = true,
225             _ => bug!(
226                 "Unsupported counter_format choice `{}` in environment variable {}",
227                 component,
228                 RUSTC_COVERAGE_DEBUG_OPTIONS
229             ),
230         }
231     }
232     counter_format
233 }
234
235 #[derive(Debug, Clone)]
236 struct ExpressionFormat {
237     id: bool,
238     block: bool,
239     operation: bool,
240 }
241
242 impl Default for ExpressionFormat {
243     fn default() -> Self {
244         Self { id: false, block: true, operation: true }
245     }
246 }
247
248 /// If enabled, this struct maintains a map from `CoverageKind` IDs (as `ExpressionOperandId`) to
249 /// the `CoverageKind` data and optional label (normally, the counter's associated
250 /// `BasicCoverageBlock` format string, if any).
251 ///
252 /// Use `format_counter` to convert one of these `CoverageKind` counters to a debug output string,
253 /// as directed by the `DebugOptions`. This allows the format of counter labels in logs and dump
254 /// files (including the `CoverageGraph` graphviz file) to be changed at runtime, via environment
255 /// variable.
256 ///
257 /// `DebugCounters` supports a recursive rendering of `Expression` counters, so they can be
258 /// presented as nested expressions such as `(bcb3 - (bcb0 + bcb1))`.
259 pub(super) struct DebugCounters {
260     some_counters: Option<FxHashMap<ExpressionOperandId, DebugCounter>>,
261 }
262
263 impl DebugCounters {
264     pub fn new() -> Self {
265         Self { some_counters: None }
266     }
267
268     pub fn enable(&mut self) {
269         debug_assert!(!self.is_enabled());
270         self.some_counters.replace(FxHashMap::default());
271     }
272
273     pub fn is_enabled(&self) -> bool {
274         self.some_counters.is_some()
275     }
276
277     pub fn add_counter(&mut self, counter_kind: &CoverageKind, some_block_label: Option<String>) {
278         if let Some(counters) = &mut self.some_counters {
279             let id: ExpressionOperandId = match *counter_kind {
280                 CoverageKind::Counter { id, .. } => id.into(),
281                 CoverageKind::Expression { id, .. } => id.into(),
282                 _ => bug!(
283                     "the given `CoverageKind` is not an counter or expression: {:?}",
284                     counter_kind
285                 ),
286             };
287             counters
288                 .try_insert(id, DebugCounter::new(counter_kind.clone(), some_block_label))
289                 .expect("attempt to add the same counter_kind to DebugCounters more than once");
290         }
291     }
292
293     pub fn some_block_label(&self, operand: ExpressionOperandId) -> Option<&String> {
294         self.some_counters.as_ref().map_or(None, |counters| {
295             counters
296                 .get(&operand)
297                 .map_or(None, |debug_counter| debug_counter.some_block_label.as_ref())
298         })
299     }
300
301     pub fn format_counter(&self, counter_kind: &CoverageKind) -> String {
302         match *counter_kind {
303             CoverageKind::Counter { .. } => {
304                 format!("Counter({})", self.format_counter_kind(counter_kind))
305             }
306             CoverageKind::Expression { .. } => {
307                 format!("Expression({})", self.format_counter_kind(counter_kind))
308             }
309             CoverageKind::Unreachable { .. } => "Unreachable".to_owned(),
310         }
311     }
312
313     fn format_counter_kind(&self, counter_kind: &CoverageKind) -> String {
314         let counter_format = &debug_options().counter_format;
315         if let CoverageKind::Expression { id, lhs, op, rhs } = *counter_kind {
316             if counter_format.operation {
317                 return format!(
318                     "{}{} {} {}",
319                     if counter_format.id || self.some_counters.is_none() {
320                         format!("#{} = ", id.index())
321                     } else {
322                         String::new()
323                     },
324                     self.format_operand(lhs),
325                     if op == Op::Add { "+" } else { "-" },
326                     self.format_operand(rhs),
327                 );
328             }
329         }
330
331         let id: ExpressionOperandId = match *counter_kind {
332             CoverageKind::Counter { id, .. } => id.into(),
333             CoverageKind::Expression { id, .. } => id.into(),
334             _ => {
335                 bug!("the given `CoverageKind` is not an counter or expression: {:?}", counter_kind)
336             }
337         };
338         if self.some_counters.is_some() && (counter_format.block || !counter_format.id) {
339             let counters = self.some_counters.as_ref().unwrap();
340             if let Some(DebugCounter { some_block_label: Some(block_label), .. }) =
341                 counters.get(&id)
342             {
343                 return if counter_format.id {
344                     format!("{}#{}", block_label, id.index())
345                 } else {
346                     block_label.to_string()
347                 };
348             }
349         }
350         format!("#{}", id.index())
351     }
352
353     fn format_operand(&self, operand: ExpressionOperandId) -> String {
354         if operand.index() == 0 {
355             return String::from("0");
356         }
357         if let Some(counters) = &self.some_counters {
358             if let Some(DebugCounter { counter_kind, some_block_label }) = counters.get(&operand) {
359                 if let CoverageKind::Expression { .. } = counter_kind {
360                     if let Some(label) = some_block_label && debug_options().counter_format.block {
361                         return format!(
362                             "{}:({})",
363                             label,
364                             self.format_counter_kind(counter_kind)
365                         );
366                     }
367                     return format!("({})", self.format_counter_kind(counter_kind));
368                 }
369                 return self.format_counter_kind(counter_kind);
370             }
371         }
372         format!("#{}", operand.index())
373     }
374 }
375
376 /// A non-public support class to `DebugCounters`.
377 #[derive(Debug)]
378 struct DebugCounter {
379     counter_kind: CoverageKind,
380     some_block_label: Option<String>,
381 }
382
383 impl DebugCounter {
384     fn new(counter_kind: CoverageKind, some_block_label: Option<String>) -> Self {
385         Self { counter_kind, some_block_label }
386     }
387 }
388
389 /// If enabled, this data structure captures additional debugging information used when generating
390 /// a Graphviz (.dot file) representation of the `CoverageGraph`, for debugging purposes.
391 pub(super) struct GraphvizData {
392     some_bcb_to_coverage_spans_with_counters:
393         Option<FxHashMap<BasicCoverageBlock, Vec<(CoverageSpan, CoverageKind)>>>,
394     some_bcb_to_dependency_counters: Option<FxHashMap<BasicCoverageBlock, Vec<CoverageKind>>>,
395     some_edge_to_counter: Option<FxHashMap<(BasicCoverageBlock, BasicBlock), CoverageKind>>,
396 }
397
398 impl GraphvizData {
399     pub fn new() -> Self {
400         Self {
401             some_bcb_to_coverage_spans_with_counters: None,
402             some_bcb_to_dependency_counters: None,
403             some_edge_to_counter: None,
404         }
405     }
406
407     pub fn enable(&mut self) {
408         debug_assert!(!self.is_enabled());
409         self.some_bcb_to_coverage_spans_with_counters = Some(FxHashMap::default());
410         self.some_bcb_to_dependency_counters = Some(FxHashMap::default());
411         self.some_edge_to_counter = Some(FxHashMap::default());
412     }
413
414     pub fn is_enabled(&self) -> bool {
415         self.some_bcb_to_coverage_spans_with_counters.is_some()
416     }
417
418     pub fn add_bcb_coverage_span_with_counter(
419         &mut self,
420         bcb: BasicCoverageBlock,
421         coverage_span: &CoverageSpan,
422         counter_kind: &CoverageKind,
423     ) {
424         if let Some(bcb_to_coverage_spans_with_counters) =
425             self.some_bcb_to_coverage_spans_with_counters.as_mut()
426         {
427             bcb_to_coverage_spans_with_counters
428                 .entry(bcb)
429                 .or_insert_with(Vec::new)
430                 .push((coverage_span.clone(), counter_kind.clone()));
431         }
432     }
433
434     pub fn get_bcb_coverage_spans_with_counters(
435         &self,
436         bcb: BasicCoverageBlock,
437     ) -> Option<&Vec<(CoverageSpan, CoverageKind)>> {
438         if let Some(bcb_to_coverage_spans_with_counters) =
439             self.some_bcb_to_coverage_spans_with_counters.as_ref()
440         {
441             bcb_to_coverage_spans_with_counters.get(&bcb)
442         } else {
443             None
444         }
445     }
446
447     pub fn add_bcb_dependency_counter(
448         &mut self,
449         bcb: BasicCoverageBlock,
450         counter_kind: &CoverageKind,
451     ) {
452         if let Some(bcb_to_dependency_counters) = self.some_bcb_to_dependency_counters.as_mut() {
453             bcb_to_dependency_counters
454                 .entry(bcb)
455                 .or_insert_with(Vec::new)
456                 .push(counter_kind.clone());
457         }
458     }
459
460     pub fn get_bcb_dependency_counters(
461         &self,
462         bcb: BasicCoverageBlock,
463     ) -> Option<&Vec<CoverageKind>> {
464         if let Some(bcb_to_dependency_counters) = self.some_bcb_to_dependency_counters.as_ref() {
465             bcb_to_dependency_counters.get(&bcb)
466         } else {
467             None
468         }
469     }
470
471     pub fn set_edge_counter(
472         &mut self,
473         from_bcb: BasicCoverageBlock,
474         to_bb: BasicBlock,
475         counter_kind: &CoverageKind,
476     ) {
477         if let Some(edge_to_counter) = self.some_edge_to_counter.as_mut() {
478             edge_to_counter
479                 .try_insert((from_bcb, to_bb), counter_kind.clone())
480                 .expect("invalid attempt to insert more than one edge counter for the same edge");
481         }
482     }
483
484     pub fn get_edge_counter(
485         &self,
486         from_bcb: BasicCoverageBlock,
487         to_bb: BasicBlock,
488     ) -> Option<&CoverageKind> {
489         if let Some(edge_to_counter) = self.some_edge_to_counter.as_ref() {
490             edge_to_counter.get(&(from_bcb, to_bb))
491         } else {
492             None
493         }
494     }
495 }
496
497 /// If enabled, this struct captures additional data used to track whether expressions were used,
498 /// directly or indirectly, to compute the coverage counts for all `CoverageSpan`s, and any that are
499 /// _not_ used are retained in the `unused_expressions` Vec, to be included in debug output (logs
500 /// and/or a `CoverageGraph` graphviz output).
501 pub(super) struct UsedExpressions {
502     some_used_expression_operands:
503         Option<FxHashMap<ExpressionOperandId, Vec<InjectedExpressionId>>>,
504     some_unused_expressions:
505         Option<Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)>>,
506 }
507
508 impl UsedExpressions {
509     pub fn new() -> Self {
510         Self { some_used_expression_operands: None, some_unused_expressions: None }
511     }
512
513     pub fn enable(&mut self) {
514         debug_assert!(!self.is_enabled());
515         self.some_used_expression_operands = Some(FxHashMap::default());
516         self.some_unused_expressions = Some(Vec::new());
517     }
518
519     pub fn is_enabled(&self) -> bool {
520         self.some_used_expression_operands.is_some()
521     }
522
523     pub fn add_expression_operands(&mut self, expression: &CoverageKind) {
524         if let Some(used_expression_operands) = self.some_used_expression_operands.as_mut() {
525             if let CoverageKind::Expression { id, lhs, rhs, .. } = *expression {
526                 used_expression_operands.entry(lhs).or_insert_with(Vec::new).push(id);
527                 used_expression_operands.entry(rhs).or_insert_with(Vec::new).push(id);
528             }
529         }
530     }
531
532     pub fn expression_is_used(&self, expression: &CoverageKind) -> bool {
533         if let Some(used_expression_operands) = self.some_used_expression_operands.as_ref() {
534             used_expression_operands.contains_key(&expression.as_operand_id())
535         } else {
536             false
537         }
538     }
539
540     pub fn add_unused_expression_if_not_found(
541         &mut self,
542         expression: &CoverageKind,
543         edge_from_bcb: Option<BasicCoverageBlock>,
544         target_bcb: BasicCoverageBlock,
545     ) {
546         if let Some(used_expression_operands) = self.some_used_expression_operands.as_ref() {
547             if !used_expression_operands.contains_key(&expression.as_operand_id()) {
548                 self.some_unused_expressions.as_mut().unwrap().push((
549                     expression.clone(),
550                     edge_from_bcb,
551                     target_bcb,
552                 ));
553             }
554         }
555     }
556
557     /// Return the list of unused counters (if any) as a tuple with the counter (`CoverageKind`),
558     /// optional `from_bcb` (if it was an edge counter), and `target_bcb`.
559     pub fn get_unused_expressions(
560         &self,
561     ) -> Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)> {
562         if let Some(unused_expressions) = self.some_unused_expressions.as_ref() {
563             unused_expressions.clone()
564         } else {
565             Vec::new()
566         }
567     }
568
569     /// If enabled, validate that every BCB or edge counter not directly associated with a coverage
570     /// span is at least indirectly associated (it is a dependency of a BCB counter that _is_
571     /// associated with a coverage span).
572     pub fn validate(
573         &mut self,
574         bcb_counters_without_direct_coverage_spans: &Vec<(
575             Option<BasicCoverageBlock>,
576             BasicCoverageBlock,
577             CoverageKind,
578         )>,
579     ) {
580         if self.is_enabled() {
581             let mut not_validated = bcb_counters_without_direct_coverage_spans
582                 .iter()
583                 .map(|(_, _, counter_kind)| counter_kind)
584                 .collect::<Vec<_>>();
585             let mut validating_count = 0;
586             while not_validated.len() != validating_count {
587                 let to_validate = not_validated.split_off(0);
588                 validating_count = to_validate.len();
589                 for counter_kind in to_validate {
590                     if self.expression_is_used(counter_kind) {
591                         self.add_expression_operands(counter_kind);
592                     } else {
593                         not_validated.push(counter_kind);
594                     }
595                 }
596             }
597         }
598     }
599
600     pub fn alert_on_unused_expressions(&self, debug_counters: &DebugCounters) {
601         if let Some(unused_expressions) = self.some_unused_expressions.as_ref() {
602             for (counter_kind, edge_from_bcb, target_bcb) in unused_expressions {
603                 let unused_counter_message = if let Some(from_bcb) = edge_from_bcb.as_ref() {
604                     format!(
605                         "non-coverage edge counter found without a dependent expression, in \
606                         {:?}->{:?}; counter={}",
607                         from_bcb,
608                         target_bcb,
609                         debug_counters.format_counter(&counter_kind),
610                     )
611                 } else {
612                     format!(
613                         "non-coverage counter found without a dependent expression, in {:?}; \
614                         counter={}",
615                         target_bcb,
616                         debug_counters.format_counter(&counter_kind),
617                     )
618                 };
619
620                 if debug_options().allow_unused_expressions {
621                     debug!("WARNING: {}", unused_counter_message);
622                 } else {
623                     bug!("{}", unused_counter_message);
624                 }
625             }
626         }
627     }
628 }
629
630 /// Generates the MIR pass `CoverageSpan`-specific spanview dump file.
631 pub(super) fn dump_coverage_spanview<'tcx>(
632     tcx: TyCtxt<'tcx>,
633     mir_body: &mir::Body<'tcx>,
634     basic_coverage_blocks: &CoverageGraph,
635     pass_name: &str,
636     body_span: Span,
637     coverage_spans: &Vec<CoverageSpan>,
638 ) {
639     let mir_source = mir_body.source;
640     let def_id = mir_source.def_id();
641
642     let span_viewables = span_viewables(tcx, mir_body, basic_coverage_blocks, &coverage_spans);
643     let mut file = create_dump_file(tcx, "html", None, pass_name, &0, mir_source)
644         .expect("Unexpected error creating MIR spanview HTML file");
645     let crate_name = tcx.crate_name(def_id.krate);
646     let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate();
647     let title = format!("{}.{} - Coverage Spans", crate_name, item_name);
648     spanview::write_document(tcx, body_span, span_viewables, &title, &mut file)
649         .expect("Unexpected IO error dumping coverage spans as HTML");
650 }
651
652 /// Converts the computed `BasicCoverageBlockData`s into `SpanViewable`s.
653 fn span_viewables<'tcx>(
654     tcx: TyCtxt<'tcx>,
655     mir_body: &mir::Body<'tcx>,
656     basic_coverage_blocks: &CoverageGraph,
657     coverage_spans: &Vec<CoverageSpan>,
658 ) -> Vec<SpanViewable> {
659     let mut span_viewables = Vec::new();
660     for coverage_span in coverage_spans {
661         let tooltip = coverage_span.format_coverage_statements(tcx, mir_body);
662         let CoverageSpan { span, bcb, .. } = coverage_span;
663         let bcb_data = &basic_coverage_blocks[*bcb];
664         let id = bcb_data.id();
665         let leader_bb = bcb_data.leader_bb();
666         span_viewables.push(SpanViewable { bb: leader_bb, span: *span, id, tooltip });
667     }
668     span_viewables
669 }
670
671 /// Generates the MIR pass coverage-specific graphviz dump file.
672 pub(super) fn dump_coverage_graphviz<'tcx>(
673     tcx: TyCtxt<'tcx>,
674     mir_body: &mir::Body<'tcx>,
675     pass_name: &str,
676     basic_coverage_blocks: &CoverageGraph,
677     debug_counters: &DebugCounters,
678     graphviz_data: &GraphvizData,
679     intermediate_expressions: &Vec<CoverageKind>,
680     debug_used_expressions: &UsedExpressions,
681 ) {
682     let mir_source = mir_body.source;
683     let def_id = mir_source.def_id();
684     let node_content = |bcb| {
685         bcb_to_string_sections(
686             tcx,
687             mir_body,
688             debug_counters,
689             &basic_coverage_blocks[bcb],
690             graphviz_data.get_bcb_coverage_spans_with_counters(bcb),
691             graphviz_data.get_bcb_dependency_counters(bcb),
692             // intermediate_expressions are injected into the mir::START_BLOCK, so
693             // include them in the first BCB.
694             if bcb.index() == 0 { Some(&intermediate_expressions) } else { None },
695         )
696     };
697     let edge_labels = |from_bcb| {
698         let from_bcb_data = &basic_coverage_blocks[from_bcb];
699         let from_terminator = from_bcb_data.terminator(mir_body);
700         let mut edge_labels = from_terminator.kind.fmt_successor_labels();
701         edge_labels.retain(|label| label != "unreachable");
702         let edge_counters = from_terminator
703             .successors()
704             .map(|successor_bb| graphviz_data.get_edge_counter(from_bcb, successor_bb));
705         iter::zip(&edge_labels, edge_counters)
706             .map(|(label, some_counter)| {
707                 if let Some(counter) = some_counter {
708                     format!("{}\n{}", label, debug_counters.format_counter(counter))
709                 } else {
710                     label.to_string()
711                 }
712             })
713             .collect::<Vec<_>>()
714     };
715     let graphviz_name = format!("Cov_{}_{}", def_id.krate.index(), def_id.index.index());
716     let mut graphviz_writer =
717         GraphvizWriter::new(basic_coverage_blocks, &graphviz_name, node_content, edge_labels);
718     let unused_expressions = debug_used_expressions.get_unused_expressions();
719     if unused_expressions.len() > 0 {
720         graphviz_writer.set_graph_label(&format!(
721             "Unused expressions:\n  {}",
722             unused_expressions
723                 .as_slice()
724                 .iter()
725                 .map(|(counter_kind, edge_from_bcb, target_bcb)| {
726                     if let Some(from_bcb) = edge_from_bcb.as_ref() {
727                         format!(
728                             "{:?}->{:?}: {}",
729                             from_bcb,
730                             target_bcb,
731                             debug_counters.format_counter(&counter_kind),
732                         )
733                     } else {
734                         format!(
735                             "{:?}: {}",
736                             target_bcb,
737                             debug_counters.format_counter(&counter_kind),
738                         )
739                     }
740                 })
741                 .join("\n  ")
742         ));
743     }
744     let mut file = create_dump_file(tcx, "dot", None, pass_name, &0, mir_source)
745         .expect("Unexpected error creating BasicCoverageBlock graphviz DOT file");
746     graphviz_writer
747         .write_graphviz(tcx, &mut file)
748         .expect("Unexpected error writing BasicCoverageBlock graphviz DOT file");
749 }
750
751 fn bcb_to_string_sections<'tcx>(
752     tcx: TyCtxt<'tcx>,
753     mir_body: &mir::Body<'tcx>,
754     debug_counters: &DebugCounters,
755     bcb_data: &BasicCoverageBlockData,
756     some_coverage_spans_with_counters: Option<&Vec<(CoverageSpan, CoverageKind)>>,
757     some_dependency_counters: Option<&Vec<CoverageKind>>,
758     some_intermediate_expressions: Option<&Vec<CoverageKind>>,
759 ) -> Vec<String> {
760     let len = bcb_data.basic_blocks.len();
761     let mut sections = Vec::new();
762     if let Some(collect_intermediate_expressions) = some_intermediate_expressions {
763         sections.push(
764             collect_intermediate_expressions
765                 .iter()
766                 .map(|expression| {
767                     format!("Intermediate {}", debug_counters.format_counter(expression))
768                 })
769                 .join("\n"),
770         );
771     }
772     if let Some(coverage_spans_with_counters) = some_coverage_spans_with_counters {
773         sections.push(
774             coverage_spans_with_counters
775                 .iter()
776                 .map(|(covspan, counter)| {
777                     format!(
778                         "{} at {}",
779                         debug_counters.format_counter(counter),
780                         covspan.format(tcx, mir_body)
781                     )
782                 })
783                 .join("\n"),
784         );
785     }
786     if let Some(dependency_counters) = some_dependency_counters {
787         sections.push(format!(
788             "Non-coverage counters:\n  {}",
789             dependency_counters
790                 .iter()
791                 .map(|counter| debug_counters.format_counter(counter))
792                 .join("  \n"),
793         ));
794     }
795     if let Some(counter_kind) = &bcb_data.counter_kind {
796         sections.push(format!("{:?}", counter_kind));
797     }
798     let non_term_blocks = bcb_data.basic_blocks[0..len - 1]
799         .iter()
800         .map(|&bb| format!("{:?}: {}", bb, term_type(&mir_body[bb].terminator().kind)))
801         .collect::<Vec<_>>();
802     if non_term_blocks.len() > 0 {
803         sections.push(non_term_blocks.join("\n"));
804     }
805     sections.push(format!(
806         "{:?}: {}",
807         bcb_data.basic_blocks.last().unwrap(),
808         term_type(&bcb_data.terminator(mir_body).kind)
809     ));
810     sections
811 }
812
813 /// Returns a simple string representation of a `TerminatorKind` variant, independent of any
814 /// values it might hold.
815 pub(super) fn term_type(kind: &TerminatorKind<'_>) -> &'static str {
816     match kind {
817         TerminatorKind::Goto { .. } => "Goto",
818         TerminatorKind::SwitchInt { .. } => "SwitchInt",
819         TerminatorKind::Resume => "Resume",
820         TerminatorKind::Abort => "Abort",
821         TerminatorKind::Return => "Return",
822         TerminatorKind::Unreachable => "Unreachable",
823         TerminatorKind::Drop { .. } => "Drop",
824         TerminatorKind::DropAndReplace { .. } => "DropAndReplace",
825         TerminatorKind::Call { .. } => "Call",
826         TerminatorKind::Assert { .. } => "Assert",
827         TerminatorKind::Yield { .. } => "Yield",
828         TerminatorKind::GeneratorDrop => "GeneratorDrop",
829         TerminatorKind::FalseEdge { .. } => "FalseEdge",
830         TerminatorKind::FalseUnwind { .. } => "FalseUnwind",
831         TerminatorKind::InlineAsm { .. } => "InlineAsm",
832     }
833 }