Skip to main content

rustc_mir_transform/coverage/
query.rs

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