rustc_mir_transform/coverage/
query.rs

1use rustc_attr_data_structures::{AttributeKind, CoverageStatus, find_attr};
2use rustc_index::bit_set::DenseBitSet;
3use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
4use rustc_middle::mir::coverage::{BasicCoverageBlock, CoverageIdsInfo, CoverageKind, MappingKind};
5use rustc_middle::mir::{Body, Statement, StatementKind};
6use rustc_middle::ty::{self, TyCtxt};
7use rustc_middle::util::Providers;
8use rustc_span::def_id::LocalDefId;
9use tracing::trace;
10
11use crate::coverage::counters::node_flow::make_node_counters;
12use crate::coverage::counters::{CoverageCounters, transcribe_counters};
13
14/// Registers query/hook implementations related to coverage.
15pub(crate) fn provide(providers: &mut Providers) {
16    providers.hooks.is_eligible_for_coverage = is_eligible_for_coverage;
17    providers.queries.coverage_attr_on = coverage_attr_on;
18    providers.queries.coverage_ids_info = coverage_ids_info;
19}
20
21/// Hook implementation for [`TyCtxt::is_eligible_for_coverage`].
22fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
23    // Only instrument functions, methods, and closures (not constants since they are evaluated
24    // at compile time by Miri).
25    // FIXME(#73156): Handle source code coverage in const eval, but note, if and when const
26    // expressions get coverage spans, we will probably have to "carve out" space for const
27    // expressions from coverage spans in enclosing MIR's, like we do for closures. (That might
28    // be tricky if const expressions have no corresponding statements in the enclosing MIR.
29    // Closures are carved out by their initial `Assign` statement.)
30    if !tcx.def_kind(def_id).is_fn_like() {
31        trace!("InstrumentCoverage skipped for {def_id:?} (not an fn-like)");
32        return false;
33    }
34
35    // Don't instrument functions with `#[automatically_derived]` on their
36    // enclosing impl block, on the assumption that most users won't care about
37    // coverage for derived impls.
38    if let Some(impl_of) = tcx.impl_of_method(def_id.to_def_id())
39        && tcx.is_automatically_derived(impl_of)
40    {
41        trace!("InstrumentCoverage skipped for {def_id:?} (automatically derived)");
42        return false;
43    }
44
45    if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) {
46        trace!("InstrumentCoverage skipped for {def_id:?} (`#[naked]`)");
47        return false;
48    }
49
50    if !tcx.coverage_attr_on(def_id) {
51        trace!("InstrumentCoverage skipped for {def_id:?} (`#[coverage(off)]`)");
52        return false;
53    }
54
55    true
56}
57
58/// Query implementation for `coverage_attr_on`.
59fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
60    // Check for annotations directly on this def.
61    if let Some(coverage_status) =
62        find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Coverage(_, status) => status)
63    {
64        *coverage_status == CoverageStatus::On
65    } else {
66        match tcx.opt_local_parent(def_id) {
67            // Check the parent def (and so on recursively) until we find an
68            // enclosing attribute or reach the crate root.
69            Some(parent) => tcx.coverage_attr_on(parent),
70            // We reached the crate root without seeing a coverage attribute, so
71            // allow coverage instrumentation by default.
72            None => true,
73        }
74    }
75}
76
77/// Query implementation for `coverage_ids_info`.
78fn coverage_ids_info<'tcx>(
79    tcx: TyCtxt<'tcx>,
80    instance_def: ty::InstanceKind<'tcx>,
81) -> Option<CoverageIdsInfo> {
82    let mir_body = tcx.instance_mir(instance_def);
83    let fn_cov_info = mir_body.function_coverage_info.as_deref()?;
84
85    // Scan through the final MIR to see which BCBs survived MIR opts.
86    // Any BCB not in this set was optimized away.
87    let mut bcbs_seen = DenseBitSet::new_empty(fn_cov_info.priority_list.len());
88    for kind in all_coverage_in_mir_body(mir_body) {
89        match *kind {
90            CoverageKind::VirtualCounter { bcb } => {
91                bcbs_seen.insert(bcb);
92            }
93            _ => {}
94        }
95    }
96
97    // Determine the set of BCBs that are referred to by mappings, and therefore
98    // need a counter. Any node not in this set will only get a counter if it
99    // is part of the counter expression for a node that is in the set.
100    let mut bcb_needs_counter =
101        DenseBitSet::<BasicCoverageBlock>::new_empty(fn_cov_info.priority_list.len());
102    for mapping in &fn_cov_info.mappings {
103        match mapping.kind {
104            MappingKind::Code { bcb } => {
105                bcb_needs_counter.insert(bcb);
106            }
107            MappingKind::Branch { true_bcb, false_bcb } => {
108                bcb_needs_counter.insert(true_bcb);
109                bcb_needs_counter.insert(false_bcb);
110            }
111            MappingKind::MCDCBranch { true_bcb, false_bcb, mcdc_params: _ } => {
112                bcb_needs_counter.insert(true_bcb);
113                bcb_needs_counter.insert(false_bcb);
114            }
115            MappingKind::MCDCDecision(_) => {}
116        }
117    }
118
119    // Clone the priority list so that we can re-sort it.
120    let mut priority_list = fn_cov_info.priority_list.clone();
121    // The first ID in the priority list represents the synthetic "sink" node,
122    // and must remain first so that it _never_ gets a physical counter.
123    debug_assert_eq!(priority_list[0], priority_list.iter().copied().max().unwrap());
124    assert!(!bcbs_seen.contains(priority_list[0]));
125    // Partition the priority list, so that unreachable nodes (removed by MIR opts)
126    // are sorted later and therefore are _more_ likely to get a physical counter.
127    // This is counter-intuitive, but it means that `transcribe_counters` can
128    // easily skip those unused physical counters and replace them with zero.
129    // (The original ordering remains in effect within both partitions.)
130    priority_list[1..].sort_by_key(|&bcb| !bcbs_seen.contains(bcb));
131
132    let node_counters = make_node_counters(&fn_cov_info.node_flow_data, &priority_list);
133    let coverage_counters = transcribe_counters(&node_counters, &bcb_needs_counter, &bcbs_seen);
134
135    let CoverageCounters {
136        phys_counter_for_node, next_counter_id, node_counters, expressions, ..
137    } = coverage_counters;
138
139    Some(CoverageIdsInfo {
140        num_counters: next_counter_id.as_u32(),
141        phys_counter_for_node,
142        term_for_bcb: node_counters,
143        expressions,
144    })
145}
146
147fn all_coverage_in_mir_body<'a, 'tcx>(
148    body: &'a Body<'tcx>,
149) -> impl Iterator<Item = &'a CoverageKind> {
150    body.basic_blocks.iter().flat_map(|bb_data| &bb_data.statements).filter_map(|statement| {
151        match statement.kind {
152            StatementKind::Coverage(ref kind) if !is_inlined(body, statement) => Some(kind),
153            _ => None,
154        }
155    })
156}
157
158fn is_inlined(body: &Body<'_>, statement: &Statement<'_>) -> bool {
159    let scope_data = &body.source_scopes[statement.source_info.scope];
160    scope_data.inlined.is_some() || scope_data.inlined_parent_scope.is_some()
161}