Skip to content

Commit 8b9ef3b

Browse files
authored
Rollup merge of rust-lang#122226 - Zalathar:zcoverage-options, r=nnethercote
coverage: Remove or migrate all unstable values of `-Cinstrument-coverage` (This PR was substantially overhauled from its original version, which migrated all of the existing unstable values intact.) This PR takes the three nightly-only values that are currently accepted by `-Cinstrument-coverage`, completely removes two of them (`except-unused-functions` and `except-unused-generics`), and migrates the third (`branch`) over to a newly-introduced unstable flag `-Zcoverage-options`. I have a few motivations for wanting to do this: - It's unclear whether anyone actually uses the `except-unused-*` values, so this serves as an opportunity to either remove them, or prompt existing users to object to their removal. - After rust-lang#117199, the stable values of `-Cinstrument-coverage` treat it as a boolean-valued flag, so having nightly-only extra values feels out-of-place. - Nightly-only values also require extra ad-hoc code to make sure they aren't accidentally exposed to stable users. - The new system allows multiple different settings to be toggled independently, which isn't possible in the current single-value system. - The new system makes it easier to introduce new behaviour behind an unstable toggle, and then gather nightly-user feedback before possibly making it the default behaviour for all users. - The new system also gives us a convenient place to put relatively-narrow options that won't ever be the default, but that nightly users might still want access to. - It's likely that we will eventually want to give stable users more fine-grained control over coverage instrumentation. The new flag serves as a prototype of what that stable UI might eventually look like. The `branch` option is a placeholder that currently does nothing. It will be used by rust-lang#122322 to opt into branch coverage instrumentation. --- I see `-Zcoverage-options` as something that will exist more-or-less indefinitely, though individual sub-options might come and go as appropriate. I think there will always be some demand for nightly-only toggles, so I don't see `-Zcoverage-options` itself ever being stable, though we might eventually stabilize something similar to it.
2 parents 8d78f8e + 3407fcc commit 8b9ef3b

File tree

18 files changed

+106
-125
lines changed

18 files changed

+106
-125
lines changed

compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -355,21 +355,20 @@ fn add_unused_functions(cx: &CodegenCx<'_, '_>) {
355355

356356
let tcx = cx.tcx;
357357

358-
let ignore_unused_generics = tcx.sess.instrument_coverage_except_unused_generics();
359-
360358
let eligible_def_ids = tcx.mir_keys(()).iter().filter_map(|local_def_id| {
361359
let def_id = local_def_id.to_def_id();
362360
let kind = tcx.def_kind(def_id);
363361
// `mir_keys` will give us `DefId`s for all kinds of things, not
364362
// just "functions", like consts, statics, etc. Filter those out.
365-
// If `ignore_unused_generics` was specified, filter out any
366-
// generic functions from consideration as well.
367363
if !matches!(kind, DefKind::Fn | DefKind::AssocFn | DefKind::Closure) {
368364
return None;
369365
}
370-
if ignore_unused_generics && tcx.generics_of(def_id).requires_monomorphization(tcx) {
371-
return None;
372-
}
366+
367+
// FIXME(79651): Consider trying to filter out dummy instantiations of
368+
// unused generic functions from library crates, because they can produce
369+
// "unused instantiation" in coverage reports even when they are actually
370+
// used by some downstream crate in the same binary.
371+
373372
Some(local_def_id.to_def_id())
374373
});
375374

compiler/rustc_interface/src/tests.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ use rustc_data_structures::profiling::TimePassesFormat;
44
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
55
use rustc_session::config::{
66
build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg,
7-
CollapseMacroDebuginfo, DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry,
8-
ExternLocation, Externs, FunctionReturn, InliningThreshold, Input, InstrumentCoverage,
9-
InstrumentXRay, LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig,
10-
OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
11-
ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
7+
CollapseMacroDebuginfo, CoverageOptions, DebugInfo, DumpMonoStatsFormat, ErrorOutputType,
8+
ExternEntry, ExternLocation, Externs, FunctionReturn, InliningThreshold, Input,
9+
InstrumentCoverage, InstrumentXRay, LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli,
10+
NextSolverConfig, OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet,
11+
Passes, Polonius, ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion,
12+
WasiExecModel,
1213
};
1314
use rustc_session::lint::Level;
1415
use rustc_session::search_paths::SearchPath;
@@ -750,6 +751,7 @@ fn test_unstable_options_tracking_hash() {
750751
);
751752
tracked!(codegen_backend, Some("abc".to_string()));
752753
tracked!(collapse_macro_debuginfo, CollapseMacroDebuginfo::Yes);
754+
tracked!(coverage_options, CoverageOptions { branch: true });
753755
tracked!(crate_attr, vec!["abc".to_string()]);
754756
tracked!(cross_crate_inline_threshold, InliningThreshold::Always);
755757
tracked!(debug_info_for_profiling, true);

compiler/rustc_monomorphize/src/partitioning.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,7 @@ where
175175
}
176176

