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.
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.
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
18 use hir::{CodegenFnAttrs, CodegenFnAttrFlags};
19 use hir::map as hir_map;
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;
27 use util::nodemap::{NodeSet, FxHashSet};
29 use rustc_target::spec::abi::Abi;
32 use hir::def_id::LOCAL_CRATE;
33 use hir::intravisit::{Visitor, NestedVisitorMap};
34 use hir::itemlikevisit::ItemLikeVisitor;
37 // Returns true if the given set of generics implies that the item it's
38 // associated with must be inlined.
39 fn generics_require_inlining(generics: &ty::Generics) -> bool {
40 for param in &generics.params {
42 GenericParamDefKind::Lifetime { .. } => {}
43 GenericParamDefKind::Type { .. } => return true,
49 // Returns true if the given item must be inlined because it may be
50 // monomorphized or it was marked with `#[inline]`. This will only return
51 // true for functions.
52 fn item_might_be_inlined(tcx: TyCtxt<'a, 'tcx, 'tcx>,
54 attrs: CodegenFnAttrs) -> bool {
55 if attrs.requests_inline() {
60 hir::ItemKind::Impl(..) |
61 hir::ItemKind::Fn(..) => {
62 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
63 generics_require_inlining(generics)
69 fn method_might_be_inlined<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
70 impl_item: &hir::ImplItem,
71 impl_src: DefId) -> bool {
72 let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner_def_id());
73 let generics = tcx.generics_of(tcx.hir.local_def_id(impl_item.id));
74 if codegen_fn_attrs.requests_inline() || generics_require_inlining(generics) {
77 if let Some(impl_node_id) = tcx.hir.as_local_node_id(impl_src) {
78 match tcx.hir.find(impl_node_id) {
79 Some(hir_map::NodeItem(item)) =>
80 item_might_be_inlined(tcx, &item, codegen_fn_attrs),
82 span_bug!(impl_item.span, "impl did is not an item")
85 span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
89 // Information needed while computing reachability.
90 struct ReachableContext<'a, 'tcx: 'a> {
92 tcx: TyCtxt<'a, 'tcx, 'tcx>,
93 tables: &'a ty::TypeckTables<'tcx>,
94 // The set of items which must be exported in the linkage sense.
95 reachable_symbols: NodeSet,
96 // A worklist of item IDs. Each item ID in this worklist will be inlined
97 // and will be scanned for further references.
98 worklist: Vec<ast::NodeId>,
99 // Whether any output of this compilation is a library
103 impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
104 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
105 NestedVisitorMap::None
108 fn visit_nested_body(&mut self, body: hir::BodyId) {
109 let old_tables = self.tables;
110 self.tables = self.tcx.body_tables(body);
111 let body = self.tcx.hir.body(body);
112 self.visit_body(body);
113 self.tables = old_tables;
116 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
117 let def = match expr.node {
118 hir::ExprKind::Path(ref qpath) => {
119 Some(self.tables.qpath_def(qpath, expr.hir_id))
121 hir::ExprKind::MethodCall(..) => {
122 self.tables.type_dependent_defs().get(expr.hir_id).cloned()
128 Some(Def::Local(node_id)) | Some(Def::Upvar(node_id, ..)) => {
129 self.reachable_symbols.insert(node_id);
132 let def_id = def.def_id();
133 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
134 if self.def_id_represents_local_inlined_item(def_id) {
135 self.worklist.push(node_id);
138 // If this path leads to a constant, then we need to
139 // recurse into the constant to continue finding
140 // items that are reachable.
141 Def::Const(..) | Def::AssociatedConst(..) => {
142 self.worklist.push(node_id);
145 // If this wasn't a static, then the destination is
148 self.reachable_symbols.insert(node_id);
157 intravisit::walk_expr(self, expr)
161 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
162 // Returns true if the given def ID represents a local item that is
163 // eligible for inlining and false otherwise.
164 fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
165 let node_id = match self.tcx.hir.as_local_node_id(def_id) {
166 Some(node_id) => node_id,
167 None => { return false; }
170 match self.tcx.hir.find(node_id) {
171 Some(hir_map::NodeItem(item)) => {
173 hir::ItemKind::Fn(..) =>
174 item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id)),
178 Some(hir_map::NodeTraitItem(trait_method)) => {
179 match trait_method.node {
180 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
181 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => true,
182 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
183 hir::TraitItemKind::Type(..) => false,
186 Some(hir_map::NodeImplItem(impl_item)) => {
187 match impl_item.node {
188 hir::ImplItemKind::Const(..) => true,
189 hir::ImplItemKind::Method(..) => {
190 let attrs = self.tcx.codegen_fn_attrs(def_id);
191 let generics = self.tcx.generics_of(def_id);
192 if generics_require_inlining(&generics) ||
193 attrs.requests_inline() {
196 let impl_did = self.tcx
198 .get_parent_did(node_id);
199 // Check the impl. If the generics on the self
200 // type of the impl require inlining, this method
202 let impl_node_id = self.tcx.hir.as_local_node_id(impl_did).unwrap();
203 match self.tcx.hir.expect_item(impl_node_id).node {
204 hir::ItemKind::Impl(..) => {
205 let generics = self.tcx.generics_of(impl_did);
206 generics_require_inlining(&generics)
212 hir::ImplItemKind::Existential(..) |
213 hir::ImplItemKind::Type(_) => false,
217 None => false // This will happen for default methods.
221 // Step 2: Mark all symbols that the symbols on the worklist touch.
222 fn propagate(&mut self) {
223 let mut scanned = FxHashSet();
224 while let Some(search_item) = self.worklist.pop() {
225 if !scanned.insert(search_item) {
229 if let Some(ref item) = self.tcx.hir.find(search_item) {
230 self.propagate_node(item, search_item);
235 fn propagate_node(&mut self, node: &hir_map::Node<'tcx>,
236 search_item: ast::NodeId) {
237 if !self.any_library {
238 // If we are building an executable, only explicitly extern
239 // types need to be exported.
240 if let hir_map::NodeItem(item) = *node {
241 let reachable = if let hir::ItemKind::Fn(_, header, ..) = item.node {
242 header.abi != Abi::Rust
246 let def_id = self.tcx.hir.local_def_id(item.id);
247 let is_extern = self.tcx.codegen_fn_attrs(def_id).contains_extern_indicator();
248 if reachable || is_extern {
249 self.reachable_symbols.insert(search_item);
253 // If we are building a library, then reachable symbols will
254 // continue to participate in linkage after this product is
255 // produced. In this case, we traverse the ast node, recursing on
256 // all reachable nodes from this one.
257 self.reachable_symbols.insert(search_item);
261 hir_map::NodeItem(item) => {
263 hir::ItemKind::Fn(.., body) => {
264 let def_id = self.tcx.hir.local_def_id(item.id);
265 if item_might_be_inlined(self.tcx,
267 self.tcx.codegen_fn_attrs(def_id)) {
268 self.visit_nested_body(body);
272 // Reachable constants will be inlined into other crates
273 // unconditionally, so we need to make sure that their
274 // contents are also reachable.
275 hir::ItemKind::Const(_, init) => {
276 self.visit_nested_body(init);
279 // These are normal, nothing reachable about these
280 // inherently and their children are already in the
281 // worklist, as determined by the privacy pass
282 hir::ItemKind::ExternCrate(_) |
283 hir::ItemKind::Use(..) |
284 hir::ItemKind::Existential(..) |
285 hir::ItemKind::Ty(..) |
286 hir::ItemKind::Static(..) |
287 hir::ItemKind::Mod(..) |
288 hir::ItemKind::ForeignMod(..) |
289 hir::ItemKind::Impl(..) |
290 hir::ItemKind::Trait(..) |
291 hir::ItemKind::TraitAlias(..) |
292 hir::ItemKind::Struct(..) |
293 hir::ItemKind::Enum(..) |
294 hir::ItemKind::Union(..) |
295 hir::ItemKind::GlobalAsm(..) => {}
298 hir_map::NodeTraitItem(trait_method) => {
299 match trait_method.node {
300 hir::TraitItemKind::Const(_, None) |
301 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
302 // Keep going, nothing to get exported
304 hir::TraitItemKind::Const(_, Some(body_id)) |
305 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
306 self.visit_nested_body(body_id);
308 hir::TraitItemKind::Type(..) => {}
311 hir_map::NodeImplItem(impl_item) => {
312 match impl_item.node {
313 hir::ImplItemKind::Const(_, body) => {
314 self.visit_nested_body(body);
316 hir::ImplItemKind::Method(_, body) => {
317 let did = self.tcx.hir.get_parent_did(search_item);
318 if method_might_be_inlined(self.tcx, impl_item, did) {
319 self.visit_nested_body(body)
322 hir::ImplItemKind::Existential(..) |
323 hir::ImplItemKind::Type(_) => {}
326 hir_map::NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(.., body, _, _), .. }) => {
327 self.visit_nested_body(body);
329 // Nothing to recurse on for these
330 hir_map::NodeForeignItem(_) |
331 hir_map::NodeVariant(_) |
332 hir_map::NodeStructCtor(_) |
333 hir_map::NodeField(_) |
335 hir_map::NodeMacroDef(_) => {}
337 bug!("found unexpected thingy in worklist: {}",
338 self.tcx.hir.node_to_string(search_item))
344 // Some methods from non-exported (completely private) trait impls still have to be
345 // reachable if they are called from inlinable code. Generally, it's not known until
346 // monomorphization if a specific trait impl item can be reachable or not. So, we
347 // conservatively mark all of them as reachable.
348 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
349 // items of non-exported traits (or maybe all local traits?) unless their respective
350 // trait items are used from inlinable code through method call syntax or UFCS, or their
351 // trait is a lang item.
352 struct CollectPrivateImplItemsVisitor<'a, 'tcx: 'a> {
353 tcx: TyCtxt<'a, 'tcx, 'tcx>,
354 access_levels: &'a privacy::AccessLevels,
355 worklist: &'a mut Vec<ast::NodeId>,
358 impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
359 fn visit_item(&mut self, item: &hir::Item) {
360 // Anything which has custom linkage gets thrown on the worklist no
361 // matter where it is in the crate, along with "special std symbols"
362 // which are currently akin to allocator symbols.
363 let def_id = self.tcx.hir.local_def_id(item.id);
364 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
365 if codegen_attrs.linkage.is_some() ||
366 codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
367 self.worklist.push(item.id);
370 // We need only trait impls here, not inherent impls, and only non-exported ones
371 if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
372 if !self.access_levels.is_reachable(item.id) {
373 self.worklist.extend(impl_item_refs.iter().map(|r| r.id.node_id));
375 let trait_def_id = match trait_ref.path.def {
376 Def::Trait(def_id) => def_id,
380 if !trait_def_id.is_local() {
384 for default_method in self.tcx.provided_trait_methods(trait_def_id) {
385 let node_id = self.tcx
387 .as_local_node_id(default_method.def_id)
389 self.worklist.push(node_id);
395 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
397 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
398 // processed in visit_item above
402 // We introduce a new-type here, so we can have a specialized HashStable
403 // implementation for it.
405 pub struct ReachableSet(pub Lrc<NodeSet>);
408 fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet {
409 debug_assert!(crate_num == LOCAL_CRATE);
411 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
413 let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
414 *ty == config::CrateType::Rlib || *ty == config::CrateType::Dylib ||
415 *ty == config::CrateType::ProcMacro
417 let mut reachable_context = ReachableContext {
419 tables: &ty::TypeckTables::empty(None),
420 reachable_symbols: NodeSet(),
421 worklist: Vec::new(),
425 // Step 1: Seed the worklist with all nodes which were found to be public as
426 // a result of the privacy pass along with all local lang items and impl items.
427 // If other crates link to us, they're going to expect to be able to
428 // use the lang items, so we need to be sure to mark them as
430 reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
431 for item in tcx.lang_items().items().iter() {
432 if let Some(did) = *item {
433 if let Some(node_id) = tcx.hir.as_local_node_id(did) {
434 reachable_context.worklist.push(node_id);
439 let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
442 worklist: &mut reachable_context.worklist,
444 tcx.hir.krate().visit_all_item_likes(&mut collect_private_impl_items);
447 // Step 2: Mark all symbols that the symbols on the worklist touch.
448 reachable_context.propagate();
450 // Return the set of reachable symbols.
451 ReachableSet(Lrc::new(reachable_context.reachable_symbols))
454 pub fn provide(providers: &mut Providers) {
455 *providers = Providers {