]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/reachable.rs
Move reachable.rs to librustc_passes.
[rust.git] / src / librustc_passes / 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 crate::hir::def::{DefKind, Res};
9 use crate::hir::def_id::{CrateNum, DefId};
10 use crate::hir::Node;
11 use crate::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
12 use crate::middle::privacy;
13 use crate::session::config;
14 use crate::ty::query::Providers;
15 use crate::ty::{self, TyCtxt};
16 use crate::util::nodemap::{FxHashSet, HirIdSet};
17 use rustc_data_structures::sync::Lrc;
18
19 use crate::hir;
20 use crate::hir::def_id::LOCAL_CRATE;
21 use crate::hir::intravisit;
22 use crate::hir::intravisit::{NestedVisitorMap, Visitor};
23 use crate::hir::itemlikevisit::ItemLikeVisitor;
24 use rustc_macros::HashStable;
25 use rustc_target::spec::abi::Abi;
26
27 // Returns true if the given item must be inlined because it may be
28 // monomorphized or it was marked with `#[inline]`. This will only return
29 // true for functions.
30 fn item_might_be_inlined(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>, attrs: CodegenFnAttrs) -> bool {
31     if attrs.requests_inline() {
32         return true;
33     }
34
35     match item.kind {
36         hir::ItemKind::Fn(ref sig, ..) if sig.header.is_const() => {
37             return true;
38         }
39         hir::ItemKind::Impl(..) | hir::ItemKind::Fn(..) => {
40             let generics = tcx.generics_of(tcx.hir().local_def_id(item.hir_id));
41             generics.requires_monomorphization(tcx)
42         }
43         _ => false,
44     }
45 }
46
47 fn method_might_be_inlined(
48     tcx: TyCtxt<'_>,
49     impl_item: &hir::ImplItem<'_>,
50     impl_src: DefId,
51 ) -> bool {
52     let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner_def_id());
53     let generics = tcx.generics_of(tcx.hir().local_def_id(impl_item.hir_id));
54     if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) {
55         return true;
56     }
57     if let hir::ImplItemKind::Method(method_sig, _) = &impl_item.kind {
58         if method_sig.header.is_const() {
59             return true;
60         }
61     }
62     if let Some(impl_hir_id) = tcx.hir().as_local_hir_id(impl_src) {
63         match tcx.hir().find(impl_hir_id) {
64             Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs),
65             Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"),
66         }
67     } else {
68         span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
69     }
70 }
71
72 // Information needed while computing reachability.
73 struct ReachableContext<'a, 'tcx> {
74     // The type context.
75     tcx: TyCtxt<'tcx>,
76     tables: &'a ty::TypeckTables<'tcx>,
77     // The set of items which must be exported in the linkage sense.
78     reachable_symbols: HirIdSet,
79     // A worklist of item IDs. Each item ID in this worklist will be inlined
80     // and will be scanned for further references.
81     worklist: Vec<hir::HirId>,
82     // Whether any output of this compilation is a library
83     any_library: bool,
84 }
85
86 impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
87     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
88         NestedVisitorMap::None
89     }
90
91     fn visit_nested_body(&mut self, body: hir::BodyId) {
92         let old_tables = self.tables;
93         self.tables = self.tcx.body_tables(body);
94         let body = self.tcx.hir().body(body);
95         self.visit_body(body);
96         self.tables = old_tables;
97     }
98
99     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
100         let res = match expr.kind {
101             hir::ExprKind::Path(ref qpath) => Some(self.tables.qpath_res(qpath, expr.hir_id)),
102             hir::ExprKind::MethodCall(..) => self
103                 .tables
104                 .type_dependent_def(expr.hir_id)
105                 .map(|(kind, def_id)| Res::Def(kind, def_id)),
106             _ => None,
107         };
108
109         match res {
110             Some(Res::Local(hir_id)) => {
111                 self.reachable_symbols.insert(hir_id);
112             }
113             Some(res) => {
114                 if let Some((hir_id, def_id)) = res.opt_def_id().and_then(|def_id| {
115                     self.tcx.hir().as_local_hir_id(def_id).map(|hir_id| (hir_id, def_id))
116                 }) {
117                     if self.def_id_represents_local_inlined_item(def_id) {
118                         self.worklist.push(hir_id);
119                     } else {
120                         match res {
121                             // If this path leads to a constant, then we need to
122                             // recurse into the constant to continue finding
123                             // items that are reachable.
124                             Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {
125                                 self.worklist.push(hir_id);
126                             }
127
128                             // If this wasn't a static, then the destination is
129                             // surely reachable.
130                             _ => {
131                                 self.reachable_symbols.insert(hir_id);
132                             }
133                         }
134                     }
135                 }
136             }
137             _ => {}
138         }
139
140         intravisit::walk_expr(self, expr)
141     }
142 }
143
144 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
145     // Returns true if the given def ID represents a local item that is
146     // eligible for inlining and false otherwise.
147     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
148         let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
149             Some(hir_id) => hir_id,
150             None => {
151                 return false;
152             }
153         };
154
155         match self.tcx.hir().find(hir_id) {
156             Some(Node::Item(item)) => match item.kind {
157                 hir::ItemKind::Fn(..) => {
158                     item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
159                 }
160                 _ => false,
161             },
162             Some(Node::TraitItem(trait_method)) => match trait_method.kind {
163                 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
164                 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => true,
165                 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))
166                 | hir::TraitItemKind::Type(..) => false,
167             },
168             Some(Node::ImplItem(impl_item)) => {
169                 match impl_item.kind {
170                     hir::ImplItemKind::Const(..) => true,
171                     hir::ImplItemKind::Method(..) => {
172                         let attrs = self.tcx.codegen_fn_attrs(def_id);
173                         let generics = self.tcx.generics_of(def_id);
174                         if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
175                             true
176                         } else {
177                             let impl_did = self.tcx.hir().get_parent_did(hir_id);
178                             // Check the impl. If the generics on the self
179                             // type of the impl require inlining, this method
180                             // does too.
181                             let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did).unwrap();
182                             match self.tcx.hir().expect_item(impl_hir_id).kind {
183                                 hir::ItemKind::Impl(..) => {
184                                     let generics = self.tcx.generics_of(impl_did);
185                                     generics.requires_monomorphization(self.tcx)
186                                 }
187                                 _ => false,
188                             }
189                         }
190                     }
191                     hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => false,
192                 }
193             }
194             Some(_) => false,
195             None => false, // This will happen for default methods.
196         }
197     }
198
199     // Step 2: Mark all symbols that the symbols on the worklist touch.
200     fn propagate(&mut self) {
201         let mut scanned = FxHashSet::default();
202         while let Some(search_item) = self.worklist.pop() {
203             if !scanned.insert(search_item) {
204                 continue;
205             }
206
207             if let Some(ref item) = self.tcx.hir().find(search_item) {
208                 self.propagate_node(item, search_item);
209             }
210         }
211     }
212
213     fn propagate_node(&mut self, node: &Node<'tcx>, search_item: hir::HirId) {
214         if !self.any_library {
215             // If we are building an executable, only explicitly extern
216             // types need to be exported.
217             if let Node::Item(item) = *node {
218                 let reachable = if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
219                     sig.header.abi != Abi::Rust
220                 } else {
221                     false
222                 };
223                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
224                 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
225                 let is_extern = codegen_attrs.contains_extern_indicator();
226                 let std_internal =
227                     codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
228                 if reachable || is_extern || std_internal {
229                     self.reachable_symbols.insert(search_item);
230                 }
231             }
232         } else {
233             // If we are building a library, then reachable symbols will
234             // continue to participate in linkage after this product is
235             // produced. In this case, we traverse the ast node, recursing on
236             // all reachable nodes from this one.
237             self.reachable_symbols.insert(search_item);
238         }
239
240         match *node {
241             Node::Item(item) => {
242                 match item.kind {
243                     hir::ItemKind::Fn(.., body) => {
244                         let def_id = self.tcx.hir().local_def_id(item.hir_id);
245                         if item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
246                         {
247                             self.visit_nested_body(body);
248                         }
249                     }
250
251                     // Reachable constants will be inlined into other crates
252                     // unconditionally, so we need to make sure that their
253                     // contents are also reachable.
254                     hir::ItemKind::Const(_, init) => {
255                         self.visit_nested_body(init);
256                     }
257
258                     // These are normal, nothing reachable about these
259                     // inherently and their children are already in the
260                     // worklist, as determined by the privacy pass
261                     hir::ItemKind::ExternCrate(_)
262                     | hir::ItemKind::Use(..)
263                     | hir::ItemKind::OpaqueTy(..)
264                     | hir::ItemKind::TyAlias(..)
265                     | hir::ItemKind::Static(..)
266                     | hir::ItemKind::Mod(..)
267                     | hir::ItemKind::ForeignMod(..)
268                     | hir::ItemKind::Impl(..)
269                     | hir::ItemKind::Trait(..)
270                     | hir::ItemKind::TraitAlias(..)
271                     | hir::ItemKind::Struct(..)
272                     | hir::ItemKind::Enum(..)
273                     | hir::ItemKind::Union(..)
274                     | hir::ItemKind::GlobalAsm(..) => {}
275                 }
276             }
277             Node::TraitItem(trait_method) => {
278                 match trait_method.kind {
279                     hir::TraitItemKind::Const(_, None)
280                     | hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
281                         // Keep going, nothing to get exported
282                     }
283                     hir::TraitItemKind::Const(_, Some(body_id))
284                     | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
285                         self.visit_nested_body(body_id);
286                     }
287                     hir::TraitItemKind::Type(..) => {}
288                 }
289             }
290             Node::ImplItem(impl_item) => match impl_item.kind {
291                 hir::ImplItemKind::Const(_, body) => {
292                     self.visit_nested_body(body);
293                 }
294                 hir::ImplItemKind::Method(_, body) => {
295                     let did = self.tcx.hir().get_parent_did(search_item);
296                     if method_might_be_inlined(self.tcx, impl_item, did) {
297                         self.visit_nested_body(body)
298                     }
299                 }
300                 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => {}
301             },
302             Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
303                 self.visit_nested_body(body);
304             }
305             // Nothing to recurse on for these
306             Node::ForeignItem(_)
307             | Node::Variant(_)
308             | Node::Ctor(..)
309             | Node::Field(_)
310             | Node::Ty(_)
311             | Node::MacroDef(_) => {}
312             _ => {
313                 bug!(
314                     "found unexpected node kind in worklist: {} ({:?})",
315                     self.tcx.hir().node_to_string(search_item),
316                     node,
317                 );
318             }
319         }
320     }
321 }
322
323 // Some methods from non-exported (completely private) trait impls still have to be
324 // reachable if they are called from inlinable code. Generally, it's not known until
325 // monomorphization if a specific trait impl item can be reachable or not. So, we
326 // conservatively mark all of them as reachable.
327 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
328 // items of non-exported traits (or maybe all local traits?) unless their respective
329 // trait items are used from inlinable code through method call syntax or UFCS, or their
330 // trait is a lang item.
331 struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
332     tcx: TyCtxt<'tcx>,
333     access_levels: &'a privacy::AccessLevels,
334     worklist: &'a mut Vec<hir::HirId>,
335 }
336
337 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
338     fn visit_item(&mut self, item: &hir::Item<'_>) {
339         // Anything which has custom linkage gets thrown on the worklist no
340         // matter where it is in the crate, along with "special std symbols"
341         // which are currently akin to allocator symbols.
342         let def_id = self.tcx.hir().local_def_id(item.hir_id);
343         let codegen_attrs = self.tcx.codegen_fn_attrs(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.hir_id);
348         }
349
350         // We need only trait impls here, not inherent impls, and only non-exported ones
351         if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.kind {
352             if !self.access_levels.is_reachable(item.hir_id) {
353                 self.worklist.extend(impl_item_refs.iter().map(|ii_ref| ii_ref.id.hir_id));
354
355                 let trait_def_id = match trait_ref.path.res {
356                     Res::Def(DefKind::Trait, def_id) => def_id,
357                     _ => unreachable!(),
358                 };
359
360                 if !trait_def_id.is_local() {
361                     return;
362                 }
363
364                 let provided_trait_methods = self.tcx.provided_trait_methods(trait_def_id);
365                 self.worklist.reserve(provided_trait_methods.len());
366                 for default_method in provided_trait_methods {
367                     let hir_id = self.tcx.hir().as_local_hir_id(default_method.def_id).unwrap();
368                     self.worklist.push(hir_id);
369                 }
370             }
371         }
372     }
373
374     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
375
376     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {
377         // processed in visit_item above
378     }
379 }
380
381 // We introduce a new-type here, so we can have a specialized HashStable
382 // implementation for it.
383 #[derive(Clone, HashStable)]
384 pub struct ReachableSet(pub Lrc<HirIdSet>);
385
386 fn reachable_set(tcx: TyCtxt<'_>, crate_num: CrateNum) -> ReachableSet {
387     debug_assert!(crate_num == LOCAL_CRATE);
388
389     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
390
391     let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
392         *ty == config::CrateType::Rlib
393             || *ty == config::CrateType::Dylib
394             || *ty == config::CrateType::ProcMacro
395     });
396     let mut reachable_context = ReachableContext {
397         tcx,
398         tables: &ty::TypeckTables::empty(None),
399         reachable_symbols: Default::default(),
400         worklist: Vec::new(),
401         any_library,
402     };
403
404     // Step 1: Seed the worklist with all nodes which were found to be public as
405     //         a result of the privacy pass along with all local lang items and impl items.
406     //         If other crates link to us, they're going to expect to be able to
407     //         use the lang items, so we need to be sure to mark them as
408     //         exported.
409     reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
410     for item in tcx.lang_items().items().iter() {
411         if let Some(did) = *item {
412             if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
413                 reachable_context.worklist.push(hir_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     ReachableSet(Lrc::new(reachable_context.reachable_symbols))
433 }
434
435 pub fn provide(providers: &mut Providers<'_>) {
436     *providers = Providers { reachable_set, ..*providers };
437 }