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