Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cache-based fast path for cfgs and check-cfgs #122207

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 33 additions & 31 deletions compiler/rustc_attr/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,38 +526,40 @@ pub fn cfg_matches(
) -> bool {
eval_condition(cfg, sess, features, &mut |cfg| {
try_gate_cfg(cfg.name, cfg.span, sess, features);
match sess.psess.check_config.expecteds.get(&cfg.name) {
Some(ExpectedValues::Some(values)) if !values.contains(&cfg.value) => {
sess.psess.buffer_lint_with_diagnostic(
UNEXPECTED_CFGS,
cfg.span,
lint_node_id,
if let Some(value) = cfg.value {
format!("unexpected `cfg` condition value: `{value}`")
} else {
format!("unexpected `cfg` condition value: (none)")
},
BuiltinLintDiag::UnexpectedCfgValue(
(cfg.name, cfg.name_span),
cfg.value.map(|v| (v, cfg.value_span.unwrap())),
),
);
}
None if sess.psess.check_config.exhaustive_names => {
sess.psess.buffer_lint_with_diagnostic(
UNEXPECTED_CFGS,
cfg.span,
lint_node_id,
format!("unexpected `cfg` condition name: `{}`", cfg.name),
BuiltinLintDiag::UnexpectedCfgName(
(cfg.name, cfg.name_span),
cfg.value.map(|v| (v, cfg.value_span.unwrap())),
),
);
sess.psess.config_cache.get(&(cfg.name, cfg.value)).copied().unwrap_or_else(|| {
match sess.psess.check_config.expecteds.get(&cfg.name) {
Some(ExpectedValues::Some(values)) if !values.contains(&cfg.value) => {
sess.psess.buffer_lint_with_diagnostic(
UNEXPECTED_CFGS,
cfg.span,
lint_node_id,
if let Some(value) = cfg.value {
format!("unexpected `cfg` condition value: `{value}`")
} else {
format!("unexpected `cfg` condition value: (none)")
},
BuiltinLintDiag::UnexpectedCfgValue(
(cfg.name, cfg.name_span),
cfg.value.map(|v| (v, cfg.value_span.unwrap())),
),
);
}
None if sess.psess.check_config.exhaustive_names => {
sess.psess.buffer_lint_with_diagnostic(
UNEXPECTED_CFGS,
cfg.span,
lint_node_id,
format!("unexpected `cfg` condition name: `{}`", cfg.name),
BuiltinLintDiag::UnexpectedCfgName(
(cfg.name, cfg.name_span),
cfg.value.map(|v| (v, cfg.value_span.unwrap())),
),
);
}
_ => { /* not unexpected */ }
}
_ => { /* not unexpected */ }
}
sess.psess.config.contains(&(cfg.name, cfg.value))
sess.psess.config.contains(&(cfg.name, cfg.value))
})
})
}

Expand Down
33 changes: 32 additions & 1 deletion compiler/rustc_interface/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use rustc_query_impl::QueryCtxt;
use rustc_query_system::query::print_query_stack;
use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName};
use rustc_session::filesearch::{self, sysroot_candidates};
use rustc_session::parse::ParseSess;
use rustc_session::parse::{CfgCache, ParseSess};
use rustc_session::{lint, CompilerIO, EarlyDiagCtxt, Session};
use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
use rustc_span::symbol::sym;
Expand Down Expand Up @@ -297,6 +297,35 @@ pub(crate) fn parse_check_cfg(dcx: &DiagCtxt, specs: Vec<String>) -> CheckCfg {
check_cfg
}

/// Create the config cache of `--cfg` and `--check-cfg` for internal use.
///
/// The cache is used to reduce the number of hashmap lookups by
/// pre-computing the maximum possible configs[^1] from `--check-cfg` and `--cfg`.
///
/// It heavily favours expected cfgs (if any are provided), since if the
/// user provides a list of expected cfgs, they are likely to care more
/// about expected cfgs than unexpected cfgs.
///
/// [^1]: See [`CfgCache`] for an explanation of "maximum possible".
fn config_cache(config: &Cfg, check_cfg: &CheckCfg) -> CfgCache {
let mut config_cache = CfgCache::default();

if check_cfg.expecteds.is_empty() {
config_cache.extend(config.iter().map(|cfg| (*cfg, true)));
} else {
#[allow(rustc::potential_query_instability)]
for (name, expected) in &check_cfg.expecteds {
if let ExpectedValues::Some(values) = expected {
config_cache.extend(
values.iter().map(|value| ((*name, *value), config.contains(&(*name, *value)))),
);
}
}
}

config_cache
}

/// The compiler configuration
pub struct Config {
/// Command line options
Expand Down Expand Up @@ -459,6 +488,8 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
check_cfg.fill_well_known(&sess.target);
sess.psess.check_config = check_cfg;

sess.psess.config_cache = config_cache(&sess.psess.config, &sess.psess.check_config);

if let Some(psess_created) = config.psess_created {
psess_created(&mut sess.psess);
}
Expand Down
13 changes: 13 additions & 0 deletions compiler/rustc_session/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,24 @@ pub fn add_feature_diagnostics_for_issue<G: EmissionGuarantee>(
}
}

/// Config cache that tries to combine expected cfgs and enabled cfgs.
///
/// If a config is found, this means it is definitely an expected config
/// and the value represents whenever that config is enabled.
///
/// If a config is not found, it doesn't imply anything! The config still may
/// be enabled and it may also be expected. You should only rely on the
/// cache having a config and not "NOT having it". You should always fallback
/// to a manual lookup in `ParseSess::config` and `ParseSess::check_cfg`.
pub type CfgCache = FxHashMap<(Symbol, Option<Symbol>), bool>;

/// Info about a parsing session.
pub struct ParseSess {
pub dcx: DiagCtxt,
pub unstable_features: UnstableFeatures,
pub config: Cfg,
pub check_config: CheckCfg,
pub config_cache: CfgCache,
pub edition: Edition,
/// Places where raw identifiers were used. This is used to avoid complaining about idents
/// clashing with keywords in new editions.
Expand Down Expand Up @@ -253,6 +265,7 @@ impl ParseSess {
unstable_features: UnstableFeatures::from_environment(None),
config: Cfg::default(),
check_config: CheckCfg::default(),
config_cache: CfgCache::default(),
edition: ExpnId::root().expn_data().edition,
raw_identifier_spans: Default::default(),
bad_unicode_identifiers: Lock::new(Default::default()),
Expand Down
Loading