177177
// Mark one CGU for dead code, if necessary.
178-
let instrument_dead_code =
179-
tcx.sess.instrument_coverage() && !tcx.sess.instrument_coverage_except_unused_functions();
180-
if instrument_dead_code {
178+
if tcx.sess.instrument_coverage() {
181179
mark_code_coverage_dead_code_cgu(&mut codegen_units);
182180
}
183181

compiler/rustc_session/src/config.rs

+21-43
Original file line numberDiff line numberDiff line change
@@ -134,31 +134,26 @@ pub enum LtoCli {
134134
/// and higher). Nevertheless, there are many variables, depending on options
135135
/// selected, code structure, and enabled attributes. If errors are encountered,
136136
/// either while compiling or when generating `llvm-cov show` reports, consider
137-
/// lowering the optimization level, including or excluding `-C link-dead-code`,
138-
/// or using `-Zunstable-options -C instrument-coverage=except-unused-functions`
139-
/// or `-Zunstable-options -C instrument-coverage=except-unused-generics`.
140-
///
141-
/// Note that `ExceptUnusedFunctions` means: When `mapgen.rs` generates the
142-
/// coverage map, it will not attempt to generate synthetic functions for unused
143-
/// (and not code-generated) functions (whether they are generic or not). As a
144-
/// result, non-codegenned functions will not be included in the coverage map,
145-
/// and will not appear, as covered or uncovered, in coverage reports.
146-
///
147-
/// `ExceptUnusedGenerics` will add synthetic functions to the coverage map,
148-
/// unless the function has type parameters.
137+
/// lowering the optimization level, or including/excluding `-C link-dead-code`.
149138
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
150139
pub enum InstrumentCoverage {
151140
/// `-C instrument-coverage=no` (or `off`, `false` etc.)
152141
No,
153142
/// `-C instrument-coverage` or `-C instrument-coverage=yes`
154143
Yes,
155-
/// Additionally, instrument branches and output branch coverage.
156-
/// `-Zunstable-options -C instrument-coverage=branch`
157-
Branch,
158-
/// `-Zunstable-options -C instrument-coverage=except-unused-generics`
159-
ExceptUnusedGenerics,
160-
/// `-Zunstable-options -C instrument-coverage=except-unused-functions`
161-
ExceptUnusedFunctions,
144+
}
145+
146+
/// Individual flag values controlled by `-Z coverage-options`.
147+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
148+
pub struct CoverageOptions {
149+
/// Add branch coverage instrumentation (placeholder flag; not yet implemented).
150+
pub branch: bool,
151+
}
152+
153+
impl Default for CoverageOptions {
154+
fn default() -> Self {
155+
Self { branch: false }
156+
}
162157
}
163158

164159
/// Settings for `-Z instrument-xray` flag.
@@ -2718,24 +2713,6 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
27182713
}
27192714
}
27202715

