]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/reachable.rs
Fix missed same-sized member clash in ClashingExternDeclarations.
[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_results: Option<&'tcx ty::TypeckResults<'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_results =
85             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
86         let body = self.tcx.hir().body(body);
87         self.visit_body(body);
88         self.maybe_typeck_results = old_maybe_typeck_results;
89     }
90
91     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
92         let res = match expr.kind {
93             hir::ExprKind::Path(ref qpath) => {
94                 Some(self.typeck_results().qpath_res(qpath, expr.hir_id))
95             }
96             hir::ExprKind::MethodCall(..) => self
97                 .typeck_results()
98                 .type_dependent_def(expr.hir_id)
99                 .map(|(kind, def_id)| Res::Def(kind, def_id)),
100             _ => None,
101         };
102
103         match res {
104             Some(Res::Local(hir_id)) => {
105                 self.reachable_symbols.insert(hir_id);
106             }
107             Some(res) => {
108                 if let Some((hir_id, def_id)) = res.opt_def_id().and_then(|def_id| {
109                     def_id.as_local().map(|def_id| (self.tcx.hir().as_local_hir_id(def_id), def_id))
110                 }) {
111                     if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
112                         self.worklist.push(hir_id);
113                     } else {
114                         match res {
115                             // If this path leads to a constant, then we need to
116                             // recurse into the constant to continue finding
117                             // items that are reachable.
118                             Res::Def(DefKind::Const | DefKind::AssocConst, _) => {
119                                 self.worklist.push(hir_id);
120                             }
121
122                             // If this wasn't a static, then the destination is
123                             // surely reachable.
124                             _ => {
125                                 self.reachable_symbols.insert(hir_id);
126                             }
127                         }
128                     }
129                 }
130             }
131             _ => {}
132         }
133
134         intravisit::walk_expr(self, expr)
135     }
136 }
137
138 impl<'tcx> ReachableContext<'tcx> {
139     /// Gets the type-checking results for the current body.
140     /// As this will ICE if called outside bodies, only call when working with
141     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
142     #[track_caller]
143     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
144         self.maybe_typeck_results
145             .expect("`ReachableContext::typeck_results` called outside of body")
146     }
147
148     // Returns true if the given def ID represents a local item that is
149     // eligible for inlining and false otherwise.
150     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
151         let hir_id = match def_id.as_local() {
152             Some(def_id) => self.tcx.hir().as_local_hir_id(def_id),
153             None => {
154                 return false;
155             }
156         };
157
158         match self.tcx.hir().find(hir_id) {
159             Some(Node::Item(item)) => match item.kind {
160                 hir::ItemKind::Fn(..) => {
161                     item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
162                 }
163                 _ => false,
164             },
165             Some(Node::TraitItem(trait_method)) => match trait_method.kind {
166                 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
167                 hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true,
168                 hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
169                 | hir::TraitItemKind::Type(..) => false,
170             },
171             Some(Node::ImplItem(impl_item)) => {
172                 match impl_item.kind {
173                     hir::ImplItemKind::Const(..) => true,
174                     hir::ImplItemKind::Fn(..) => {
175                         let attrs = self.tcx.codegen_fn_attrs(def_id);
176                         let generics = self.tcx.generics_of(def_id);
177                         if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
178                             true
179                         } else {
180                             let impl_did = self.tcx.hir().get_parent_did(hir_id);
181                             // Check the impl. If the generics on the self
182                             // type of the impl require inlining, this method
183                             // does too.
184                             let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did);
185                             match self.tcx.hir().expect_item(impl_hir_id).kind {
186                                 hir::ItemKind::Impl { .. } => {
187                                     let generics = self.tcx.generics_of(impl_did);
188                                     generics.requires_monomorphization(self.tcx)
189                                 }
190                                 _ => false,
191                             }
192                         }
193                     }
194                     hir::ImplItemKind::TyAlias(_) => false,
195                 }
196             }
197             Some(_) => false,
198             None => false, // This will happen for default methods.
199         }
200     }
201
202     // Step 2: Mark all symbols that the symbols on the worklist touch.
203     fn propagate(&mut self) {
204         let mut scanned = FxHashSet::default();
205         while let Some(search_item) = self.worklist.pop() {
206             if !scanned.insert(search_item) {
207                 continue;
208             }
209
210             if let Some(ref item) = self.tcx.hir().find(search_item) {
211                 self.propagate_node(item, search_item);
212             }
213         }
214     }
215
216     fn propagate_node(&mut self, node: &Node<'tcx>, search_item: hir::HirId) {
217         if !self.any_library {
218             // If we are building an executable, only explicitly extern
219             // types need to be exported.
220             if let Node::Item(item) = *node {
221                 let reachable = if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
222                     sig.header.abi != Abi::Rust
223                 } else {
224                     false
225                 };
226                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
227                 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
228                 let is_extern = codegen_attrs.contains_extern_indicator();
229                 let std_internal =
230                     codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
231                 if reachable || is_extern || std_internal {
232                     self.reachable_symbols.insert(search_item);
233                 }
234             }
235         } else {
236             // If we are building a library, then reachable symbols will
237             // continue to participate in linkage after this product is
238             // produced. In this case, we traverse the ast node, recursing on
239             // all reachable nodes from this one.
240             self.reachable_symbols.insert(search_item);
241         }
242
243         match *node {
244             Node::Item(item) => {
245                 match item.kind {
246                     hir::ItemKind::Fn(.., body) => {
247                         let def_id = self.tcx.hir().local_def_id(item.hir_id);
248                         if item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
249                         {
250                             self.visit_nested_body(body);
251                         }
252                     }
253
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);
259                     }
260
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::OpaqueTy(..)
267                     | hir::ItemKind::TyAlias(..)
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(..) => {}
278                 }
279             }
280             Node::TraitItem(trait_method) => {
281                 match trait_method.kind {
282                     hir::TraitItemKind::Const(_, None)
283                     | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => {
284                         // Keep going, nothing to get exported
285                     }
286                     hir::TraitItemKind::Const(_, Some(body_id))
287                     | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
288                         self.visit_nested_body(body_id);
289                     }
290                     hir::TraitItemKind::Type(..) => {}
291                 }
292             }
293             Node::ImplItem(impl_item) => match impl_item.kind {
294                 hir::ImplItemKind::Const(_, body) => {
295                     self.visit_nested_body(body);
296                 }
297                 hir::ImplItemKind::Fn(_, body) => {
298                     let did = self.tcx.hir().get_parent_did(search_item);
299                     if method_might_be_inlined(self.tcx, impl_item, did) {
300                         self.visit_nested_body(body)
301                     }
302                 }
303                 hir::ImplItemKind::TyAlias(_) => {}
304             },
305             Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
306                 self.visit_nested_body(body);
307             }
308             // Nothing to recurse on for these
309             Node::ForeignItem(_)
310             | Node::Variant(_)
311             | Node::Ctor(..)
312             | Node::Field(_)
313             | Node::Ty(_)
314             | Node::MacroDef(_) => {}
315             _ => {
316                 bug!(
317                     "found unexpected node kind in worklist: {} ({:?})",
318                     self.tcx.hir().node_to_string(search_item),
319                     node,
320                 );
321             }
322         }
323     }
324 }
325
326 // Some methods from non-exported (completely private) trait impls still have to be
327 // reachable if they are called from inlinable code. Generally, it's not known until
328 // monomorphization if a specific trait impl item can be reachable or not. So, we
329 // conservatively mark all of them as reachable.
330 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
331 // items of non-exported traits (or maybe all local traits?) unless their respective
332 // trait items are used from inlinable code through method call syntax or UFCS, or their
333 // trait is a lang item.
334 struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
335     tcx: TyCtxt<'tcx>,
336     access_levels: &'a privacy::AccessLevels,
337     worklist: &'a mut Vec<hir::HirId>,
338 }
339
340 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
341     fn visit_item(&mut self, item: &hir::Item<'_>) {
342         // Anything which has custom linkage gets thrown on the worklist no
343         // matter where it is in the crate, along with "special std symbols"
344         // which are currently akin to allocator symbols.
345         let def_id = self.tcx.hir().local_def_id(item.hir_id);
346         let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
347         if codegen_attrs.contains_extern_indicator()
348             || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
349         {
350             self.worklist.push(item.hir_id);
351         }
352
353         // We need only trait impls here, not inherent impls, and only non-exported ones
354         if let hir::ItemKind::Impl { of_trait: Some(ref trait_ref), ref items, .. } = item.kind {
355             if !self.access_levels.is_reachable(item.hir_id) {
356                 self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.hir_id));
357
358                 let trait_def_id = match trait_ref.path.res {
359                     Res::Def(DefKind::Trait, def_id) => def_id,
360                     _ => unreachable!(),
361                 };
362
363                 if !trait_def_id.is_local() {
364                     return;
365                 }
366
367                 // FIXME(#53488) remove `let`
368                 let tcx = self.tcx;
369                 self.worklist.extend(
370                     tcx.provided_trait_methods(trait_def_id)
371                         .map(|assoc| tcx.hir().as_local_hir_id(assoc.def_id.expect_local())),
372                 );
373             }
374         }
375     }
376
377     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
378
379     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {
380         // processed in visit_item above
381     }
382 }
383
384 fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, crate_num: CrateNum) -> &'tcx HirIdSet {
385     debug_assert!(crate_num == LOCAL_CRATE);
386
387     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
388
389     let any_library =
390         tcx.sess.crate_types().iter().any(|ty| {
391             *ty == CrateType::Rlib || *ty == CrateType::Dylib || *ty == CrateType::ProcMacro
392         });
393     let mut reachable_context = ReachableContext {
394         tcx,
395         maybe_typeck_results: None,
396         reachable_symbols: Default::default(),
397         worklist: Vec::new(),
398         any_library,
399     };
400
401     // Step 1: Seed the worklist with all nodes which were found to be public as
402     //         a result of the privacy pass along with all local lang items and impl items.
403     //         If other crates link to us, they're going to expect to be able to
404     //         use the lang items, so we need to be sure to mark them as
405     //         exported.
406     reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
407     for item in tcx.lang_items().items().iter() {
408         if let Some(did) = *item {
409             if let Some(hir_id) = did.as_local().map(|did| tcx.hir().as_local_hir_id(did)) {
410                 reachable_context.worklist.push(hir_id);
411             }
412         }
413     }
414     {
415         let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
416             tcx,
417             access_levels,
418             worklist: &mut reachable_context.worklist,
419         };
420         tcx.hir().krate().visit_all_item_likes(&mut collect_private_impl_items);
421     }
422
423     // Step 2: Mark all symbols that the symbols on the worklist touch.
424     reachable_context.propagate();
425
426     debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
427
428     // Return the set of reachable symbols.
429     tcx.arena.alloc(reachable_context.reachable_symbols)
430 }
431
432 pub fn provide(providers: &mut Providers) {
433     *providers = Providers { reachable_set, ..*providers };
434 }