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
8 use crate::hir::{CodegenFnAttrs, CodegenFnAttrFlags};
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};
19 use rustc_target::spec::abi::Abi;
20 use rustc_macros::HashStable;
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;
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>, item: &hir::Item, attrs: CodegenFnAttrs) -> bool {
31 if attrs.requests_inline() {
36 hir::ItemKind::Impl(..) |
37 hir::ItemKind::Fn(..) => {
38 let generics = tcx.generics_of(tcx.hir().local_def_id_from_hir_id(item.hir_id));
39 generics.requires_monomorphization(tcx)
45 fn method_might_be_inlined<'tcx>(
47 impl_item: &hir::ImplItem,
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) {
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),
60 span_bug!(impl_item.span, "impl did is not an item")
63 span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
67 // Information needed while computing reachability.
68 struct ReachableContext<'a, '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
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
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;
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))
99 hir::ExprKind::MethodCall(..) => {
100 self.tables.type_dependent_def(expr.hir_id)
101 .map(|(kind, def_id)| Res::Def(kind, def_id))
107 Some(Res::Local(hir_id)) => {
108 self.reachable_symbols.insert(hir_id);
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))
114 if self.def_id_represents_local_inlined_item(def_id) {
115 self.worklist.push(hir_id);
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);
125 // If this wasn't a static, then the destination is
128 self.reachable_symbols.insert(hir_id);
137 intravisit::walk_expr(self, expr)
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; }
150 match self.tcx.hir().find_by_hir_id(hir_id) {
151 Some(Node::Item(item)) => {
153 hir::ItemKind::Fn(..) =>
154 item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id)),
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,
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() {
175 let impl_did = self.tcx
177 .get_parent_did(hir_id);
178 // Check the impl. If the generics on the self
179 // type of the impl require inlining, this method
181 let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did).unwrap();
182 match self.tcx.hir().expect_item(impl_hir_id).node {
183 hir::ItemKind::Impl(..) => {
184 let generics = self.tcx.generics_of(impl_did);
185 generics.requires_monomorphization(self.tcx)
191 hir::ImplItemKind::Existential(..) |
192 hir::ImplItemKind::Type(_) => false,
196 None => false // This will happen for default methods.
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) {
208 if let Some(ref item) = self.tcx.hir().find_by_hir_id(search_item) {
209 self.propagate_node(item, search_item);
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
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);
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);
243 Node::Item(item) => {
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,
249 self.tcx.codegen_fn_attrs(def_id)) {
250 self.visit_nested_body(body);
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);
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(..) => {}
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
286 hir::TraitItemKind::Const(_, Some(body_id)) |
287 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
288 self.visit_nested_body(body_id);
290 hir::TraitItemKind::Type(..) => {}
293 Node::ImplItem(impl_item) => {
294 match impl_item.node {
295 hir::ImplItemKind::Const(_, body) => {
296 self.visit_nested_body(body);
298 hir::ImplItemKind::Method(_, body) => {
299 let did = self.tcx.hir().get_parent_did(search_item);
300 if method_might_be_inlined(self.tcx, impl_item, did) {
301 self.visit_nested_body(body)
304 hir::ImplItemKind::Existential(..) |
305 hir::ImplItemKind::Type(_) => {}
308 Node::Expr(&hir::Expr { node: hir::ExprKind::Closure(.., body, _, _), .. }) => {
309 self.visit_nested_body(body);
311 // Nothing to recurse on for these
312 Node::ForeignItem(_) |
317 Node::MacroDef(_) => {}
320 "found unexpected node kind in worklist: {} ({:?})",
321 self.tcx.hir().node_to_string(search_item),
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> {
339 access_levels: &'a privacy::AccessLevels,
340 worklist: &'a mut Vec<hir::HirId>,
343 impl<'a, 'tcx> 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);
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));
360 let trait_def_id = match trait_ref.path.res {
361 Res::Def(DefKind::Trait, def_id) => def_id,
365 if !trait_def_id.is_local() {
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
374 .as_local_hir_id(default_method.def_id)
376 self.worklist.push(hir_id);
382 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
384 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
385 // processed in visit_item above
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>);
394 fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, crate_num: CrateNum) -> ReachableSet {
395 debug_assert!(crate_num == LOCAL_CRATE);
397 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
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
403 let mut reachable_context = ReachableContext {
405 tables: &ty::TypeckTables::empty(None),
406 reachable_symbols: Default::default(),
407 worklist: Vec::new(),
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
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);
426 let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
429 worklist: &mut reachable_context.worklist,
431 tcx.hir().krate().visit_all_item_likes(&mut collect_private_impl_items);
434 // Step 2: Mark all symbols that the symbols on the worklist touch.
435 reachable_context.propagate();
437 debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
439 // Return the set of reachable symbols.
440 ReachableSet(Lrc::new(reachable_context.reachable_symbols))
443 pub fn provide(providers: &mut Providers<'_>) {
444 *providers = Providers {