rustc_mir_transform/coverage/
mod.rs

1use rustc_middle::mir::coverage::{CoverageKind, FunctionCoverageInfo};
2use rustc_middle::mir::{self, BasicBlock, Statement, StatementKind, TerminatorKind};
3use rustc_middle::ty::TyCtxt;
4use tracing::{debug, debug_span, trace};
5
6use crate::coverage::counters::BcbCountersData;
7use crate::coverage::graph::CoverageGraph;
8use crate::coverage::mappings::ExtractedMappings;
9
10mod counters;
11mod expansion;
12mod from_mir;
13mod graph;
14mod hir_info;
15mod mappings;
16pub(super) mod query;
17mod spans;
18#[cfg(test)]
19mod tests;
20mod unexpand;
21
22/// Inserts `StatementKind::Coverage` statements that either instrument the binary with injected
23/// counters, via intrinsic `llvm.instrprof.increment`, and/or inject metadata used during codegen
24/// to construct the coverage map.
25pub(super) struct InstrumentCoverage;
26
27impl<'tcx> crate::MirPass<'tcx> for InstrumentCoverage {
28    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
29        sess.instrument_coverage()
30    }
31
32    fn run_pass(&self, tcx: TyCtxt<'tcx>, mir_body: &mut mir::Body<'tcx>) {
33        let mir_source = mir_body.source;
34
35        // This pass runs after MIR promotion, but before promoted MIR starts to
36        // be transformed, so it should never see promoted MIR.
37        assert!(mir_source.promoted.is_none());
38
39        let def_id = mir_source.def_id().expect_local();
40
41        if !tcx.is_eligible_for_coverage(def_id) {
42            trace!("InstrumentCoverage skipped for {def_id:?} (not eligible)");
43            return;
44        }
45
46        // An otherwise-eligible function is still skipped if its start block
47        // is known to be unreachable.
48        match mir_body.basic_blocks[mir::START_BLOCK].terminator().kind {
49            TerminatorKind::Unreachable => {
50                trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`");
51                return;
52            }
53            _ => {}
54        }
55
56        instrument_function_for_coverage(tcx, mir_body);
57    }
58
59    fn is_required(&self) -> bool {
60        false
61    }
62}
63
64fn instrument_function_for_coverage<'tcx>(tcx: TyCtxt<'tcx>, mir_body: &mut mir::Body<'tcx>) {
65    let def_id = mir_body.source.def_id();
66    let _span = debug_span!("instrument_function_for_coverage", ?def_id).entered();
67
68    let hir_info = hir_info::extract_hir_info(tcx, def_id.expect_local());
69
70    // Build the coverage graph, which is a simplified view of the MIR control-flow
71    // graph that ignores some details not relevant to coverage instrumentation.
72    let graph = CoverageGraph::from_mir(mir_body);
73
74    ////////////////////////////////////////////////////
75    // Extract coverage spans and other mapping info from MIR.
76    let ExtractedMappings { mappings } =
77        mappings::extract_mappings_from_mir(tcx, mir_body, &hir_info, &graph);
78    if mappings.is_empty() {
79        // No spans could be converted into valid mappings, so skip this function.
80        debug!("no spans could be converted into valid mappings; skipping");
81        return;
82    }
83
84    // Use the coverage graph to prepare intermediate data that will eventually
85    // be used to assign physical counters and counter expressions to points in
86    // the control-flow graph.
87    let BcbCountersData { node_flow_data, priority_list } =
88        counters::prepare_bcb_counters_data(&graph);
89
90    // Inject coverage statements into MIR.
91    inject_coverage_statements(mir_body, &graph);
92
93    mir_body.function_coverage_info = Some(Box::new(FunctionCoverageInfo {
94        function_source_hash: hir_info.function_source_hash,
95
96        node_flow_data,
97        priority_list,
98
99        mappings,
100    }));
101}
102
103/// Inject any necessary coverage statements into MIR, so that they influence codegen.
104fn inject_coverage_statements<'tcx>(mir_body: &mut mir::Body<'tcx>, graph: &CoverageGraph) {
105    for (bcb, data) in graph.iter_enumerated() {
106        let target_bb = data.leader_bb();
107        inject_statement(mir_body, CoverageKind::VirtualCounter { bcb }, target_bb);
108    }
109}
110
111fn inject_statement(mir_body: &mut mir::Body<'_>, counter_kind: CoverageKind, bb: BasicBlock) {
112    debug!("  injecting statement {counter_kind:?} for {bb:?}");
113    let data = &mut mir_body[bb];
114    let source_info = data.terminator().source_info;
115    let statement = Statement::new(source_info, StatementKind::Coverage(counter_kind));
116    data.statements.insert(0, statement);
117}