Skip to content

Commit

Permalink
Avoid more invocations of hir_crate query.
Browse files Browse the repository at this point in the history
  • Loading branch information
cjgillot committed Sep 29, 2021
1 parent 1149193 commit db9fea5
Show file tree
Hide file tree
Showing 41 changed files with 123 additions and 141 deletions.
51 changes: 2 additions & 49 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::def::{CtorKind, DefKind, Res};
use crate::def_id::{DefId, CRATE_DEF_ID};
crate use crate::hir_id::{HirId, ItemLocalId};
use crate::{itemlikevisit, LangItem};
use crate::LangItem;

use rustc_ast::util::parser::ExprPrecedence;
use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
Expand All @@ -10,7 +10,6 @@ pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
pub use rustc_ast::{CaptureBy, Movability, Mutability};
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
use rustc_index::vec::IndexVec;
use rustc_macros::HashStable_Generic;
use rustc_span::source_map::Spanned;
Expand Down Expand Up @@ -672,7 +671,7 @@ pub struct Crate<'hir> {
pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
}

impl Crate<'hir> {
impl<'hir> Crate<'hir> {
pub fn module(&self) -> &'hir Mod<'hir> {
if let Some(OwnerNode::Crate(m)) = self.owners[CRATE_DEF_ID] { m } else { panic!() }
}
Expand All @@ -698,52 +697,6 @@ impl Crate<'hir> {
}
}

impl Crate<'_> {
/// Visits all items in the crate in some deterministic (but
/// unspecified) order. If you just need to process every item,
/// but don't care about nesting, this method is the best choice.
///
/// If you do care about nesting -- usually because your algorithm
/// follows lexical scoping rules -- then you want a different
/// approach. You should override `visit_nested_item` in your
/// visitor and then call `intravisit::walk_crate` instead.
pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
where
V: itemlikevisit::ItemLikeVisitor<'hir>,
{
for owner in self.owners.iter().filter_map(Option::as_ref) {
match owner {
OwnerNode::Item(item) => visitor.visit_item(item),
OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
OwnerNode::Crate(_) => {}
}
}
}

/// A parallel version of `visit_all_item_likes`.
pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
where
V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
{
par_for_each_in(&self.owners.raw, |owner| match owner {
Some(OwnerNode::Item(item)) => visitor.visit_item(item),
Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
Some(OwnerNode::Crate(_)) | None => {}
})
}

pub fn items<'hir>(&'hir self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
self.owners.iter().filter_map(|owner| match owner {
Some(OwnerNode::Item(item)) => Some(*item),
_ => None,
})
}
}

/// A block of statements `{ .. }`, which may have a label (in this case the
/// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
/// the `rules` being anything but `DefaultBlock`.
Expand Down
13 changes: 0 additions & 13 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,6 @@ pub struct NoAnn;
impl PpAnn for NoAnn {}
pub const NO_ANN: &dyn PpAnn = &NoAnn;

impl PpAnn for hir::Crate<'_> {
fn nested(&self, state: &mut State<'_>, nested: Nested) {
match nested {
Nested::Item(id) => state.print_item(self.item(id)),
Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
Nested::Body(id) => state.print_expr(&self.body(id).value),
Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
}
}
}

/// Identical to the `PpAnn` implementation for `hir::Crate`,
/// except it avoids creating a dependency on the whole crate.
impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_incremental/src/assert_dep_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub fn assert_dep_graph(tcx: TyCtxt<'_>) {
let mut visitor =
IfThisChanged { tcx, if_this_changed: vec![], then_this_would_need: vec![] };
visitor.process_attrs(hir::CRATE_HIR_ID);
tcx.hir().krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
tcx.hir().visit_all_item_likes(&mut visitor.as_deep_visitor());
(visitor.if_this_changed, visitor.then_this_would_need)
};

Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_incremental/src/persist/dirty_clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,8 @@ pub fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) {
}

