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