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 rustc_data_structures::fx::FxHashSet;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::intravisit::{self, Visitor};
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;
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() {
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)
39 fn method_might_be_inlined(
41 impl_item: &hir::ImplItem<'_>,
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) {
49 if let hir::ImplItemKind::Fn(method_sig, _) = &impl_item.kind {
50 if method_sig.header.is_const() {
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"),
60 // Information needed while computing reachability.
61 struct ReachableContext<'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
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;
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))
89 hir::ExprKind::MethodCall(..) => self
91 .type_dependent_def(expr.hir_id)
92 .map(|(kind, def_id)| Res::Def(kind, def_id)),
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);
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);
108 // If this wasn't a static, then the destination is
111 self.reachable_symbols.insert(def_id);
117 intravisit::walk_expr(self, expr)
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).
126 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
127 self.maybe_typeck_results
128 .expect("`ReachableContext::typeck_results` called outside of body")
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 {
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))
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,
151 Some(Node::ImplItem(impl_item)) => match impl_item.kind {
152 hir::ImplItemKind::Const(..) => true,
153 hir::ImplItemKind::Fn(..) => {
154 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
155 let impl_did = self.tcx.hir().get_parent_item(hir_id);
156 method_might_be_inlined(self.tcx, impl_item, impl_did)
158 hir::ImplItemKind::TyAlias(_) => false,
161 None => false, // This will happen for default methods.
165 // Step 2: Mark all symbols that the symbols on the worklist touch.
166 fn propagate(&mut self) {
167 let mut scanned = FxHashSet::default();
168 while let Some(search_item) = self.worklist.pop() {
169 if !scanned.insert(search_item) {
173 if let Some(ref item) = self.tcx.hir().find_by_def_id(search_item) {
174 self.propagate_node(item, search_item);
179 fn propagate_node(&mut self, node: &Node<'tcx>, search_item: LocalDefId) {
180 if !self.any_library {
181 // If we are building an executable, only explicitly extern
182 // types need to be exported.
184 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })
185 | Node::ImplItem(hir::ImplItem {
186 kind: hir::ImplItemKind::Fn(sig, ..), ..
189 sig.header.abi != Abi::Rust
193 let codegen_attrs = if self.tcx.def_kind(search_item).has_codegen_attrs() {
194 self.tcx.codegen_fn_attrs(search_item)
196 CodegenFnAttrs::EMPTY
198 let is_extern = codegen_attrs.contains_extern_indicator();
200 codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
201 if reachable || is_extern || std_internal {
202 self.reachable_symbols.insert(search_item);
205 // If we are building a library, then reachable symbols will
206 // continue to participate in linkage after this product is
207 // produced. In this case, we traverse the ast node, recursing on
208 // all reachable nodes from this one.
209 self.reachable_symbols.insert(search_item);
213 Node::Item(item) => {
215 hir::ItemKind::Fn(.., body) => {
216 if item_might_be_inlined(
219 self.tcx.codegen_fn_attrs(item.def_id),
221 self.visit_nested_body(body);
225 // Reachable constants will be inlined into other crates
226 // unconditionally, so we need to make sure that their
227 // contents are also reachable.
228 hir::ItemKind::Const(_, init) | hir::ItemKind::Static(_, _, init) => {
229 self.visit_nested_body(init);
232 // These are normal, nothing reachable about these
233 // inherently and their children are already in the
234 // worklist, as determined by the privacy pass
235 hir::ItemKind::ExternCrate(_)
236 | hir::ItemKind::Use(..)
237 | hir::ItemKind::OpaqueTy(..)
238 | hir::ItemKind::TyAlias(..)
239 | hir::ItemKind::Macro(..)
240 | hir::ItemKind::Mod(..)
241 | hir::ItemKind::ForeignMod { .. }
242 | hir::ItemKind::Impl { .. }
243 | hir::ItemKind::Trait(..)
244 | hir::ItemKind::TraitAlias(..)
245 | hir::ItemKind::Struct(..)
246 | hir::ItemKind::Enum(..)
247 | hir::ItemKind::Union(..)
248 | hir::ItemKind::GlobalAsm(..) => {}
251 Node::TraitItem(trait_method) => {
252 match trait_method.kind {
253 hir::TraitItemKind::Const(_, None)
254 | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => {
255 // Keep going, nothing to get exported
257 hir::TraitItemKind::Const(_, Some(body_id))
258 | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
259 self.visit_nested_body(body_id);
261 hir::TraitItemKind::Type(..) => {}
264 Node::ImplItem(impl_item) => match impl_item.kind {
265 hir::ImplItemKind::Const(_, body) => {
266 self.visit_nested_body(body);
268 hir::ImplItemKind::Fn(_, body) => {
269 let impl_def_id = self.tcx.local_parent(search_item);
270 if method_might_be_inlined(self.tcx, impl_item, impl_def_id) {
271 self.visit_nested_body(body)
274 hir::ImplItemKind::TyAlias(_) => {}
276 Node::Expr(&hir::Expr {
277 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
280 self.visit_nested_body(body);
282 // Nothing to recurse on for these
288 | Node::Crate(_) => {}
291 "found unexpected node kind in worklist: {} ({:?})",
294 .node_to_string(self.tcx.hir().local_def_id_to_hir_id(search_item)),
305 worklist: &mut Vec<LocalDefId>,
306 access_levels: &privacy::AccessLevels,
308 if has_custom_linkage(tcx, id.def_id) {
309 worklist.push(id.def_id);
312 if !matches!(tcx.def_kind(id.def_id), DefKind::Impl) {
316 // We need only trait impls here, not inherent impls, and only non-exported ones
317 let item = tcx.hir().item(id);
318 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), ref items, .. }) =
321 if !access_levels.is_reachable(item.def_id) {
322 worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id));
324 let Res::Def(DefKind::Trait, trait_def_id) = trait_ref.path.res else {
328 if !trait_def_id.is_local() {
333 tcx.provided_trait_methods(trait_def_id).map(|assoc| assoc.def_id.expect_local()),
339 fn has_custom_linkage<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> bool {
340 // Anything which has custom linkage gets thrown on the worklist no
341 // matter where it is in the crate, along with "special std symbols"
342 // which are currently akin to allocator symbols.
343 if !tcx.def_kind(def_id).has_codegen_attrs() {
346 let codegen_attrs = tcx.codegen_fn_attrs(def_id);
347 codegen_attrs.contains_extern_indicator()
348 || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
349 // FIXME(nbdd0121): `#[used]` are marked as reachable here so it's picked up by
350 // `linked_symbols` in cg_ssa. They won't be exported in binary or cdylib due to their
351 // `SymbolExportLevel::Rust` export level but may end up being exported in dylibs.
352 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED)
353 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
356 fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> FxHashSet<LocalDefId> {
357 let access_levels = &tcx.privacy_access_levels(());
360 tcx.sess.crate_types().iter().any(|ty| {
361 *ty == CrateType::Rlib || *ty == CrateType::Dylib || *ty == CrateType::ProcMacro
363 let mut reachable_context = ReachableContext {
365 maybe_typeck_results: None,
366 reachable_symbols: Default::default(),
367 worklist: Vec::new(),
371 // Step 1: Seed the worklist with all nodes which were found to be public as
372 // a result of the privacy pass along with all local lang items and impl items.
373 // If other crates link to us, they're going to expect to be able to
374 // use the lang items, so we need to be sure to mark them as
376 reachable_context.worklist.extend(access_levels.map.keys());
377 for item in tcx.lang_items().items().iter() {
378 if let Some(def_id) = *item {
379 if let Some(def_id) = def_id.as_local() {
380 reachable_context.worklist.push(def_id);
385 // Some methods from non-exported (completely private) trait impls still have to be
386 // reachable if they are called from inlinable code. Generally, it's not known until
387 // monomorphization if a specific trait impl item can be reachable or not. So, we
388 // conservatively mark all of them as reachable.
389 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
390 // items of non-exported traits (or maybe all local traits?) unless their respective
391 // trait items are used from inlinable code through method call syntax or UFCS, or their
392 // trait is a lang item.
393 let crate_items = tcx.hir_crate_items(());
395 for id in crate_items.items() {
396 check_item(tcx, id, &mut reachable_context.worklist, access_levels);
399 for id in crate_items.impl_items() {
400 if has_custom_linkage(tcx, id.def_id) {
401 reachable_context.worklist.push(id.def_id);
406 // Step 2: Mark all symbols that the symbols on the worklist touch.
407 reachable_context.propagate();
409 debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
411 // Return the set of reachable symbols.
412 reachable_context.reachable_symbols
415 pub fn provide(providers: &mut Providers) {
416 *providers = Providers { reachable_set, ..*providers };