1 // Finds items that are externally reachable, to determine which items
2 // need to have their metadata (and possibly their AST) serialized.
3 // All items that can be referred to through an exported name are
4 // reachable, and when a reachable thing is inline or generic, it
5 // makes all other generics or inline functions that it references
8 use rustc_data_structures::fx::FxHashSet;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::LOCAL_CRATE;
12 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::{HirIdSet, Node};
16 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
17 use rustc_middle::middle::privacy;
18 use rustc_middle::ty::query::Providers;
19 use rustc_middle::ty::{self, TyCtxt};
20 use rustc_session::config;
21 use rustc_target::spec::abi::Abi;
23 // Returns true if the given item must be inlined because it may be
24 // monomorphized or it was marked with `#[inline]`. This will only return
25 // true for functions.
26 fn item_might_be_inlined(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>, attrs: &CodegenFnAttrs) -> bool {
27 if attrs.requests_inline() {
32 hir::ItemKind::Fn(ref sig, ..) if sig.header.is_const() => true,
33 hir::ItemKind::Impl { .. } | hir::ItemKind::Fn(..) => {
34 let generics = tcx.generics_of(tcx.hir().local_def_id(item.hir_id));
35 generics.requires_monomorphization(tcx)
41 fn method_might_be_inlined(
43 impl_item: &hir::ImplItem<'_>,
46 let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner.to_def_id());
47 let generics = tcx.generics_of(tcx.hir().local_def_id(impl_item.hir_id));
48 if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) {
51 if let hir::ImplItemKind::Fn(method_sig, _) = &impl_item.kind {
52 if method_sig.header.is_const() {
56 match tcx.hir().find(tcx.hir().as_local_hir_id(impl_src)) {
57 Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs),
58 Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"),
62 // Information needed while computing reachability.
63 struct ReachableContext<'a, 'tcx> {
66 tables: &'a ty::TypeckTables<'tcx>,
67 // The set of items which must be exported in the linkage sense.
68 reachable_symbols: HirIdSet,
69 // A worklist of item IDs. Each item ID in this worklist will be inlined
70 // and will be scanned for further references.
71 worklist: Vec<hir::HirId>,
72 // Whether any output of this compilation is a library
76 impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
77 type Map = intravisit::ErasedMap<'tcx>;
79 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
80 NestedVisitorMap::None
83 fn visit_nested_body(&mut self, body: hir::BodyId) {
84 let old_tables = self.tables;
85 self.tables = self.tcx.body_tables(body);
86 let body = self.tcx.hir().body(body);
87 self.visit_body(body);
88 self.tables = old_tables;
91 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
92 let res = match expr.kind {
93 hir::ExprKind::Path(ref qpath) => Some(self.tables.qpath_res(qpath, expr.hir_id)),
94 hir::ExprKind::MethodCall(..) => self
96 .type_dependent_def(expr.hir_id)
97 .map(|(kind, def_id)| Res::Def(kind, def_id)),
102 Some(Res::Local(hir_id)) => {
103 self.reachable_symbols.insert(hir_id);
106 if let Some((hir_id, def_id)) = res.opt_def_id().and_then(|def_id| {
107 def_id.as_local().map(|def_id| (self.tcx.hir().as_local_hir_id(def_id), def_id))
109 if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
110 self.worklist.push(hir_id);
113 // If this path leads to a constant, then we need to
114 // recurse into the constant to continue finding
115 // items that are reachable.
116 Res::Def(DefKind::Const | DefKind::AssocConst, _) => {
117 self.worklist.push(hir_id);
120 // If this wasn't a static, then the destination is
123 self.reachable_symbols.insert(hir_id);
132 intravisit::walk_expr(self, expr)
136 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
137 // Returns true if the given def ID represents a local item that is
138 // eligible for inlining and false otherwise.
139 fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
140 let hir_id = match def_id.as_local() {
141 Some(def_id) => self.tcx.hir().as_local_hir_id(def_id),
147 match self.tcx.hir().find(hir_id) {
148 Some(Node::Item(item)) => match item.kind {
149 hir::ItemKind::Fn(..) => {
150 item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
154 Some(Node::TraitItem(trait_method)) => match trait_method.kind {
155 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
156 hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true,
157 hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
158 | hir::TraitItemKind::Type(..) => false,
160 Some(Node::ImplItem(impl_item)) => {
161 match impl_item.kind {
162 hir::ImplItemKind::Const(..) => true,
163 hir::ImplItemKind::Fn(..) => {
164 let attrs = self.tcx.codegen_fn_attrs(def_id);
165 let generics = self.tcx.generics_of(def_id);
166 if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
169 let impl_did = self.tcx.hir().get_parent_did(hir_id);
170 // Check the impl. If the generics on the self
171 // type of the impl require inlining, this method
173 let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did);
174 match self.tcx.hir().expect_item(impl_hir_id).kind {
175 hir::ItemKind::Impl { .. } => {
176 let generics = self.tcx.generics_of(impl_did);
177 generics.requires_monomorphization(self.tcx)
183 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => false,
187 None => false, // This will happen for default methods.
191 // Step 2: Mark all symbols that the symbols on the worklist touch.
192 fn propagate(&mut self) {
193 let mut scanned = FxHashSet::default();
194 while let Some(search_item) = self.worklist.pop() {
195 if !scanned.insert(search_item) {
199 if let Some(ref item) = self.tcx.hir().find(search_item) {
200 self.propagate_node(item, search_item);
205 fn propagate_node(&mut self, node: &Node<'tcx>, search_item: hir::HirId) {
206 if !self.any_library {
207 // If we are building an executable, only explicitly extern
208 // types need to be exported.
209 if let Node::Item(item) = *node {
210 let reachable = if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
211 sig.header.abi != Abi::Rust
215 let def_id = self.tcx.hir().local_def_id(item.hir_id);
216 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
217 let is_extern = codegen_attrs.contains_extern_indicator();
219 codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
220 if reachable || is_extern || std_internal {
221 self.reachable_symbols.insert(search_item);
225 // If we are building a library, then reachable symbols will
226 // continue to participate in linkage after this product is
227 // produced. In this case, we traverse the ast node, recursing on
228 // all reachable nodes from this one.
229 self.reachable_symbols.insert(search_item);
233 Node::Item(item) => {
235 hir::ItemKind::Fn(.., body) => {
236 let def_id = self.tcx.hir().local_def_id(item.hir_id);
237 if item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
239 self.visit_nested_body(body);
243 // Reachable constants will be inlined into other crates
244 // unconditionally, so we need to make sure that their
245 // contents are also reachable.
246 hir::ItemKind::Const(_, init) => {
247 self.visit_nested_body(init);
250 // These are normal, nothing reachable about these
251 // inherently and their children are already in the
252 // worklist, as determined by the privacy pass
253 hir::ItemKind::ExternCrate(_)
254 | hir::ItemKind::Use(..)
255 | hir::ItemKind::OpaqueTy(..)
256 | hir::ItemKind::TyAlias(..)
257 | hir::ItemKind::Static(..)
258 | hir::ItemKind::Mod(..)
259 | hir::ItemKind::ForeignMod(..)
260 | hir::ItemKind::Impl { .. }
261 | hir::ItemKind::Trait(..)
262 | hir::ItemKind::TraitAlias(..)
263 | hir::ItemKind::Struct(..)
264 | hir::ItemKind::Enum(..)
265 | hir::ItemKind::Union(..)
266 | hir::ItemKind::GlobalAsm(..) => {}
269 Node::TraitItem(trait_method) => {
270 match trait_method.kind {
271 hir::TraitItemKind::Const(_, None)
272 | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => {
273 // Keep going, nothing to get exported
275 hir::TraitItemKind::Const(_, Some(body_id))
276 | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
277 self.visit_nested_body(body_id);
279 hir::TraitItemKind::Type(..) => {}
282 Node::ImplItem(impl_item) => match impl_item.kind {
283 hir::ImplItemKind::Const(_, body) => {
284 self.visit_nested_body(body);
286 hir::ImplItemKind::Fn(_, body) => {
287 let did = self.tcx.hir().get_parent_did(search_item);
288 if method_might_be_inlined(self.tcx, impl_item, did) {
289 self.visit_nested_body(body)
292 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => {}
294 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
295 self.visit_nested_body(body);
297 // Nothing to recurse on for these
303 | Node::MacroDef(_) => {}
306 "found unexpected node kind in worklist: {} ({:?})",
307 self.tcx.hir().node_to_string(search_item),
315 // Some methods from non-exported (completely private) trait impls still have to be
316 // reachable if they are called from inlinable code. Generally, it's not known until
317 // monomorphization if a specific trait impl item can be reachable or not. So, we
318 // conservatively mark all of them as reachable.
319 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
320 // items of non-exported traits (or maybe all local traits?) unless their respective
321 // trait items are used from inlinable code through method call syntax or UFCS, or their
322 // trait is a lang item.
323 struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
325 access_levels: &'a privacy::AccessLevels,
326 worklist: &'a mut Vec<hir::HirId>,
329 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
330 fn visit_item(&mut self, item: &hir::Item<'_>) {
331 // Anything which has custom linkage gets thrown on the worklist no
332 // matter where it is in the crate, along with "special std symbols"
333 // which are currently akin to allocator symbols.
334 let def_id = self.tcx.hir().local_def_id(item.hir_id);
335 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
336 if codegen_attrs.contains_extern_indicator()
337 || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
339 self.worklist.push(item.hir_id);
342 // We need only trait impls here, not inherent impls, and only non-exported ones
343 if let hir::ItemKind::Impl { of_trait: Some(ref trait_ref), ref items, .. } = item.kind {
344 if !self.access_levels.is_reachable(item.hir_id) {
345 self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.hir_id));
347 let trait_def_id = match trait_ref.path.res {
348 Res::Def(DefKind::Trait, def_id) => def_id,
352 if !trait_def_id.is_local() {
356 // FIXME(#53488) remove `let`
358 self.worklist.extend(
359 tcx.provided_trait_methods(trait_def_id)
360 .map(|assoc| tcx.hir().as_local_hir_id(assoc.def_id.expect_local())),
366 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
368 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {
369 // processed in visit_item above
373 fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, crate_num: CrateNum) -> &'tcx HirIdSet {
374 debug_assert!(crate_num == LOCAL_CRATE);
376 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
378 let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
379 *ty == config::CrateType::Rlib
380 || *ty == config::CrateType::Dylib
381 || *ty == config::CrateType::ProcMacro
383 let mut reachable_context = ReachableContext {
385 tables: &ty::TypeckTables::empty(None),
386 reachable_symbols: Default::default(),
387 worklist: Vec::new(),
391 // Step 1: Seed the worklist with all nodes which were found to be public as
392 // a result of the privacy pass along with all local lang items and impl items.
393 // If other crates link to us, they're going to expect to be able to
394 // use the lang items, so we need to be sure to mark them as
396 reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
397 for item in tcx.lang_items().items().iter() {
398 if let Some(did) = *item {
399 if let Some(hir_id) = did.as_local().map(|did| tcx.hir().as_local_hir_id(did)) {
400 reachable_context.worklist.push(hir_id);
405 let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
408 worklist: &mut reachable_context.worklist,
410 tcx.hir().krate().visit_all_item_likes(&mut collect_private_impl_items);
413 // Step 2: Mark all symbols that the symbols on the worklist touch.
414 reachable_context.propagate();
416 debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
418 // Return the set of reachable symbols.
419 tcx.arena.alloc(reachable_context.reachable_symbols)
422 pub fn provide(providers: &mut Providers<'_>) {
423 *providers = Providers { reachable_set, ..*providers };