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