2721-
// Check for unstable values of `-C instrument-coverage`.
2722-
// This is what prevents them from being used on stable compilers.
2723-
match cg.instrument_coverage {
2724-
// Stable values:
2725-
InstrumentCoverage::Yes | InstrumentCoverage::No => {}
2726-
// Unstable values:
2727-
InstrumentCoverage::Branch
2728-
| InstrumentCoverage::ExceptUnusedFunctions
2729-
| InstrumentCoverage::ExceptUnusedGenerics => {
2730-
if !unstable_opts.unstable_options {
2731-
early_dcx.early_fatal(
2732-
"`-C instrument-coverage=branch` and `-C instrument-coverage=except-*` \
2733-
require `-Z unstable-options`",
2734-
);
2735-
}
2736-
}
2737-
}
2738-
27392716
if cg.instrument_coverage != InstrumentCoverage::No {
27402717
if cg.profile_generate.enabled() || cg.profile_use.is_some() {
27412718
early_dcx.early_fatal(
@@ -3204,12 +3181,12 @@ pub enum WasiExecModel {
32043181
/// how the hash should be calculated when adding a new command-line argument.
32053182
pub(crate) mod dep_tracking {
32063183
use super::{
3207-
BranchProtection, CFGuard, CFProtection, CollapseMacroDebuginfo, CrateType, DebugInfo,
3208-
DebugInfoCompression, ErrorOutputType, FunctionReturn, InliningThreshold,
3209-
InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail, LtoCli,
3210-
NextSolverConfig, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes, Polonius,
3211-
RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm, SplitDwarfKind,
3212-
SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
3184+
BranchProtection, CFGuard, CFProtection, CollapseMacroDebuginfo, CoverageOptions,
3185+
CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FunctionReturn,
3186+
InliningThreshold, InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail,
3187+
LtoCli, NextSolverConfig, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes,
3188+
Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
3189+
SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
32133190
};
32143191
use crate::lint;
32153192
use crate::utils::NativeLib;
@@ -3279,6 +3256,7 @@ pub(crate) mod dep_tracking {
32793256
CodeModel,
32803257
TlsModel,
32813258
InstrumentCoverage,
3259+
CoverageOptions,
32823260
InstrumentXRay,
32833261
CrateType,
32843262
MergeFunctions,

compiler/rustc_session/src/options.rs

+27-16
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,8 @@ mod desc {
395395
pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of();
396396
pub const parse_optimization_fuel: &str = "crate=integer";
397397
pub const parse_dump_mono_stats: &str = "`markdown` (default) or `json`";
398-
pub const parse_instrument_coverage: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc) or (unstable) one of `branch`, `except-unused-generics`, `except-unused-functions`";
398+
pub const parse_instrument_coverage: &str = parse_bool;
399+
pub const parse_coverage_options: &str = "`branch` or `no-branch`";
399400
pub const parse_instrument_xray: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or a comma separated list of settings: `always` or `never` (mutually exclusive), `ignore-loops`, `instruction-threshold=N`, `skip-entry`, `skip-exit`";
400401
pub const parse_unpretty: &str = "`string` or `string=string`";
401402
pub const parse_treat_err_as_bug: &str = "either no value or a non-negative number";
@@ -928,21 +929,34 @@ mod parse {
928929
return true;
929930
};
930931

932+
// Parse values that have historically been accepted by stable compilers,
933+
// even though they're currently just aliases for boolean values.
931934
*slot = match v {
932935
"all" => InstrumentCoverage::Yes,
933-
"branch" => InstrumentCoverage::Branch,
934-
"except-unused-generics" | "except_unused_generics" => {
935-
InstrumentCoverage::ExceptUnusedGenerics
936-
}
937-
"except-unused-functions" | "except_unused_functions" => {
938-
InstrumentCoverage::ExceptUnusedFunctions
939-
}
940936
"0" => InstrumentCoverage::No,
941937
_ => return false,
942938
};
943939
true
944940
}
945941

942+
pub(crate) fn parse_coverage_options(slot: &mut CoverageOptions, v: Option<&str>) -> bool {
943+
let Some(v) = v else { return true };
944+
945+
for option in v.split(',') {
946+
let (option, enabled) = match option.strip_prefix("no-") {
947+
Some(without_no) => (without_no, false),
948+
None => (option, true),
949+
};
950+
let slot = match option {
951+
"branch" => &mut slot.branch,
952+
_ => return false,
953+
};
954+
*slot = enabled;
955+
}
956+
957+
true
958+
}
959+
946960
pub(crate) fn parse_instrument_xray(
947961
slot: &mut Option<InstrumentXRay>,
948962
v: Option<&str>,
@@ -1445,14 +1459,9 @@ options! {
14451459
"set the threshold for inlining a function"),
14461460
#[rustc_lint_opt_deny_field_access("use `Session::instrument_coverage` instead of this field")]
14471461
instrument_coverage: InstrumentCoverage = (InstrumentCoverage::No, parse_instrument_coverage, [TRACKED],
1448-
"instrument the generated code to support LLVM source-based code coverage \
1449-
reports (note, the compiler build config must include `profiler = true`); \
1450-
implies `-C symbol-mangling-version=v0`. Optional values are:
1451-
`=no` `=n` `=off` `=false` (default)
1452-
`=yes` `=y` `=on` `=true` (implicit value)
1453-
`=branch` (unstable)
1454-
`=except-unused-generics` (unstable)
1455-
`=except-unused-functions` (unstable)"),
1462+
"instrument the generated code to support LLVM source-based code coverage reports \
1463+
(note, the compiler build config must include `profiler = true`); \
1464+
implies `-C symbol-mangling-version=v0`"),
14561465
link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
14571466
"a single extra argument to append to the linker invocation (can be used several times)"),
14581467
link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
@@ -1574,6 +1583,8 @@ options! {
15741583
"set option to collapse debuginfo for macros"),
15751584
combine_cgu: bool = (false, parse_bool, [TRACKED],
15761585
"combine CGUs into a single one"),
1586+
coverage_options: CoverageOptions = (CoverageOptions::default(), parse_coverage_options, [TRACKED],
1587+
"control details of coverage instrumentation"),
15771588
crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
15781589
"inject the given attribute in the crate"),
15791590
cross_crate_inline_threshold: InliningThreshold = (InliningThreshold::Sometimes(100), parse_inlining_threshold, [TRACKED],

compiler/rustc_session/src/session.rs

+1-9
Original file line numberDiff line numberDiff line change
@@ -353,15 +353,7 @@ impl Session {
353353
}
354354

355355
pub fn instrument_coverage_branch(&self) -> bool {
356-
self.opts.cg.instrument_coverage() == InstrumentCoverage::Branch
357-
}
358-
359-
pub fn instrument_coverage_except_unused_generics(&self) -> bool {
360-
self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedGenerics
361-
}
362-
363-
pub fn instrument_coverage_except_unused_functions(&self) -> bool {
364-
self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedFunctions
356+
self.instrument_coverage() && self.opts.unstable_opts.coverage_options.branch
365357
}
366358

367359
pub fn is_sanitizer_cfi_enabled(&self) -> bool {

src/doc/rustc/src/instrument-coverage.md

+7-8
Original file line numberDiff line numberDiff line change
@@ -346,14 +346,13 @@ $ llvm-cov report \
346346
more fine-grained coverage options are added.
347347
Using this value is currently not recommended.
348348

349-
### Unstable values
350-
351-
- `-Z unstable-options -C instrument-coverage=branch`:
352-
Placeholder for potential branch coverage support in the future.
353-
- `-Z unstable-options -C instrument-coverage=except-unused-generics`:
354-
Instrument all functions except unused generics.
355-
- `-Z unstable-options -C instrument-coverage=except-unused-functions`:
356-
Instrument only used (called) functions and instantiated generic functions.
349+
## `-Z coverage-options=<options>`
350+
351+
This unstable option provides finer control over some aspects of coverage
352+
instrumentation. Pass one or more of the following values, separated by commas.
353+
354+
- `branch` or `no-branch`
355+
- Placeholder for potential branch coverage support in the future.
357356

358357
## Other references
359358

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# `coverage-options`
2+
3+
This option controls details of the coverage instrumentation performed by
4+
`-C instrument-coverage`.
5+
6+
Multiple options can be passed, separated by commas. Valid options are:
7+
8+
- `branch` or `no-branch`: Placeholder for future branch coverage support.

tests/coverage/auxiliary/used_crate.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,8 @@ fn use_this_lib_crate() {
7676
// ```
7777
//
7878
// The notice is triggered because the function is unused by the library itself,
79-
// and when the library is compiled, a synthetic function is generated, so
80-
// unused function coverage can be reported. Coverage can be skipped for unused
81-
// generic functions with:
82-
//
83-
// ```shell
84-
// $ `rustc -Zunstable-options -C instrument-coverage=except-unused-generics ...`
85-
// ```
79+
// so when the library is compiled, an "unused" set of mappings for that function
80+
// is included in the library's coverage metadata.
8681
//
8782
// Even though this function is used by `uses_crate.rs` (and
8883
// counted), with substitutions for `T`, those instantiations are only generated
@@ -98,6 +93,6 @@ fn use_this_lib_crate() {
9893
// another binary that never used this generic function, then it would be valid
9994
// to show the unused generic, with unknown substitution (`_`).
10095
//
101-
// The alternative is to exclude all generics from being included in the "unused
102-
// functions" list, which would then omit coverage results for
103-
// `unused_generic_function<T>()`, below.
96+
// The alternative would be to exclude all generics from being included in the
97+
// "unused functions" list, which would then omit coverage results for
98+
// `unused_generic_function<T>()`.

tests/coverage/uses_crate.coverage

+5-10
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,8 @@ $DIR/auxiliary/used_crate.rs:
124124
LL| |// ```
125125
LL| |//
126126
LL| |// The notice is triggered because the function is unused by the library itself,
127-
LL| |// and when the library is compiled, a synthetic function is generated, so
128-
LL| |// unused function coverage can be reported. Coverage can be skipped for unused
129-
LL| |// generic functions with:
130-
LL| |//
131-
LL| |// ```shell
132-
LL| |// $ `rustc -Zunstable-options -C instrument-coverage=except-unused-generics ...`
133-
LL| |// ```
127+
LL| |// so when the library is compiled, an "unused" set of mappings for that function
128+
LL| |// is included in the library's coverage metadata.
134129
LL| |//
135130
LL| |// Even though this function is used by `uses_crate.rs` (and
136131
LL| |// counted), with substitutions for `T`, those instantiations are only generated
@@ -146,9 +141,9 @@ $DIR/auxiliary/used_crate.rs:
146141
LL| |// another binary that never used this generic function, then it would be valid
147142
LL| |// to show the unused generic, with unknown substitution (`_`).
148143
LL| |//
149-
LL| |// The alternative is to exclude all generics from being included in the "unused
150-
LL| |// functions" list, which would then omit coverage results for
151-
LL| |// `unused_generic_function<T>()`, below.
144+
LL| |// The alternative would be to exclude all generics from being included in the
145+
LL| |// "unused functions" list, which would then omit coverage results for
146+
LL| |// `unused_generic_function<T>()`.
152147

153148
$DIR/uses_crate.rs:
154149
LL| |// This test was failing on Linux for a while due to #110393 somehow making
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
error: incorrect value `bad-value` for codegen option `instrument-coverage` - either a boolean (`yes`, `no`, `on`, `off`, etc) or (unstable) one of `branch`, `except-unused-generics`, `except-unused-functions` was expected
1+
error: incorrect value `bad-value` for codegen option `instrument-coverage` - one of: `y`, `yes`, `on`, `true`, `n`, `no`, `off` or `false` was expected
22

Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
error: incorrect value `` for codegen option `instrument-coverage` - either a boolean (`yes`, `no`, `on`, `off`, etc) or (unstable) one of `branch`, `except-unused-generics`, `except-unused-functions` was expected
1+
error: incorrect value `` for codegen option `instrument-coverage` - one of: `y`, `yes`, `on`, `true`, `n`, `no`, `off` or `false` was expected
22

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
error: incorrect value `bad` for unstable option `coverage-options` - `branch` or `no-branch` was expected
2+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
//@ needs-profiler-support
2+
//@ revisions: branch no-branch bad
3+
//@ compile-flags -Cinstrument-coverage
4+
5+
//@ [branch] check-pass
6+
//@ [branch] compile-flags: -Zcoverage-options=branch
7+
8+
//@ [no-branch] check-pass
9+
//@ [no-branch] compile-flags: -Zcoverage-options=no-branch
10+
11+
//@ [bad] check-fail
12+
//@ [bad] compile-flags: -Zcoverage-options=bad
13+
14+
fn main() {}

tests/ui/instrument-coverage/unstable.branch.stderr

-2
This file was deleted.

tests/ui/instrument-coverage/unstable.except-unused-functions.stderr

-2
This file was deleted.

tests/ui/instrument-coverage/unstable.except-unused-generics.stderr

-2
This file was deleted.

tests/ui/instrument-coverage/unstable.rs

-6
This file was deleted.

0 commit comments

Comments
 (0)