]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/reachable.rs
rustc_passes: Remove unused dependency rustc_trait_selection
[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, NestedVisitorMap, 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<'tcx>, 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(tcx.hir().local_def_id_to_hir_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     type Map = intravisit::ErasedMap<'tcx>;
78
79     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
80         NestedVisitorMap::None
81     }
82
83     fn visit_nested_body(&mut self, body: hir::BodyId) {
84         let old_maybe_typeck_results =
85             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
86         let body = self.tcx.hir().body(body);
87         self.visit_body(body);
88         self.maybe_typeck_results = old_maybe_typeck_results;
89     }
90
91     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
92         let res = match expr.kind {
93             hir::ExprKind::Path(ref qpath) => {
94                 Some(self.typeck_results().qpath_res(qpath, expr.hir_id))
95             }
96             hir::ExprKind::MethodCall(..) => self
97                 .typeck_results()
98                 .type_dependent_def(expr.hir_id)
99                 .map(|(kind, def_id)| Res::Def(kind, def_id)),
100             _ => None,
101         };
102
103         if let Some(res) = res {
104             if let Some(def_id) = res.opt_def_id().and_then(|def_id| def_id.as_local()) {
105                 if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
106                     self.worklist.push(def_id);
107                 } else {
108                     match res {
109                         // If this path leads to a constant, then we need to
110                         // recurse into the constant to continue finding
111                         // items that are reachable.
112                         Res::Def(DefKind::Const | DefKind::AssocConst, _) => {
113                             self.worklist.push(def_id);
114                         }
115
116                         // If this wasn't a static, then the destination is
117                         // surely reachable.
118                         _ => {
119                             self.reachable_symbols.insert(def_id);
120                         }
121                     }
122                 }
123             }
124         }
125
126         intravisit::walk_expr(self, expr)
127     }
128 }
129
130 impl<'tcx> ReachableContext<'tcx> {
131     /// Gets the type-checking results for the current body.
132     /// As this will ICE if called outside bodies, only call when working with
133     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
134     #[track_caller]
135     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
136         self.maybe_typeck_results
137             .expect("`ReachableContext::typeck_results` called outside of body")
138     }
139
140     // Returns true if the given def ID represents a local item that is
141     // eligible for inlining and false otherwise.
142     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
143         let hir_id = match def_id.as_local() {
144             Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
145             None => {
146                 return false;
147             }
148         };
149
150         match self.tcx.hir().find(hir_id) {
151             Some(Node::Item(item)) => match item.kind {
152                 hir::ItemKind::Fn(..) => {
153                     item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
154                 }
155                 _ => false,
156             },
157             Some(Node::TraitItem(trait_method)) => match trait_method.kind {
158                 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
159                 hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true,
160                 hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
161                 | hir::TraitItemKind::Type(..) => false,
162             },
163             Some(Node::ImplItem(impl_item)) => {
164                 match impl_item.kind {
165                     hir::ImplItemKind::Const(..) => true,
166                     hir::ImplItemKind::Fn(..) => {
167                         let attrs = self.tcx.codegen_fn_attrs(def_id);
168                         let generics = self.tcx.generics_of(def_id);
169                         if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
170                             true
171                         } else {
172                             let impl_did = self.tcx.hir().get_parent_did(hir_id);
173                             // Check the impl. If the generics on the self
174                             // type of the impl require inlining, this method
175                             // does too.
176                             let impl_hir_id = self.tcx.hir().local_def_id_to_hir_id(impl_did);
177                             match self.tcx.hir().expect_item(impl_hir_id).kind {
178                                 hir::ItemKind::Impl { .. } => {
179                                     let generics = self.tcx.generics_of(impl_did);
180                                     generics.requires_monomorphization(self.tcx)
181                                 }
182                                 _ => false,
183                             }
184                         }
185                     }
186                     hir::ImplItemKind::TyAlias(_) => false,
187                 }
188             }
189             Some(_) => false,
190             None => false, // This will happen for default methods.
191         }
192     }
193
194     // Step 2: Mark all symbols that the symbols on the worklist touch.
195     fn propagate(&mut self) {
196         let mut scanned = FxHashSet::default();
197         while let Some(search_item) = self.worklist.pop() {
198             if !scanned.insert(search_item) {
199                 continue;
200             }
201
202             if let Some(ref item) =
203                 self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(search_item))
204             {
205                 self.propagate_node(item, search_item);
206             }
207         }
208     }
209
210     fn propagate_node(&mut self, node: &Node<'tcx>, search_item: LocalDefId) {
211         if !self.any_library {
212             // If we are building an executable, only explicitly extern
213             // types need to be exported.
214             if let Node::Item(item) = *node {
215                 let reachable = if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
216                     sig.header.abi != Abi::Rust
217                 } else {
218                     false
219                 };
220                 let codegen_attrs = self.tcx.codegen_fn_attrs(item.def_id);
221                 let is_extern = codegen_attrs.contains_extern_indicator();
222                 let std_internal =
223                     codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
224                 if reachable || is_extern || std_internal {
225                     self.reachable_symbols.insert(search_item);
226                 }
227             }
228         } else {
229             // If we are building a library, then reachable symbols will
230             // continue to participate in linkage after this product is
231             // produced. In this case, we traverse the ast node, recursing on
232             // all reachable nodes from this one.
233             self.reachable_symbols.insert(search_item);
234         }
235
236         match *node {
237             Node::Item(item) => {
238                 match item.kind {
239                     hir::ItemKind::Fn(.., body) => {
240                         if item_might_be_inlined(
241                             self.tcx,
242                             &item,
243                             self.tcx.codegen_fn_attrs(item.def_id),
244                         ) {
245                             self.visit_nested_body(body);
246                         }
247                     }
248
249                     // Reachable constants will be inlined into other crates
250                     // unconditionally, so we need to make sure that their
251                     // contents are also reachable.
252                     hir::ItemKind::Const(_, init) | hir::ItemKind::Static(_, _, init) => {
253                         self.visit_nested_body(init);
254                     }
255
256                     // These are normal, nothing reachable about these
257                     // inherently and their children are already in the
258                     // worklist, as determined by the privacy pass
259                     hir::ItemKind::ExternCrate(_)
260                     | hir::ItemKind::Use(..)
261                     | hir::ItemKind::OpaqueTy(..)
262                     | hir::ItemKind::TyAlias(..)
263                     | hir::ItemKind::Mod(..)
264                     | hir::ItemKind::ForeignMod { .. }
265                     | hir::ItemKind::Impl { .. }
266                     | hir::ItemKind::Trait(..)
267                     | hir::ItemKind::TraitAlias(..)
268                     | hir::ItemKind::Struct(..)
269                     | hir::ItemKind::Enum(..)
270                     | hir::ItemKind::Union(..)
271                     | hir::ItemKind::GlobalAsm(..) => {}
272                 }
273             }
274             Node::TraitItem(trait_method) => {
275                 match trait_method.kind {
276                     hir::TraitItemKind::Const(_, None)
277                     | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => {
278                         // Keep going, nothing to get exported
279                     }
280                     hir::TraitItemKind::Const(_, Some(body_id))
281                     | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
282                         self.visit_nested_body(body_id);
283                     }
284                     hir::TraitItemKind::Type(..) => {}
285                 }
286             }
287             Node::ImplItem(impl_item) => match impl_item.kind {
288                 hir::ImplItemKind::Const(_, body) => {
289                     self.visit_nested_body(body);
290                 }
291                 hir::ImplItemKind::Fn(_, body) => {
292                     let impl_def_id =
293                         self.tcx.parent(search_item.to_def_id()).unwrap().expect_local();
294                     if method_might_be_inlined(self.tcx, impl_item, impl_def_id) {
295                         self.visit_nested_body(body)
296                     }
297                 }
298                 hir::ImplItemKind::TyAlias(_) => {}
299             },
300             Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
301                 self.visit_nested_body(body);
302             }
303             // Nothing to recurse on for these
304             Node::ForeignItem(_)
305             | Node::Variant(_)
306             | Node::Ctor(..)
307             | Node::Field(_)
308             | Node::Ty(_)
309             | Node::Crate(_)
310             | Node::MacroDef(_) => {}
311             _ => {
312                 bug!(
313                     "found unexpected node kind in worklist: {} ({:?})",
314                     self.tcx
315                         .hir()
316                         .node_to_string(self.tcx.hir().local_def_id_to_hir_id(search_item)),
317                     node,
318                 );
319             }
320         }
321     }
322 }
323
324 // Some methods from non-exported (completely private) trait impls still have to be
325 // reachable if they are called from inlinable code. Generally, it's not known until
326 // monomorphization if a specific trait impl item can be reachable or not. So, we
327 // conservatively mark all of them as reachable.
328 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
329 // items of non-exported traits (or maybe all local traits?) unless their respective
330 // trait items are used from inlinable code through method call syntax or UFCS, or their
331 // trait is a lang item.
332 struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
333     tcx: TyCtxt<'tcx>,
334     access_levels: &'a privacy::AccessLevels,
335     worklist: &'a mut Vec<LocalDefId>,
336 }
337
338 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
339     fn visit_item(&mut self, item: &hir::Item<'_>) {
340         // Anything which has custom linkage gets thrown on the worklist no
341         // matter where it is in the crate, along with "special std symbols"
342         // which are currently akin to allocator symbols.
343         let codegen_attrs = self.tcx.codegen_fn_attrs(item.def_id);
344         if codegen_attrs.contains_extern_indicator()
345             || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
346         {
347             self.worklist.push(item.def_id);
348         }
349
350         // We need only trait impls here, not inherent impls, and only non-exported ones
351         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), ref items, .. }) =
352             item.kind
353         {
354             if !self.access_levels.is_reachable(item.hir_id()) {
355                 // FIXME(#53488) remove `let`
356                 let tcx = self.tcx;
357                 self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id));
358
359                 let trait_def_id = match trait_ref.path.res {
360                     Res::Def(DefKind::Trait, def_id) => def_id,
361                     _ => unreachable!(),
362                 };
363
364                 if !trait_def_id.is_local() {
365                     return;
366                 }
367
368                 self.worklist.extend(
369                     tcx.provided_trait_methods(trait_def_id)
370                         .map(|assoc| assoc.def_id.expect_local()),
371                 );
372             }
373         }
374     }
375
376     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
377
378     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {
379         // processed in visit_item above
380     }
381
382     fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {
383         // We never export foreign functions as they have no body to export.
384     }
385 }
386
387 fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> FxHashSet<LocalDefId> {
388     let access_levels = &tcx.privacy_access_levels(());
389
390     let any_library =
391         tcx.sess.crate_types().iter().any(|ty| {
392             *ty == CrateType::Rlib || *ty == CrateType::Dylib || *ty == CrateType::ProcMacro
393         });
394     let mut reachable_context = ReachableContext {
395         tcx,
396         maybe_typeck_results: None,
397         reachable_symbols: Default::default(),
398         worklist: Vec::new(),
399         any_library,
400     };
401
402     // Step 1: Seed the worklist with all nodes which were found to be public as
403     //         a result of the privacy pass along with all local lang items and impl items.
404     //         If other crates link to us, they're going to expect to be able to
405     //         use the lang items, so we need to be sure to mark them as
406     //         exported.
407     reachable_context
408         .worklist
409         .extend(access_levels.map.iter().map(|(id, _)| tcx.hir().local_def_id(*id)));
410     for item in tcx.lang_items().items().iter() {
411         if let Some(def_id) = *item {
412             if let Some(def_id) = def_id.as_local() {
413                 reachable_context.worklist.push(def_id);
414             }
415         }
416     }
417     {
418         let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
419             tcx,
420             access_levels,
421             worklist: &mut reachable_context.worklist,
422         };
423         tcx.hir().krate().visit_all_item_likes(&mut collect_private_impl_items);
424     }
425
426     // Step 2: Mark all symbols that the symbols on the worklist touch.
427     reachable_context.propagate();
428
429     debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
430
431     // Return the set of reachable symbols.
432     reachable_context.reachable_symbols
433 }
434
435 pub fn provide(providers: &mut Providers) {
436     *providers = Providers { reachable_set, ..*providers };
437 }