]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/reachable.rs
review
[rust.git] / compiler / rustc_passes / src / reachable.rs
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
6 // reachable as well.
7
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::intravisit::{self, Visitor};
13 use rustc_hir::itemlikevisit::ItemLikeVisitor;
14 use rustc_hir::Node;
15 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
16 use rustc_middle::middle::privacy;
17 use rustc_middle::ty::query::Providers;
18 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
19 use rustc_session::config::CrateType;
20 use rustc_target::spec::abi::Abi;
21
22 // Returns true if the given item must be inlined because it may be
23 // monomorphized or it was marked with `#[inline]`. This will only return
24 // true for functions.
25 fn item_might_be_inlined(tcx: TyCtxt<'_>, item: &hir::Item<'_>, attrs: &CodegenFnAttrs) -> bool {
26     if attrs.requests_inline() {
27         return true;
28     }
29
30     match item.kind {
31         hir::ItemKind::Fn(ref sig, ..) if sig.header.is_const() => true,
32         hir::ItemKind::Impl { .. } | hir::ItemKind::Fn(..) => {
33             let generics = tcx.generics_of(item.def_id);
34             generics.requires_monomorphization(tcx)
35         }
36         _ => false,
37     }
38 }
39
40 fn method_might_be_inlined(
41     tcx: TyCtxt<'_>,
42     impl_item: &hir::ImplItem<'_>,
43     impl_src: LocalDefId,
44 ) -> bool {
45     let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id().owner.to_def_id());
46     let generics = tcx.generics_of(impl_item.def_id);
47     if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) {
48         return true;
49     }
50     if let hir::ImplItemKind::Fn(method_sig, _) = &impl_item.kind {
51         if method_sig.header.is_const() {
52             return true;
53         }
54     }
55     match tcx.hir().find_by_def_id(impl_src) {
56         Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs),
57         Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"),
58     }
59 }
60
61 // Information needed while computing reachability.
62 struct ReachableContext<'tcx> {
63     // The type context.
64     tcx: TyCtxt<'tcx>,
65     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
66     // The set of items which must be exported in the linkage sense.
67     reachable_symbols: FxHashSet<LocalDefId>,
68     // A worklist of item IDs. Each item ID in this worklist will be inlined
69     // and will be scanned for further references.
70     // FIXME(eddyb) benchmark if this would be faster as a `VecDeque`.
71     worklist: Vec<LocalDefId>,
72     // Whether any output of this compilation is a library
73     any_library: bool,
74 }
75
76 impl<'tcx> Visitor<'tcx> for ReachableContext<'tcx> {
77     fn visit_nested_body(&mut self, body: hir::BodyId) {
78         let old_maybe_typeck_results =
79             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
80         let body = self.tcx.hir().body(body);
81         self.visit_body(body);
82         self.maybe_typeck_results = old_maybe_typeck_results;
83     }
84
85     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
86         let res = match expr.kind {
87             hir::ExprKind::Path(ref qpath) => {
88                 Some(self.typeck_results().qpath_res(qpath, expr.hir_id))
89             }
90             hir::ExprKind::MethodCall(..) => self
91                 .typeck_results()
92                 .type_dependent_def(expr.hir_id)
93                 .map(|(kind, def_id)| Res::Def(kind, def_id)),
94             _ => None,
95         };
96
97         if let Some(res) = res && let Some(def_id) = res.opt_def_id().and_then(|el| el.as_local()) {
98             if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
99                 self.worklist.push(def_id);
100             } else {
101                 match res {
102                     // If this path leads to a constant, then we need to
103                     // recurse into the constant to continue finding
104                     // items that are reachable.
105                     Res::Def(DefKind::Const | DefKind::AssocConst, _) => {
106                         self.worklist.push(def_id);
107                     }
108
109                     // If this wasn't a static, then the destination is
110                     // surely reachable.
111                     _ => {
112                         self.reachable_symbols.insert(def_id);
113                     }
114                 }
115             }
116         }
117
118         intravisit::walk_expr(self, expr)
119     }
120 }
121
122 impl<'tcx> ReachableContext<'tcx> {
123     /// Gets the type-checking results for the current body.
124     /// As this will ICE if called outside bodies, only call when working with
125     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
126     #[track_caller]
127     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
128         self.maybe_typeck_results
129             .expect("`ReachableContext::typeck_results` called outside of body")
130     }
131
132     // Returns true if the given def ID represents a local item that is
133     // eligible for inlining and false otherwise.
134     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
135         let Some(def_id) = def_id.as_local() else {
136             return false;
137         };
138
139         match self.tcx.hir().find_by_def_id(def_id) {
140             Some(Node::Item(item)) => match item.kind {
141                 hir::ItemKind::Fn(..) => {
142                     item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
143                 }
144                 _ => false,
145             },
146             Some(Node::TraitItem(trait_method)) => match trait_method.kind {
147                 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
148                 hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true,
149                 hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
150                 | hir::TraitItemKind::Type(..) => false,
151             },
152             Some(Node::ImplItem(impl_item)) => {
153                 match impl_item.kind {
154                     hir::ImplItemKind::Const(..) => true,
155                     hir::ImplItemKind::Fn(..) => {
156                         let attrs = self.tcx.codegen_fn_attrs(def_id);
157                         let generics = self.tcx.generics_of(def_id);
158                         if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
159                             true
160                         } else {
161                             let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
162                             let impl_did = self.tcx.hir().get_parent_item(hir_id);
163                             // Check the impl. If the generics on the self
164                             // type of the impl require inlining, this method
165                             // does too.
166                             match self.tcx.hir().expect_item(impl_did).kind {
167                                 hir::ItemKind::Impl { .. } => {
168                                     let generics = self.tcx.generics_of(impl_did);
169                                     generics.requires_monomorphization(self.tcx)
170                                 }
171                                 _ => false,
172                             }
173                         }
174                     }
175                     hir::ImplItemKind::TyAlias(_) => false,
176                 }
177             }
178             Some(_) => false,
179             None => false, // This will happen for default methods.
180         }
181     }
182
183     // Step 2: Mark all symbols that the symbols on the worklist touch.
184     fn propagate(&mut self) {
185         let mut scanned = FxHashSet::default();
186         while let Some(search_item) = self.worklist.pop() {
187             if !scanned.insert(search_item) {
188                 continue;
189             }
190
191             if let Some(ref item) = self.tcx.hir().find_by_def_id(search_item) {
192                 self.propagate_node(item, search_item);
193             }
194         }
195     }
196
197     fn propagate_node(&mut self, node: &Node<'tcx>, search_item: LocalDefId) {
198         if !self.any_library {
199             // If we are building an executable, only explicitly extern
200             // types need to be exported.
201             let reachable =
202                 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })
203                 | Node::ImplItem(hir::ImplItem {
204                     kind: hir::ImplItemKind::Fn(sig, ..), ..
205                 }) = *node
206                 {
207                     sig.header.abi != Abi::Rust
208                 } else {
209                     false
210                 };
211             let codegen_attrs = if self.tcx.def_kind(search_item).has_codegen_attrs() {
212                 self.tcx.codegen_fn_attrs(search_item)
213             } else {
214                 CodegenFnAttrs::EMPTY
215             };
216             let is_extern = codegen_attrs.contains_extern_indicator();
217             let std_internal =
218                 codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
219             if reachable || is_extern || std_internal {
220                 self.reachable_symbols.insert(search_item);
221             }
222         } else {
223             // If we are building a library, then reachable symbols will
224             // continue to participate in linkage after this product is
225             // produced. In this case, we traverse the ast node, recursing on
226             // all reachable nodes from this one.
227             self.reachable_symbols.insert(search_item);
228         }
229
230         match *node {
231             Node::Item(item) => {
232                 match item.kind {
233                     hir::ItemKind::Fn(.., body) => {
234                         if item_might_be_inlined(
235                             self.tcx,
236                             &item,
237                             self.tcx.codegen_fn_attrs(item.def_id),
238                         ) {
239                             self.visit_nested_body(body);
240                         }
241                     }
242
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) | hir::ItemKind::Static(_, _, init) => {
247                         self.visit_nested_body(init);
248                     }
249
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::Macro(..)
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(..) => {}
267                 }
268             }
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
274                     }
275                     hir::TraitItemKind::Const(_, Some(body_id))
276                     | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
277                         self.visit_nested_body(body_id);
278                     }
279                     hir::TraitItemKind::Type(..) => {}
280                 }
281             }
282             Node::ImplItem(impl_item) => match impl_item.kind {
283                 hir::ImplItemKind::Const(_, body) => {
284                     self.visit_nested_body(body);
285                 }
286                 hir::ImplItemKind::Fn(_, body) => {
287                     let impl_def_id = self.tcx.local_parent(search_item);
288                     if method_might_be_inlined(self.tcx, impl_item, impl_def_id) {
289                         self.visit_nested_body(body)
290                     }
291                 }
292                 hir::ImplItemKind::TyAlias(_) => {}
293             },
294             Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
295                 self.visit_nested_body(body);
296             }
297             // Nothing to recurse on for these
298             Node::ForeignItem(_)
299             | Node::Variant(_)
300             | Node::Ctor(..)
301             | Node::Field(_)
302             | Node::Ty(_)
303             | Node::Crate(_) => {}
304             _ => {
305                 bug!(
306                     "found unexpected node kind in worklist: {} ({:?})",
307                     self.tcx
308                         .hir()
309                         .node_to_string(self.tcx.hir().local_def_id_to_hir_id(search_item)),
310                     node,
311                 );
312             }
313         }
314     }
315 }
316
317 // Some methods from non-exported (completely private) trait impls still have to be
318 // reachable if they are called from inlinable code. Generally, it's not known until
319 // monomorphization if a specific trait impl item can be reachable or not. So, we
320 // conservatively mark all of them as reachable.
321 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
322 // items of non-exported traits (or maybe all local traits?) unless their respective
323 // trait items are used from inlinable code through method call syntax or UFCS, or their
324 // trait is a lang item.
325 struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
326     tcx: TyCtxt<'tcx>,
327     access_levels: &'a privacy::AccessLevels,
328     worklist: &'a mut Vec<LocalDefId>,
329 }
330
331 impl CollectPrivateImplItemsVisitor<'_, '_> {
332     fn push_to_worklist_if_has_custom_linkage(&mut self, def_id: LocalDefId) {
333         // Anything which has custom linkage gets thrown on the worklist no
334         // matter where it is in the crate, along with "special std symbols"
335         // which are currently akin to allocator symbols.
336         if self.tcx.def_kind(def_id).has_codegen_attrs() {
337             let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
338             if codegen_attrs.contains_extern_indicator()
339                 || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
340                 // FIXME(nbdd0121): `#[used]` are marked as reachable here so it's picked up by
341                 // `linked_symbols` in cg_ssa. They won't be exported in binary or cdylib due to their
342                 // `SymbolExportLevel::Rust` export level but may end up being exported in dylibs.
343                 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED)
344                 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
345             {
346                 self.worklist.push(def_id);
347             }
348         }
349     }
350 }
351
352 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
353     fn visit_item(&mut self, item: &hir::Item<'_>) {
354         self.push_to_worklist_if_has_custom_linkage(item.def_id);
355
356         // We need only trait impls here, not inherent impls, and only non-exported ones
357         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), ref items, .. }) =
358             item.kind
359         {
360             if !self.access_levels.is_reachable(item.def_id) {
361                 // FIXME(#53488) remove `let`
362                 let tcx = self.tcx;
363                 self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id));
364
365                 let Res::Def(DefKind::Trait, trait_def_id) = trait_ref.path.res else {
366                     unreachable!();
367                 };
368
369                 if !trait_def_id.is_local() {
370                     return;
371                 }
372
373                 self.worklist.extend(
374                     tcx.provided_trait_methods(trait_def_id)
375                         .map(|assoc| assoc.def_id.expect_local()),
376                 );
377             }
378         }
379     }
380
381     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
382
383     fn visit_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) {
384         self.push_to_worklist_if_has_custom_linkage(impl_item.def_id);
385     }
386
387     fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {
388         // We never export foreign functions as they have no body to export.
389     }
390 }
391
392 fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> FxHashSet<LocalDefId> {
393     let access_levels = &tcx.privacy_access_levels(());
394
395     let any_library =
396         tcx.sess.crate_types().iter().any(|ty| {
397             *ty == CrateType::Rlib || *ty == CrateType::Dylib || *ty == CrateType::ProcMacro
398         });
399     let mut reachable_context = ReachableContext {
400         tcx,
401         maybe_typeck_results: None,
402         reachable_symbols: Default::default(),
403         worklist: Vec::new(),
404         any_library,
405     };
406
407     // Step 1: Seed the worklist with all nodes which were found to be public as
408     //         a result of the privacy pass along with all local lang items and impl items.
409     //         If other crates link to us, they're going to expect to be able to
410     //         use the lang items, so we need to be sure to mark them as
411     //         exported.
412     reachable_context.worklist.extend(access_levels.map.keys());
413     for item in tcx.lang_items().items().iter() {
414         if let Some(def_id) = *item {
415             if let Some(def_id) = def_id.as_local() {
416                 reachable_context.worklist.push(def_id);
417             }
418         }
419     }
420     {
421         let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
422             tcx,
423             access_levels,
424             worklist: &mut reachable_context.worklist,
425         };
426         tcx.hir().visit_all_item_likes(&mut collect_private_impl_items);
427     }
428
429     // Step 2: Mark all symbols that the symbols on the worklist touch.
430     reachable_context.propagate();
431
432     debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
433
434     // Return the set of reachable symbols.
435     reachable_context.reachable_symbols
436 }
437
438 pub fn provide(providers: &mut Providers) {
439     *providers = Providers { reachable_set, ..*providers };
440 }