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
23 use util::nodemap::NodeSet;
25 use std::collections::HashSet;
29 use syntax::ast_util::{is_local, PostExpansionMethod};
31 use syntax::attr::{InlineAlways, InlineHint, InlineNever, InlineNone};
33 use syntax::visit::Visitor;
36 // Returns true if the given set of attributes contains the `#[inline]`
38 fn attributes_specify_inlining(attrs: &[ast::Attribute]) -> bool {
39 match attr::find_inline_attr(attrs) {
40 InlineNone | InlineNever => false,
41 InlineAlways | InlineHint => true,
45 // Returns true if the given set of generics implies that the item it's
46 // associated with must be inlined.
47 fn generics_require_inlining(generics: &ast::Generics) -> bool {
48 !generics.ty_params.is_empty()
51 // Returns true if the given item must be inlined because it may be
52 // monomorphized or it was marked with `#[inline]`. This will only return
53 // true for functions.
54 fn item_might_be_inlined(item: &ast::Item) -> bool {
55 if attributes_specify_inlining(item.attrs.as_slice()) {
60 ast::ItemImpl(ref generics, _, _, _) |
61 ast::ItemFn(_, _, _, ref generics, _) => {
62 generics_require_inlining(generics)
68 fn method_might_be_inlined(tcx: &ty::ctxt, method: &ast::Method,
69 impl_src: ast::DefId) -> bool {
70 if attributes_specify_inlining(method.attrs.as_slice()) ||
71 generics_require_inlining(method.pe_generics()) {
74 if is_local(impl_src) {
76 match tcx.map.find(impl_src.node) {
77 Some(ast_map::NodeItem(item)) => {
78 item_might_be_inlined(&*item)
81 tcx.sess.span_bug(method.span, "impl did is not an item")
86 tcx.sess.span_bug(method.span, "found a foreign impl as a parent of a \
91 // Information needed while computing reachability.
92 struct ReachableContext<'a> {
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
104 impl<'a> Visitor<()> for ReachableContext<'a> {
106 fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
109 ast::ExprPath(_) => {
110 let def = match self.tcx.def_map.borrow().find(&expr.id) {
113 self.tcx.sess.span_bug(expr.span,
114 "def ID not in def map?!")
118 let def_id = def.def_id();
119 if is_local(def_id) {
120 if self.def_id_represents_local_inlined_item(def_id) {
121 self.worklist.push(def_id.node)
124 // If this path leads to a static, then we may have
125 // to do some work to figure out whether the static
126 // is indeed reachable. (Inlineable statics are
128 def::DefStatic(..) => {
129 self.worklist.push(def_id.node);
132 // If this wasn't a static, then this destination is
135 self.reachable_symbols.insert(def_id.node);
141 ast::ExprMethodCall(..) => {
142 let method_call = typeck::MethodCall::expr(expr.id);
143 match self.tcx.method_map.borrow().get(&method_call).origin {
144 typeck::MethodStatic(def_id) => {
145 if is_local(def_id) {
146 if self.def_id_represents_local_inlined_item(def_id) {
147 self.worklist.push(def_id.node)
149 self.reachable_symbols.insert(def_id.node);
158 visit::walk_expr(self, expr, ())
161 fn visit_item(&mut self, _item: &ast::Item, _: ()) {
162 // Do not recurse into items. These items will be added to the worklist
163 // and recursed into manually if necessary.
167 impl<'a> ReachableContext<'a> {
168 // Creates a new reachability computation context.
169 fn new(tcx: &'a ty::ctxt) -> ReachableContext<'a> {
170 let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
171 *ty != config::CrateTypeExecutable
175 reachable_symbols: NodeSet::new(),
176 worklist: Vec::new(),
177 any_library: any_library,
181 // Returns true if the given def ID represents a local item that is
182 // eligible for inlining and false otherwise.
183 fn def_id_represents_local_inlined_item(&self, def_id: ast::DefId) -> bool {
184 if def_id.krate != ast::LOCAL_CRATE {
188 let node_id = def_id.node;
189 match self.tcx.map.find(node_id) {
190 Some(ast_map::NodeItem(item)) => {
192 ast::ItemFn(..) => item_might_be_inlined(&*item),
196 Some(ast_map::NodeTraitItem(trait_method)) => {
197 match *trait_method {
198 ast::RequiredMethod(_) => false,
199 ast::ProvidedMethod(_) => true,
202 Some(ast_map::NodeImplItem(impl_item)) => {
204 ast::MethodImplItem(method) => {
205 if generics_require_inlining(method.pe_generics()) ||
206 attributes_specify_inlining(
207 method.attrs.as_slice()) {
210 let impl_did = self.tcx
212 .get_parent_did(node_id);
213 // Check the impl. If the generics on the self
214 // type of the impl require inlining, this method
216 assert!(impl_did.krate == ast::LOCAL_CRATE);
219 .expect_item(impl_did.node)
221 ast::ItemImpl(ref generics, _, _, _) => {
222 generics_require_inlining(generics)
231 None => false // This will happen for default methods.
235 // Step 2: Mark all symbols that the symbols on the worklist touch.
236 fn propagate(&mut self) {
237 let mut scanned = HashSet::new();
239 if self.worklist.len() == 0 {
242 let search_item = self.worklist.pop().unwrap();
243 if scanned.contains(&search_item) {
247 scanned.insert(search_item);
248 match self.tcx.map.find(search_item) {
249 Some(ref item) => self.propagate_node(item, search_item),
250 None if search_item == ast::CRATE_NODE_ID => {}
252 self.tcx.sess.bug(format!("found unmapped ID in worklist: \
254 search_item).as_slice())
260 fn propagate_node(&mut self, node: &ast_map::Node,
261 search_item: ast::NodeId) {
262 if !self.any_library {
263 // If we are building an executable, then there's no need to flag
264 // anything as external except for `extern fn` types. These
265 // functions may still participate in some form of native interface,
266 // but all other rust-only interfaces can be private (they will not
267 // participate in linkage after this product is produced)
269 ast_map::NodeItem(item) => {
271 ast::ItemFn(_, _, abi, _, _) => {
272 if abi != abi::Rust {
273 self.reachable_symbols.insert(search_item);
282 // If we are building a library, then reachable symbols will
283 // continue to participate in linkage after this product is
284 // produced. In this case, we traverse the ast node, recursing on
285 // all reachable nodes from this one.
286 self.reachable_symbols.insert(search_item);
290 ast_map::NodeItem(item) => {
292 ast::ItemFn(_, _, _, _, ref search_block) => {
293 if item_might_be_inlined(&*item) {
294 visit::walk_block(self, &**search_block, ())
298 // Statics with insignificant addresses are not reachable
299 // because they're inlined specially into all other crates.
300 ast::ItemStatic(_, mutbl, ref init) => {
301 if !ast_util::static_has_significant_address(
303 item.attrs.as_slice()) {
304 self.reachable_symbols.remove(&search_item);
306 visit::walk_expr(self, &**init, ());
309 // These are normal, nothing reachable about these
310 // inherently and their children are already in the
311 // worklist, as determined by the privacy pass
313 ast::ItemMod(..) | ast::ItemForeignMod(..) |
314 ast::ItemImpl(..) | ast::ItemTrait(..) |
315 ast::ItemStruct(..) | ast::ItemEnum(..) => {}
318 self.tcx.sess.span_bug(item.span,
319 "found non-function item \
324 ast_map::NodeTraitItem(trait_method) => {
325 match *trait_method {
326 ast::RequiredMethod(..) => {
327 // Keep going, nothing to get exported
329 ast::ProvidedMethod(ref method) => {
330 visit::walk_block(self, &*method.pe_body(), ())
334 ast_map::NodeImplItem(impl_item) => {
336 ast::MethodImplItem(method) => {
337 let did = self.tcx.map.get_parent_did(search_item);
338 if method_might_be_inlined(self.tcx, &*method, did) {
339 visit::walk_block(self, &*method.pe_body(), ())
344 // Nothing to recurse on for these
345 ast_map::NodeForeignItem(_) |
346 ast_map::NodeVariant(_) |
347 ast_map::NodeStructCtor(_) => {}
351 .bug(format!("found unexpected thingy in worklist: {}",
354 .node_to_string(search_item)).as_slice())
359 // Step 3: Mark all destructors as reachable.
361 // FIXME(pcwalton): This is a conservative overapproximation, but fixing
362 // this properly would result in the necessity of computing *type*
363 // reachability, which might result in a compile time loss.
364 fn mark_destructors_reachable(&mut self) {
365 for (_, destructor_def_id) in self.tcx.destructor_for_type.borrow().iter() {
366 if destructor_def_id.krate == ast::LOCAL_CRATE {
367 self.reachable_symbols.insert(destructor_def_id.node);
373 pub fn find_reachable(tcx: &ty::ctxt,
374 exported_items: &privacy::ExportedItems)
376 let mut reachable_context = ReachableContext::new(tcx);
378 // Step 1: Seed the worklist with all nodes which were found to be public as
379 // a result of the privacy pass along with all local lang items. If
380 // other crates link to us, they're going to expect to be able to
381 // use the lang items, so we need to be sure to mark them as
383 for id in exported_items.iter() {
384 reachable_context.worklist.push(*id);
386 for (_, item) in tcx.lang_items.items() {
388 Some(did) if is_local(did) => {
389 reachable_context.worklist.push(did.node);
395 // Step 2: Mark all symbols that the symbols on the worklist touch.
396 reachable_context.propagate();
398 // Step 3: Mark all destructors as reachable.
399 reachable_context.mark_destructors_reachable();
401 // Return the set of reachable symbols.
402 reachable_context.reachable_symbols