tcx.dep_graph.with_ignore(|| {
let krate = tcx.hir().krate();
let mut dirty_clean_visitor = DirtyCleanVisitor { tcx, checked_attrs: Default::default() };
krate.visit_all_item_likes(&mut dirty_clean_visitor);
tcx.hir().visit_all_item_likes(&mut dirty_clean_visitor);

let mut all_attrs = FindAllAttrs { tcx, found_attrs: vec![] };
tcx.hir().walk_attributes(&mut all_attrs);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_interface/src/proc_macro_decls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rustc_span::symbol::sym;

fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option<LocalDefId> {
let mut finder = Finder { tcx, decls: None };
tcx.hir().krate().visit_all_item_likes(&mut finder);
tcx.hir().visit_all_item_likes(&mut finder);

finder.decls.map(|id| tcx.hir().local_def_id(id))
}
Expand Down
10 changes: 8 additions & 2 deletions compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,8 +584,14 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
}

fn check_crate(&mut self, cx: &LateContext<'_>, krate: &hir::Crate<'_>) {
self.check_missing_docs_attrs(cx, CRATE_DEF_ID, krate.module().inner, "the", "crate");
fn check_crate(&mut self, cx: &LateContext<'_>, _: &hir::Crate<'_>) {
self.check_missing_docs_attrs(
cx,
CRATE_DEF_ID,
cx.tcx.def_span(CRATE_DEF_ID),
"the",
"crate",
);
}

fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/foreign_modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use rustc_middle::ty::TyCtxt;

crate fn collect(tcx: TyCtxt<'_>) -> Vec<ForeignModule> {
let mut collector = Collector { modules: Vec::new() };
tcx.hir().krate().visit_all_item_likes(&mut collector);
tcx.hir().visit_all_item_likes(&mut collector);
collector.modules
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/native_libs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rustc_target::spec::abi::Abi;

crate fn collect(tcx: TyCtxt<'_>) -> Vec<NativeLib> {
let mut collector = Collector { tcx, libs: Vec::new() };
tcx.hir().krate().visit_all_item_likes(&mut collector);
tcx.hir().visit_all_item_likes(&mut collector);
collector.process_command_line();
collector.libs
}
Expand Down
7 changes: 3 additions & 4 deletions compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,16 +440,15 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
}

fn encode_info_for_items(&mut self) {
let krate = self.tcx.hir().krate();
self.encode_info_for_mod(CRATE_DEF_ID, krate.module());
self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());

// Proc-macro crates only export proc-macro items, which are looked
// up using `proc_macro_data`
if self.is_proc_macro {
return;
}

krate.visit_all_item_likes(&mut self.as_deep_visitor());
self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor());
}

fn encode_def_path_table(&mut self) {
Expand Down Expand Up @@ -1782,7 +1781,7 @@ impl EncodeContext<'a, 'tcx> {
debug!("EncodeContext::encode_impls()");
let tcx = self.tcx;
let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
tcx.hir().krate().visit_all_item_likes(&mut visitor);
tcx.hir().visit_all_item_likes(&mut visitor);

let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();

Expand Down
55 changes: 55 additions & 0 deletions compiler/rustc_middle/src/hir/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustc_ast as ast;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
Expand Down Expand Up @@ -156,6 +157,21 @@ impl<'hir> Map<'hir> {
self.tcx.hir_crate(())
}

pub fn root_module(&self) -> &'hir Mod<'hir> {
match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) {
Some(OwnerNode::Crate(item)) => item,
_ => panic!(),
}
}

crate fn items(&self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
let krate = self.krate();
krate.owners.iter().filter_map(|owner| match owner.as_ref()? {
OwnerNode::Item(item) => Some(*item),
_ => None,
})
}

pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
// Accessing the DefKey is ok, since it is part of DefPathHash.
self.tcx.untracked_resolutions.definitions.def_key(def_id)
Expand Down Expand Up @@ -531,6 +547,45 @@ impl<'hir> Map<'hir> {
}
}

/// Visits all items in the crate in some deterministic (but
/// unspecified) order. If you just need to process every item,
/// but don't care about nesting, this method is the best choice.
///
/// If you do care about nesting -- usually because your algorithm
/// follows lexical scoping rules -- then you want a different
/// approach. You should override `visit_nested_item` in your
/// visitor and then call `intravisit::walk_crate` instead.
pub fn visit_all_item_likes<V>(&self, visitor: &mut V)
where
V: itemlikevisit::ItemLikeVisitor<'hir>,
{
let krate = self.krate();
for owner in krate.owners.iter().filter_map(Option::as_ref) {
match owner {
OwnerNode::Item(item) => visitor.visit_item(item),
OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
OwnerNode::Crate(_) => {}
}
}
}

/// A parallel version of `visit_all_item_likes`.
pub fn par_visit_all_item_likes<V>(&self, visitor: &V)
where
V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
{
let krate = self.krate();
par_for_each_in(&krate.owners.raw, |owner| match owner.as_ref() {
Some(OwnerNode::Item(item)) => visitor.visit_item(item),
Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
Some(OwnerNode::Crate(_)) | None => {}
})
}

pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
where
V: ItemLikeVisitor<'hir>,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2340,7 +2340,7 @@ define_print_and_forward_display! {
fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
// Iterate all local crate items no matter where they are defined.
let hir = tcx.hir();
for item in hir.krate().items() {
for item in hir.items() {
if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
continue;
}
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_mir_transform/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,7 @@ fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> {
NestedVisitorMap::None
}
}
tcx.hir()
.krate()
.visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
tcx.hir().visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());

set
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_monomorphize/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionMode) -> Vec<MonoItem<

let mut visitor = RootCollector { tcx, mode, entry_fn, output: &mut roots };

tcx.hir().krate().visit_all_item_likes(&mut visitor);
tcx.hir().visit_all_item_likes(&mut visitor);

visitor.push_extra_entry_roots();
}
Expand Down
19 changes: 7 additions & 12 deletions compiler/rustc_passes/src/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,15 +510,14 @@ fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
// or
// 2) We are not sure to be live or not
// * Implementations of traits and trait methods
struct LifeSeeder<'k, 'tcx> {
struct LifeSeeder<'tcx> {
worklist: Vec<LocalDefId>,
krate: &'k hir::Crate<'k>,
tcx: TyCtxt<'tcx>,
// see `MarkSymbolVisitor::struct_constructors`
struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
}

impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
impl<'v, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'tcx> {
fn visit_item(&mut self, item: &hir::Item<'_>) {
let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id());
if allow_dead_code {
Expand All @@ -545,7 +544,7 @@ impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
self.worklist.push(item.def_id);
}
for impl_item_ref in items {
let impl_item = self.krate.impl_item(impl_item_ref.id);
let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
if of_trait.is_some()
|| has_allow_dead_code_or_lang_attr(self.tcx, impl_item.hir_id())
{
Expand Down Expand Up @@ -589,7 +588,6 @@ impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
fn create_and_seed_worklist<'tcx>(
tcx: TyCtxt<'tcx>,
access_levels: &privacy::AccessLevels,
krate: &hir::Crate<'_>,
) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
let worklist = access_levels
.map
Expand All @@ -604,19 +602,17 @@ fn create_and_seed_worklist<'tcx>(
.collect::<Vec<_>>();

// Seed implemented trait items
let mut life_seeder =
LifeSeeder { worklist, krate, tcx, struct_constructors: Default::default() };
krate.visit_all_item_likes(&mut life_seeder);
let mut life_seeder = LifeSeeder { worklist, tcx, struct_constructors: Default::default() };
tcx.hir().visit_all_item_likes(&mut life_seeder);

(life_seeder.worklist, life_seeder.struct_constructors)
}

fn find_live<'tcx>(
tcx: TyCtxt<'tcx>,
access_levels: &privacy::AccessLevels,
krate: &hir::Crate<'_>,
) -> FxHashSet<LocalDefId> {
let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels);
let mut symbol_visitor = MarkSymbolVisitor {
worklist,
tcx,
Expand Down Expand Up @@ -834,8 +830,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> {

pub fn check_crate(tcx: TyCtxt<'_>) {
let access_levels = &tcx.privacy_access_levels(());
let krate = tcx.hir().krate();
let live_symbols = find_live(tcx, access_levels, krate);
let live_symbols = find_live(tcx, access_levels);
let mut visitor = DeadVisitor { tcx, live_symbols };
tcx.hir().walk_toplevel_module(&mut visitor);
}
2 changes: 1 addition & 1 deletion compiler/rustc_passes/src/diagnostic_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ fn diagnostic_items<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> FxHashMap<Symbol
let mut collector = DiagnosticItemCollector::new(tcx);

// Collect diagnostic items in this crate.
tcx.hir().krate().visit_all_item_likes(&mut collector);
tcx.hir().visit_all_item_likes(&mut collector);

collector.items
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_passes/src/entry.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rustc_ast::entry::EntryPointType;
use rustc_errors::struct_span_err;
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::def_id::{DefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::{ForeignItem, HirId, ImplItem, Item, ItemKind, Node, TraitItem, CRATE_HIR_ID};
use rustc_middle::hir::map::Map;
Expand Down Expand Up @@ -68,7 +68,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
non_main_fns: Vec::new(),
};

tcx.hir().krate().visit_all_item_likes(&mut ctxt);
tcx.hir().visit_all_item_likes(&mut ctxt);

configure_main(tcx, &ctxt)
}
Expand Down Expand Up @@ -183,7 +183,7 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(De
}

fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
let sp = tcx.hir().krate().module().inner;
let sp = tcx.def_span(CRATE_DEF_ID);
if *tcx.sess.parse_sess.reached_eof.borrow() {
// There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
// the missing `fn main()` then as it might have been hidden inside an unclosed block.
Expand Down
Loading

0 comments on commit db9fea5

Please sign in to comment.