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