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