]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/coverage/debug.rs
Auto merge of #99725 - lcnr:dedup-region_bound_pairs, r=compiler-errors
[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::ops::Deref;
127 use std::sync::OnceLock;
128
129 pub const NESTED_INDENT: &str = "    ";
130
131 const RUSTC_COVERAGE_DEBUG_OPTIONS: &str = "RUSTC_COVERAGE_DEBUG_OPTIONS";
132
133 pub(super) fn debug_options<'a>() -> &'a DebugOptions {
134     static DEBUG_OPTIONS: OnceLock<DebugOptions> = OnceLock::new();
135
136     &DEBUG_OPTIONS.get_or_init(DebugOptions::from_env)
137 }
138
139 /// Parses and maintains coverage-specific debug options captured from the environment variable
140 /// "RUSTC_COVERAGE_DEBUG_OPTIONS", if set.
141 #[derive(Debug, Clone)]
142 pub(super) struct DebugOptions {
143     pub allow_unused_expressions: bool,
144     counter_format: ExpressionFormat,
145 }
146
147 impl DebugOptions {
148     fn from_env() -> Self {
149         let mut allow_unused_expressions = true;
150         let mut counter_format = ExpressionFormat::default();
151
152         if let Ok(env_debug_options) = std::env::var(RUSTC_COVERAGE_DEBUG_OPTIONS) {
153             for setting_str in env_debug_options.replace(' ', "").replace('-', "_").split(',') {
154                 let (option, value) = match setting_str.split_once('=') {
155                     None => (setting_str, None),
156                     Some((k, v)) => (k, Some(v)),
157                 };
158                 match option {
159                     "allow_unused_expressions" => {
160                         allow_unused_expressions = bool_option_val(option, value);
161                         debug!(
162                             "{} env option `allow_unused_expressions` is set to {}",
163                             RUSTC_COVERAGE_DEBUG_OPTIONS, allow_unused_expressions
164                         );
165                     }
166                     "counter_format" => {
167                         match value {
168                             None => {
169                                 bug!(
170                                     "`{}` option in environment variable {} requires one or more \
171                                     plus-separated choices (a non-empty subset of \
172                                     `id+block+operation`)",
173                                     option,
174                                     RUSTC_COVERAGE_DEBUG_OPTIONS
175                                 );
176                             }
177                             Some(val) => {
178                                 counter_format = counter_format_option_val(val);
179                                 debug!(
180                                     "{} env option `counter_format` is set to {:?}",
181                                     RUSTC_COVERAGE_DEBUG_OPTIONS, counter_format
182                                 );
183                             }
184                         };
185                     }
186                     _ => bug!(
187                         "Unsupported setting `{}` in environment variable {}",
188                         option,
189                         RUSTC_COVERAGE_DEBUG_OPTIONS
190                     ),
191                 };
192             }
193         }
194
195         Self { allow_unused_expressions, counter_format }
196     }
197 }
198
199 fn bool_option_val(option: &str, some_strval: Option<&str>) -> bool {
200     if let Some(val) = some_strval {
201         if vec!["yes", "y", "on", "true"].contains(&val) {
202             true
203         } else if vec!["no", "n", "off", "false"].contains(&val) {
204             false
205         } else {
206             bug!(
207                 "Unsupported value `{}` for option `{}` in environment variable {}",
208                 option,
209                 val,
210                 RUSTC_COVERAGE_DEBUG_OPTIONS
211             )
212         }
213     } else {
214         true
215     }
216 }
217
218 fn counter_format_option_val(strval: &str) -> ExpressionFormat {
219     let mut counter_format = ExpressionFormat { id: false, block: false, operation: false };
220     let components = strval.splitn(3, '+');
221     for component in components {
222         match component {
223             "id" => counter_format.id = true,
224             "block" => counter_format.block = true,
225             "operation" => counter_format.operation = true,
226             _ => bug!(
227                 "Unsupported counter_format choice `{}` in environment variable {}",
228                 component,
229                 RUSTC_COVERAGE_DEBUG_OPTIONS
230             ),
231         }
232     }
233     counter_format
234 }
235
236 #[derive(Debug, Clone)]
237 struct ExpressionFormat {
238     id: bool,
239     block: bool,
240     operation: bool,
241 }
242
243 impl Default for ExpressionFormat {
244     fn default() -> Self {
245         Self { id: false, block: true, operation: true }
246     }
247 }
248
249 /// If enabled, this struct maintains a map from `CoverageKind` IDs (as `ExpressionOperandId`) to
250 /// the `CoverageKind` data and optional label (normally, the counter's associated
251 /// `BasicCoverageBlock` format string, if any).
252 ///
253 /// Use `format_counter` to convert one of these `CoverageKind` counters to a debug output string,
254 /// as directed by the `DebugOptions`. This allows the format of counter labels in logs and dump
255 /// files (including the `CoverageGraph` graphviz file) to be changed at runtime, via environment
256 /// variable.
257 ///
258 /// `DebugCounters` supports a recursive rendering of `Expression` counters, so they can be
259 /// presented as nested expressions such as `(bcb3 - (bcb0 + bcb1))`.
260 pub(super) struct DebugCounters {
261     some_counters: Option<FxHashMap<ExpressionOperandId, DebugCounter>>,
262 }
263
264 impl DebugCounters {
265     pub fn new() -> Self {
266         Self { some_counters: None }
267     }
268
269     pub fn enable(&mut self) {
270         debug_assert!(!self.is_enabled());
271         self.some_counters.replace(FxHashMap::default());
272     }
273
274     pub fn is_enabled(&self) -> bool {
275         self.some_counters.is_some()
276     }
277
278     pub fn add_counter(&mut self, counter_kind: &CoverageKind, some_block_label: Option<String>) {
279         if let Some(counters) = &mut self.some_counters {
280             let id: ExpressionOperandId = match *counter_kind {
281                 CoverageKind::Counter { id, .. } => id.into(),
282                 CoverageKind::Expression { id, .. } => id.into(),
283                 _ => bug!(
284                     "the given `CoverageKind` is not an counter or expression: {:?}",
285                     counter_kind
286                 ),
287             };
288             counters
289                 .try_insert(id, DebugCounter::new(counter_kind.clone(), some_block_label))
290                 .expect("attempt to add the same counter_kind to DebugCounters more than once");
291         }
292     }
293
294     pub fn some_block_label(&self, operand: ExpressionOperandId) -> Option<&String> {
295         self.some_counters.as_ref().map_or(None, |counters| {
296             counters
297                 .get(&operand)
298                 .map_or(None, |debug_counter| debug_counter.some_block_label.as_ref())
299         })
300     }
301
302     pub fn format_counter(&self, counter_kind: &CoverageKind) -> String {
303         match *counter_kind {
304             CoverageKind::Counter { .. } => {
305                 format!("Counter({})", self.format_counter_kind(counter_kind))
306             }
307             CoverageKind::Expression { .. } => {
308                 format!("Expression({})", self.format_counter_kind(counter_kind))
309             }
310             CoverageKind::Unreachable { .. } => "Unreachable".to_owned(),
311         }
312     }
313
314     fn format_counter_kind(&self, counter_kind: &CoverageKind) -> String {
315         let counter_format = &debug_options().counter_format;
316         if let CoverageKind::Expression { id, lhs, op, rhs } = *counter_kind {
317             if counter_format.operation {
318                 return format!(
319                     "{}{} {} {}",
320                     if counter_format.id || self.some_counters.is_none() {
321                         format!("#{} = ", id.index())
322                     } else {
323                         String::new()
324                     },
325                     self.format_operand(lhs),
326                     if op == Op::Add { "+" } else { "-" },
327                     self.format_operand(rhs),
328                 );
329             }
330         }
331
332         let id: ExpressionOperandId = match *counter_kind {
333             CoverageKind::Counter { id, .. } => id.into(),
334             CoverageKind::Expression { id, .. } => id.into(),
335             _ => {
336                 bug!("the given `CoverageKind` is not an counter or expression: {:?}", counter_kind)
337             }
338         };
339         if self.some_counters.is_some() && (counter_format.block || !counter_format.id) {
340             let counters = self.some_counters.as_ref().unwrap();
341             if let Some(DebugCounter { some_block_label: Some(block_label), .. }) =
342                 counters.get(&id)
343             {
344                 return if counter_format.id {
345                     format!("{}#{}", block_label, id.index())
346                 } else {
347                     block_label.to_string()
348                 };
349             }
350         }
351         format!("#{}", id.index())
352     }
353
354     fn format_operand(&self, operand: ExpressionOperandId) -> String {
355         if operand.index() == 0 {
356             return String::from("0");
357         }
358         if let Some(counters) = &self.some_counters {
359             if let Some(DebugCounter { counter_kind, some_block_label }) = counters.get(&operand) {
360                 if let CoverageKind::Expression { .. } = counter_kind {
361                     if let Some(label) = some_block_label && debug_options().counter_format.block {
362                         return format!(
363                             "{}:({})",
364                             label,
365                             self.format_counter_kind(counter_kind)
366                         );
367                     }
368                     return format!("({})", self.format_counter_kind(counter_kind));
369                 }
370                 return self.format_counter_kind(counter_kind);
371             }
372         }
373         format!("#{}", operand.index())
374     }
375 }
376
377 /// A non-public support class to `DebugCounters`.
378 #[derive(Debug)]
379 struct DebugCounter {
380     counter_kind: CoverageKind,
381     some_block_label: Option<String>,
382 }
383
384 impl DebugCounter {
385     fn new(counter_kind: CoverageKind, some_block_label: Option<String>) -> Self {
386         Self { counter_kind, some_block_label }
387     }
388 }
389
390 /// If enabled, this data structure captures additional debugging information used when generating
391 /// a Graphviz (.dot file) representation of the `CoverageGraph`, for debugging purposes.
392 pub(super) struct GraphvizData {
393     some_bcb_to_coverage_spans_with_counters:
394         Option<FxHashMap<BasicCoverageBlock, Vec<(CoverageSpan, CoverageKind)>>>,
395     some_bcb_to_dependency_counters: Option<FxHashMap<BasicCoverageBlock, Vec<CoverageKind>>>,
396     some_edge_to_counter: Option<FxHashMap<(BasicCoverageBlock, BasicBlock), CoverageKind>>,
397 }
398
399 impl GraphvizData {
400     pub fn new() -> Self {
401         Self {
402             some_bcb_to_coverage_spans_with_counters: None,
403             some_bcb_to_dependency_counters: None,
404             some_edge_to_counter: None,
405         }
406     }
407
408     pub fn enable(&mut self) {
409         debug_assert!(!self.is_enabled());
410         self.some_bcb_to_coverage_spans_with_counters = Some(FxHashMap::default());
411         self.some_bcb_to_dependency_counters = Some(FxHashMap::default());
412         self.some_edge_to_counter = Some(FxHashMap::default());
413     }
414
415     pub fn is_enabled(&self) -> bool {
416         self.some_bcb_to_coverage_spans_with_counters.is_some()
417     }
418
419     pub fn add_bcb_coverage_span_with_counter(
420         &mut self,
421         bcb: BasicCoverageBlock,
422         coverage_span: &CoverageSpan,
423         counter_kind: &CoverageKind,
424     ) {
425         if let Some(bcb_to_coverage_spans_with_counters) =
426             self.some_bcb_to_coverage_spans_with_counters.as_mut()
427         {
428             bcb_to_coverage_spans_with_counters
429                 .entry(bcb)
430                 .or_insert_with(Vec::new)
431                 .push((coverage_span.clone(), counter_kind.clone()));
432         }
433     }
434
435     pub fn get_bcb_coverage_spans_with_counters(
436         &self,
437         bcb: BasicCoverageBlock,
438     ) -> Option<&[(CoverageSpan, CoverageKind)]> {
439         if let Some(bcb_to_coverage_spans_with_counters) =
440             self.some_bcb_to_coverage_spans_with_counters.as_ref()
441         {
442             bcb_to_coverage_spans_with_counters.get(&bcb).map(Deref::deref)
443         } else {
444             None
445         }
446     }
447
448     pub fn add_bcb_dependency_counter(
449         &mut self,
450         bcb: BasicCoverageBlock,
451         counter_kind: &CoverageKind,
452     ) {
453         if let Some(bcb_to_dependency_counters) = self.some_bcb_to_dependency_counters.as_mut() {
454             bcb_to_dependency_counters
455                 .entry(bcb)
456                 .or_insert_with(Vec::new)
457                 .push(counter_kind.clone());
458         }
459     }
460
461     pub fn get_bcb_dependency_counters(&self, bcb: BasicCoverageBlock) -> Option<&[CoverageKind]> {
462         if let Some(bcb_to_dependency_counters) = self.some_bcb_to_dependency_counters.as_ref() {
463             bcb_to_dependency_counters.get(&bcb).map(Deref::deref)
464         } else {
465             None
466         }
467     }
468
469     pub fn set_edge_counter(
470         &mut self,
471         from_bcb: BasicCoverageBlock,
472         to_bb: BasicBlock,
473         counter_kind: &CoverageKind,
474     ) {
475         if let Some(edge_to_counter) = self.some_edge_to_counter.as_mut() {
476             edge_to_counter
477                 .try_insert((from_bcb, to_bb), counter_kind.clone())
478                 .expect("invalid attempt to insert more than one edge counter for the same edge");
479         }
480     }
481
482     pub fn get_edge_counter(
483         &self,
484         from_bcb: BasicCoverageBlock,
485         to_bb: BasicBlock,
486     ) -> Option<&CoverageKind> {
487         if let Some(edge_to_counter) = self.some_edge_to_counter.as_ref() {
488             edge_to_counter.get(&(from_bcb, to_bb))
489         } else {
490             None
491         }
492     }
493 }
494
495 /// If enabled, this struct captures additional data used to track whether expressions were used,
496 /// directly or indirectly, to compute the coverage counts for all `CoverageSpan`s, and any that are
497 /// _not_ used are retained in the `unused_expressions` Vec, to be included in debug output (logs
498 /// and/or a `CoverageGraph` graphviz output).
499 pub(super) struct UsedExpressions {
500     some_used_expression_operands:
501         Option<FxHashMap<ExpressionOperandId, Vec<InjectedExpressionId>>>,
502     some_unused_expressions:
503         Option<Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)>>,
504 }
505
506 impl UsedExpressions {
507     pub fn new() -> Self {
508         Self { some_used_expression_operands: None, some_unused_expressions: None }
509     }
510
511     pub fn enable(&mut self) {
512         debug_assert!(!self.is_enabled());
513         self.some_used_expression_operands = Some(FxHashMap::default());
514         self.some_unused_expressions = Some(Vec::new());
515     }
516
517     pub fn is_enabled(&self) -> bool {
518         self.some_used_expression_operands.is_some()
519     }
520
521     pub fn add_expression_operands(&mut self, expression: &CoverageKind) {
522         if let Some(used_expression_operands) = self.some_used_expression_operands.as_mut() {
523             if let CoverageKind::Expression { id, lhs, rhs, .. } = *expression {
524                 used_expression_operands.entry(lhs).or_insert_with(Vec::new).push(id);
525                 used_expression_operands.entry(rhs).or_insert_with(Vec::new).push(id);
526             }
527         }
528     }
529
530     pub fn expression_is_used(&self, expression: &CoverageKind) -> bool {
531         if let Some(used_expression_operands) = self.some_used_expression_operands.as_ref() {
532             used_expression_operands.contains_key(&expression.as_operand_id())
533         } else {
534             false
535         }
536     }
537
538     pub fn add_unused_expression_if_not_found(
539         &mut self,
540         expression: &CoverageKind,
541         edge_from_bcb: Option<BasicCoverageBlock>,
542         target_bcb: BasicCoverageBlock,
543     ) {
544         if let Some(used_expression_operands) = self.some_used_expression_operands.as_ref() {
545             if !used_expression_operands.contains_key(&expression.as_operand_id()) {
546                 self.some_unused_expressions.as_mut().unwrap().push((
547                     expression.clone(),
548                     edge_from_bcb,
549                     target_bcb,
550                 ));
551             }
552         }
553     }
554
555     /// Return the list of unused counters (if any) as a tuple with the counter (`CoverageKind`),
556     /// optional `from_bcb` (if it was an edge counter), and `target_bcb`.
557     pub fn get_unused_expressions(
558         &self,
559     ) -> Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)> {
560         if let Some(unused_expressions) = self.some_unused_expressions.as_ref() {
561             unused_expressions.clone()
562         } else {
563             Vec::new()
564         }
565     }
566
567     /// If enabled, validate that every BCB or edge counter not directly associated with a coverage
568     /// span is at least indirectly associated (it is a dependency of a BCB counter that _is_
569     /// associated with a coverage span).
570     pub fn validate(
571         &mut self,
572         bcb_counters_without_direct_coverage_spans: &[(
573             Option<BasicCoverageBlock>,
574             BasicCoverageBlock,
575             CoverageKind,
576         )],
577     ) {
578         if self.is_enabled() {
579             let mut not_validated = bcb_counters_without_direct_coverage_spans
580                 .iter()
581                 .map(|(_, _, counter_kind)| counter_kind)
582                 .collect::<Vec<_>>();
583             let mut validating_count = 0;
584             while not_validated.len() != validating_count {
585                 let to_validate = not_validated.split_off(0);
586                 validating_count = to_validate.len();
587                 for counter_kind in to_validate {
588                     if self.expression_is_used(counter_kind) {
589                         self.add_expression_operands(counter_kind);
590                     } else {
591                         not_validated.push(counter_kind);
592                     }
593                 }
594             }
595         }
596     }
597
598     pub fn alert_on_unused_expressions(&self, debug_counters: &DebugCounters) {
599         if let Some(unused_expressions) = self.some_unused_expressions.as_ref() {
600             for (counter_kind, edge_from_bcb, target_bcb) in unused_expressions {
601                 let unused_counter_message = if let Some(from_bcb) = edge_from_bcb.as_ref() {
602                     format!(
603                         "non-coverage edge counter found without a dependent expression, in \
604                         {:?}->{:?}; counter={}",
605                         from_bcb,
606                         target_bcb,
607                         debug_counters.format_counter(&counter_kind),
608                     )
609                 } else {
610                     format!(
611                         "non-coverage counter found without a dependent expression, in {:?}; \
612                         counter={}",
613                         target_bcb,
614                         debug_counters.format_counter(&counter_kind),
615                     )
616                 };
617
618                 if debug_options().allow_unused_expressions {
619                     debug!("WARNING: {}", unused_counter_message);
620                 } else {
621                     bug!("{}", unused_counter_message);
622                 }
623             }
624         }
625     }
626 }
627
628 /// Generates the MIR pass `CoverageSpan`-specific spanview dump file.
629 pub(super) fn dump_coverage_spanview<'tcx>(
630     tcx: TyCtxt<'tcx>,
631     mir_body: &mir::Body<'tcx>,
632     basic_coverage_blocks: &CoverageGraph,
633     pass_name: &str,
634     body_span: Span,
635     coverage_spans: &[CoverageSpan],
636 ) {
637     let mir_source = mir_body.source;
638     let def_id = mir_source.def_id();
639
640     let span_viewables = span_viewables(tcx, mir_body, basic_coverage_blocks, &coverage_spans);
641     let mut file = create_dump_file(tcx, "html", None, pass_name, &0, mir_source)
642         .expect("Unexpected error creating MIR spanview HTML file");
643     let crate_name = tcx.crate_name(def_id.krate);
644     let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate();
645     let title = format!("{}.{} - Coverage Spans", crate_name, item_name);
646     spanview::write_document(tcx, body_span, span_viewables, &title, &mut file)
647         .expect("Unexpected IO error dumping coverage spans as HTML");
648 }
649
650 /// Converts the computed `BasicCoverageBlockData`s into `SpanViewable`s.
651 fn span_viewables<'tcx>(
652     tcx: TyCtxt<'tcx>,
653     mir_body: &mir::Body<'tcx>,
654     basic_coverage_blocks: &CoverageGraph,
655     coverage_spans: &[CoverageSpan],
656 ) -> Vec<SpanViewable> {
657     let mut span_viewables = Vec::new();
658     for coverage_span in coverage_spans {
659         let tooltip = coverage_span.format_coverage_statements(tcx, mir_body);
660         let CoverageSpan { span, bcb, .. } = coverage_span;
661         let bcb_data = &basic_coverage_blocks[*bcb];
662         let id = bcb_data.id();
663         let leader_bb = bcb_data.leader_bb();
664         span_viewables.push(SpanViewable { bb: leader_bb, span: *span, id, tooltip });
665     }
666     span_viewables
667 }
668
669 /// Generates the MIR pass coverage-specific graphviz dump file.
670 pub(super) fn dump_coverage_graphviz<'tcx>(
671     tcx: TyCtxt<'tcx>,
672     mir_body: &mir::Body<'tcx>,
673     pass_name: &str,
674     basic_coverage_blocks: &CoverageGraph,
675     debug_counters: &DebugCounters,
676     graphviz_data: &GraphvizData,
677     intermediate_expressions: &[CoverageKind],
678     debug_used_expressions: &UsedExpressions,
679 ) {
680     let mir_source = mir_body.source;
681     let def_id = mir_source.def_id();
682     let node_content = |bcb| {
683         bcb_to_string_sections(
684             tcx,
685             mir_body,
686             debug_counters,
687             &basic_coverage_blocks[bcb],
688             graphviz_data.get_bcb_coverage_spans_with_counters(bcb),
689             graphviz_data.get_bcb_dependency_counters(bcb),
690             // intermediate_expressions are injected into the mir::START_BLOCK, so
691             // include them in the first BCB.
692             if bcb.index() == 0 { Some(&intermediate_expressions) } else { None },
693         )
694     };
695     let edge_labels = |from_bcb| {
696         let from_bcb_data = &basic_coverage_blocks[from_bcb];
697         let from_terminator = from_bcb_data.terminator(mir_body);
698         let mut edge_labels = from_terminator.kind.fmt_successor_labels();
699         edge_labels.retain(|label| label != "unreachable");
700         let edge_counters = from_terminator
701             .successors()
702             .map(|successor_bb| graphviz_data.get_edge_counter(from_bcb, successor_bb));
703         iter::zip(&edge_labels, edge_counters)
704             .map(|(label, some_counter)| {
705                 if let Some(counter) = some_counter {
706                     format!("{}\n{}", label, debug_counters.format_counter(counter))
707                 } else {
708                     label.to_string()
709                 }
710             })
711             .collect::<Vec<_>>()
712     };
713     let graphviz_name = format!("Cov_{}_{}", def_id.krate.index(), def_id.index.index());
714     let mut graphviz_writer =
715         GraphvizWriter::new(basic_coverage_blocks, &graphviz_name, node_content, edge_labels);
716     let unused_expressions = debug_used_expressions.get_unused_expressions();
717     if unused_expressions.len() > 0 {
718         graphviz_writer.set_graph_label(&format!(
719             "Unused expressions:\n  {}",
720             unused_expressions
721                 .as_slice()
722                 .iter()
723                 .map(|(counter_kind, edge_from_bcb, target_bcb)| {
724                     if let Some(from_bcb) = edge_from_bcb.as_ref() {
725                         format!(
726                             "{:?}->{:?}: {}",
727                             from_bcb,
728                             target_bcb,
729                             debug_counters.format_counter(&counter_kind),
730                         )
731                     } else {
732                         format!(
733                             "{:?}: {}",
734                             target_bcb,
735                             debug_counters.format_counter(&counter_kind),
736                         )
737                     }
738                 })
739                 .join("\n  ")
740         ));
741     }
742     let mut file = create_dump_file(tcx, "dot", None, pass_name, &0, mir_source)
743         .expect("Unexpected error creating BasicCoverageBlock graphviz DOT file");
744     graphviz_writer
745         .write_graphviz(tcx, &mut file)
746         .expect("Unexpected error writing BasicCoverageBlock graphviz DOT file");
747 }
748
749 fn bcb_to_string_sections<'tcx>(
750     tcx: TyCtxt<'tcx>,
751     mir_body: &mir::Body<'tcx>,
752     debug_counters: &DebugCounters,
753     bcb_data: &BasicCoverageBlockData,
754     some_coverage_spans_with_counters: Option<&[(CoverageSpan, CoverageKind)]>,
755     some_dependency_counters: Option<&[CoverageKind]>,
756     some_intermediate_expressions: Option<&[CoverageKind]>,
757 ) -> Vec<String> {
758     let len = bcb_data.basic_blocks.len();
759     let mut sections = Vec::new();
760     if let Some(collect_intermediate_expressions) = some_intermediate_expressions {
761         sections.push(
762             collect_intermediate_expressions
763                 .iter()
764                 .map(|expression| {
765                     format!("Intermediate {}", debug_counters.format_counter(expression))
766                 })
767                 .join("\n"),
768         );
769     }
770     if let Some(coverage_spans_with_counters) = some_coverage_spans_with_counters {
771         sections.push(
772             coverage_spans_with_counters
773                 .iter()
774                 .map(|(covspan, counter)| {
775                     format!(
776                         "{} at {}",
777                         debug_counters.format_counter(counter),
778                         covspan.format(tcx, mir_body)
779                     )
780                 })
781                 .join("\n"),
782         );
783     }
784     if let Some(dependency_counters) = some_dependency_counters {
785         sections.push(format!(
786             "Non-coverage counters:\n  {}",
787             dependency_counters
788                 .iter()
789                 .map(|counter| debug_counters.format_counter(counter))
790                 .join("  \n"),
791         ));
792     }
793     if let Some(counter_kind) = &bcb_data.counter_kind {
794         sections.push(format!("{:?}", counter_kind));
795     }
796     let non_term_blocks = bcb_data.basic_blocks[0..len - 1]
797         .iter()
798         .map(|&bb| format!("{:?}: {}", bb, term_type(&mir_body[bb].terminator().kind)))
799         .collect::<Vec<_>>();
800     if non_term_blocks.len() > 0 {
801         sections.push(non_term_blocks.join("\n"));
802     }
803     sections.push(format!(
804         "{:?}: {}",
805         bcb_data.basic_blocks.last().unwrap(),
806         term_type(&bcb_data.terminator(mir_body).kind)
807     ));
808     sections
809 }
810
811 /// Returns a simple string representation of a `TerminatorKind` variant, independent of any
812 /// values it might hold.
813 pub(super) fn term_type(kind: &TerminatorKind<'_>) -> &'static str {
814     match kind {
815         TerminatorKind::Goto { .. } => "Goto",
816         TerminatorKind::SwitchInt { .. } => "SwitchInt",
817         TerminatorKind::Resume => "Resume",
818         TerminatorKind::Abort => "Abort",
819         TerminatorKind::Return => "Return",
820         TerminatorKind::Unreachable => "Unreachable",
821         TerminatorKind::Drop { .. } => "Drop",
822         TerminatorKind::DropAndReplace { .. } => "DropAndReplace",
823         TerminatorKind::Call { .. } => "Call",
824         TerminatorKind::Assert { .. } => "Assert",
825         TerminatorKind::Yield { .. } => "Yield",
826         TerminatorKind::GeneratorDrop => "GeneratorDrop",
827         TerminatorKind::FalseEdge { .. } => "FalseEdge",
828         TerminatorKind::FalseUnwind { .. } => "FalseUnwind",
829         TerminatorKind::InlineAsm { .. } => "InlineAsm",
830     }
831 }