Skip to main content

rustc_passes/
dead.rs

1// This implements the dead-code warning pass.
2// All reachable symbols are live, code called from live code is live, code with certain lint
3// expectations such as `#[expect(unused)]` and `#[expect(dead_code)]` is live, and everything else
4// is dead.
5
6use std::mem;
7use std::ops::ControlFlow;
8use std::sync::atomic::Ordering;
9
10use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
11use rustc_abi::FieldIdx;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
13use rustc_errors::{ErrorGuaranteed, MultiSpan};
14use rustc_hir::def::{CtorOf, DefKind, Res};
15use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
16use rustc_hir::intravisit::{self, Visitor};
17use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath, find_attr};
18use rustc_lint_defs::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
19use rustc_lint_defs::{self as lint, Lint, StableLintExpectationId};
20use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
21use rustc_middle::middle::dead_code::{DeadCodeLivenessSnapshot, DeadCodeLivenessSummary};
22use rustc_middle::middle::privacy::Level;
23use rustc_middle::query::Providers;
24use rustc_middle::ty::{self, AssocTag, TyCtxt};
25use rustc_middle::{bug, span_bug};
26use rustc_span::{Symbol, kw};
27use rustc_structures::CrateType;
28
29use crate::diagnostics::{
30    ChangeFields, DeadCodePubInBinaryNote, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo,
31    UselessAssignment,
32};
33
34/// Any local definition that may call something in its body block should be explored. For example,
35/// if it's a live function, then we should explore its block to check for codes that may need to
36/// be marked as live.
37fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
38    match tcx.def_kind(def_id) {
39        DefKind::Mod
40        | DefKind::Struct
41        | DefKind::Union
42        | DefKind::Enum
43        | DefKind::Variant
44        | DefKind::Trait
45        | DefKind::TyAlias
46        | DefKind::ForeignTy
47        | DefKind::TraitAlias
48        | DefKind::AssocTy
49        | DefKind::Fn
50        | DefKind::Const { .. }
51        | DefKind::Static { .. }
52        | DefKind::AssocFn
53        | DefKind::AssocConst { .. }
54        | DefKind::Macro(_)
55        | DefKind::GlobalAsm
56        | DefKind::Impl { .. }
57        | DefKind::OpaqueTy
58        | DefKind::AnonConst
59        | DefKind::ExternCrate
60        | DefKind::Use
61        | DefKind::Ctor(..)
62        | DefKind::ForeignMod => true,
63
64        DefKind::TyParam
65        | DefKind::ConstParam
66        | DefKind::Field
67        | DefKind::LifetimeParam
68        | DefKind::Closure
69        | DefKind::SyntheticCoroutineBody
70        | DefKind::TestBinderConstraints => false,
71    }
72}
73
74/// Determine if a work from the worklist is coming from a `#[allow]`
75/// or a `#[expect]` of `dead_code`
76#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComesFromAllowExpect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ComesFromAllowExpect::Yes => "Yes",
                ComesFromAllowExpect::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ComesFromAllowExpect { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ComesFromAllowExpect { }
#[automatically_derived]
impl ::core::clone::Clone for ComesFromAllowExpect {
    #[inline]
    fn clone(&self) -> ComesFromAllowExpect { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for ComesFromAllowExpect {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ComesFromAllowExpect { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ComesFromAllowExpect {
    #[inline]
    fn eq(&self, other: &ComesFromAllowExpect) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for ComesFromAllowExpect {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
77enum ComesFromAllowExpect {
78    Yes,
79    No,
80}
81
82/// Carries both the propagated `allow/expect` context and the current item's
83/// own `allow/expect` status.
84///
85/// For example:
86///
87/// ```rust
88/// #[expect(dead_code)]
89/// fn root() { middle() }
90///
91/// fn middle() { leaf() }
92///
93/// #[expect(dead_code)]
94/// fn leaf() {}
95/// ```
96///
97/// The seed for `root` starts as `propagated = Yes, own = Yes`.
98///
99/// When `root` reaches `middle`, the propagated context stays `Yes`, but
100/// `middle` itself does not have `#[allow(dead_code)]` or `#[expect(dead_code)]`,
101/// so its work item becomes `propagated = Yes, own = No`.
102///
103/// When `middle` reaches `leaf`, that same propagated `Yes` context is preserved,
104/// and since `leaf` itself has `#[expect(dead_code)]`, its work item becomes
105/// `propagated = Yes, own = Yes`.
106///
107/// In general, `propagated` controls whether descendants are still explored
108/// under an `allow/expect` context, while `own` controls whether the current
109/// item itself should be excluded from `live_symbols`.
110#[derive(#[automatically_derived]
impl ::core::fmt::Debug for WorkItem {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "WorkItem",
            "id", &self.id, "propagated", &self.propagated, "own", &&self.own)
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for WorkItem { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for WorkItem { }
#[automatically_derived]
impl ::core::clone::Clone for WorkItem {
    #[inline]
    fn clone(&self) -> WorkItem {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<ComesFromAllowExpect>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for WorkItem {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
        let _: ::core::cmp::AssertParamIsEq<ComesFromAllowExpect>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for WorkItem { }
#[automatically_derived]
impl ::core::cmp::PartialEq for WorkItem {
    #[inline]
    fn eq(&self, other: &WorkItem) -> bool {
        self.id == other.id && self.propagated == other.propagated &&
            self.own == other.own
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for WorkItem {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.id, state);
        ::core::hash::Hash::hash(&self.propagated, state);
        ::core::hash::Hash::hash(&self.own, state)
    }
}Hash)]
111struct WorkItem {
112    id: LocalDefId,
113    propagated: ComesFromAllowExpect,
114    own: ComesFromAllowExpect,
115}
116
117enum ImplItemCheckResult {
118    Live(ComesFromAllowExpect),
119    Dead { require: LocalDefId },
120}
121
122struct MarkSymbolVisitor<'tcx> {
123    worklist: Vec<WorkItem>,
124    tcx: TyCtxt<'tcx>,
125    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
126    scanned: FxHashSet<(LocalDefId, ComesFromAllowExpect)>,
127    live_symbols: LocalDefIdSet,
128    repr_unconditionally_treats_fields_as_live: bool,
129    repr_has_repr_simd_or_scalable: bool,
130    in_pat: bool,
131    ignore_variant_stack: Vec<DefId>,
132    // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
133    // and the span of their respective impl (i.e., part of the derive
134    // macro)
135    ignored_derived_traits: LocalDefIdMap<FxIndexSet<DefId>>,
136    propagated_comes_from_allow_expect: ComesFromAllowExpect,
137    unsolved_items: Vec<LocalDefId>,
138}
139
140impl<'tcx> MarkSymbolVisitor<'tcx> {
141    /// Gets the type-checking results for the current body.
142    /// As this will ICE if called outside bodies, only call when working with
143    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
144    #[track_caller]
145    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
146        self.maybe_typeck_results
147            .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
148    }
149
150    /// Returns whether `def_id` itself should be treated as coming from
151    /// `#[allow(dead_code)]` or `#[expect(dead_code)]` in the current
152    /// propagated work-item context.
153    fn own_comes_from_allow_expect(&self, def_id: LocalDefId) -> ComesFromAllowExpect {
154        if self.propagated_comes_from_allow_expect == ComesFromAllowExpect::Yes
155            && let Some(ComesFromAllowExpect::Yes) =
156                has_allow_dead_code_or_lang_attr(self.tcx, def_id)
157        {
158            ComesFromAllowExpect::Yes
159        } else {
160            ComesFromAllowExpect::No
161        }
162    }
163
164    fn check_def_id(&mut self, def_id: DefId) {
165        if let Some(def_id) = def_id.as_local() {
166            let own_comes_from_allow_expect = self.own_comes_from_allow_expect(def_id);
167
168            if should_explore(self.tcx, def_id) {
169                self.worklist.push(WorkItem {
170                    id: def_id,
171                    propagated: self.propagated_comes_from_allow_expect,
172                    own: own_comes_from_allow_expect,
173                });
174            }
175
176            if own_comes_from_allow_expect == ComesFromAllowExpect::No {
177                self.live_symbols.insert(def_id);
178            }
179        }
180    }
181
182    fn insert_def_id(&mut self, def_id: DefId) {
183        if let Some(def_id) = def_id.as_local() {
184            if true {
    if !!should_explore(self.tcx, def_id) {
        ::core::panicking::panic("assertion failed: !should_explore(self.tcx, def_id)")
    };
};debug_assert!(!should_explore(self.tcx, def_id));
185
186            if self.own_comes_from_allow_expect(def_id) == ComesFromAllowExpect::No {
187                self.live_symbols.insert(def_id);
188            }
189        }
190    }
191
192    fn handle_res(&mut self, res: Res) {
193        match res {
194            Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
195            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
196                // Using a variant in patterns should not make the variant live,
197                // since we can just remove the match arm that matches the pattern
198                if self.in_pat {
199                    return;
200                }
201                let variant_id = self.tcx.parent(ctor_def_id);
202                let enum_id = self.tcx.parent(variant_id);
203                self.check_def_id(enum_id);
204                if !self.ignore_variant_stack.contains(&ctor_def_id) {
205                    self.check_def_id(variant_id);
206                }
207            }
208            Res::Def(DefKind::Variant, variant_id) => {
209                // Using a variant in patterns should not make the variant live,
210                // since we can just remove the match arm that matches the pattern
211                if self.in_pat {
212                    return;
213                }
214                let enum_id = self.tcx.parent(variant_id);
215                self.check_def_id(enum_id);
216                if !self.ignore_variant_stack.contains(&variant_id) {
217                    self.check_def_id(variant_id);
218                }
219            }
220            Res::Def(_, def_id) => self.check_def_id(def_id),
221            Res::SelfTyParam { trait_: t } => self.check_def_id(t),
222            Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
223            Res::ToolMod | Res::NonMacroAttr(..) | Res::OpenMod(..) | Res::Err => {}
224        }
225    }
226
227    fn lookup_and_handle_method(&mut self, id: hir::HirId) {
228        if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
229            self.check_def_id(def_id);
230        } else {
231            if !self.typeck_results().tainted_by_errors.is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
    }
};assert!(
232                self.typeck_results().tainted_by_errors.is_some(),
233                "no type-dependent def for method"
234            );
235        }
236    }
237
238    fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
239        match self.typeck_results().expr_ty_adjusted(lhs).kind() {
240            ty::Adt(def, _) => {
241                let index = self.typeck_results().field_index(hir_id);
242                self.insert_def_id(def.non_enum_variant().fields[index].did);
243            }
244            ty::Tuple(..) => {}
245            ty::Error(_) => {}
246            kind => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
    format_args!("named field access on non-ADT: {0:?}", kind))span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
247        }
248    }
249
250    fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
251        if self
252            .typeck_results()
253            .expr_adjustments(expr)
254            .iter()
255            .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Deref(_) => true,
    _ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
256        {
257            let _ = self.visit_expr(expr);
258        } else if let hir::ExprKind::Field(base, ..) = expr.kind {
259            // Ignore write to field
260            self.handle_assign(base);
261        } else {
262            let _ = self.visit_expr(expr);
263        }
264    }
265
266    fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
267        fn check_for_self_assign_helper<'tcx>(
268            typeck_results: &'tcx ty::TypeckResults<'tcx>,
269            lhs: &'tcx hir::Expr<'tcx>,
270            rhs: &'tcx hir::Expr<'tcx>,
271        ) -> bool {
272            match (&lhs.kind, &rhs.kind) {
273                (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
274                    if let (Res::Local(id_l), Res::Local(id_r)) = (
275                        typeck_results.qpath_res(qpath_l, lhs.hir_id),
276                        typeck_results.qpath_res(qpath_r, rhs.hir_id),
277                    ) {
278                        if id_l == id_r {
279                            return true;
280                        }
281                    }
282                    return false;
283                }
284                (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
285                    if ident_l == ident_r {
286                        return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
287                    }
288                    return false;
289                }
290                _ => {
291                    return false;
292                }
293            }
294        }
295
296        if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
297            && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
298            && !assign.span.from_expansion()
299        {
300            let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Field(..) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
301            self.tcx.emit_node_span_lint(
302                DEAD_CODE,
303                assign.hir_id,
304                assign.span,
305                UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
306            )
307        }
308    }
309
310    fn handle_field_pattern_match(
311        &mut self,
312        lhs: &hir::Pat<'_>,
313        res: Res,
314        pats: &[hir::PatField<'_>],
315    ) {
316        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
317            ty::Adt(adt, _) => {
318                // Marks the ADT live if its variant appears as the pattern,
319                // considering cases when we have `let T(x) = foo()` and `fn foo<T>() -> T;`,
320                // we will lose the liveness info of `T` cause we cannot mark it live when visiting `foo`.
321                // Related issue: https://github.com/rust-lang/rust/issues/120770
322                self.check_def_id(adt.did());
323                adt.variant_of_res(res)
324            }
325            _ => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
    format_args!("non-ADT in struct pattern"))span_bug!(lhs.span, "non-ADT in struct pattern"),
326        };
327        for pat in pats {
328            if let PatKind::Wild = pat.pat.kind {
329                continue;
330            }
331            let index = self.typeck_results().field_index(pat.hir_id);
332            self.insert_def_id(variant.fields[index].did);
333        }
334    }
335
336    fn handle_tuple_field_pattern_match(
337        &mut self,
338        lhs: &hir::Pat<'_>,
339        res: Res,
340        pats: &[hir::Pat<'_>],
341        dotdot: hir::DotDotPos,
342    ) {
343        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
344            ty::Adt(adt, _) => {
345                // Marks the ADT live if its variant appears as the pattern
346                self.check_def_id(adt.did());
347                adt.variant_of_res(res)
348            }
349            _ => {
350                self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
351                return;
352            }
353        };
354        let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
355        let first_n = pats.iter().enumerate().take(dotdot);
356        let missing = variant.fields.len() - pats.len();
357        let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
358        for (idx, pat) in first_n.chain(last_n) {
359            if let PatKind::Wild = pat.kind {
360                continue;
361            }
362            self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
363        }
364    }
365
366    fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
367        let indices = self
368            .typeck_results()
369            .offset_of_data()
370            .get(expr.hir_id)
371            .expect("no offset_of_data for offset_of");
372
373        for &(current_ty, variant, field) in indices {
374            match current_ty.kind() {
375                ty::Adt(def, _) => {
376                    let field = &def.variant(variant).fields[field];
377                    self.insert_def_id(field.did);
378                }
379                // we don't need to mark tuple fields as live,
380                // but we may need to mark subfields
381                ty::Tuple(_) => {}
382                _ => ::rustc_middle::util::bug::span_bug_fmt(expr.span,
    format_args!("named field access on non-ADT"))span_bug!(expr.span, "named field access on non-ADT"),
383            }
384        }
385    }
386
387    fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
388        while let Some(work) = self.worklist.pop() {
389            let WorkItem { mut id, propagated, own } = work;
390            self.propagated_comes_from_allow_expect = propagated;
391
392            // in the case of tuple struct constructors we want to check the item,
393            // not the generated tuple struct constructor function
394            if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
395                id = self.tcx.local_parent(id);
396            }
397
398            // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement
399            // by declaring fn calls, statics, ... within said items as live, as well as
400            // the item itself, although technically this is not the case.
401            //
402            // This means that the lint for said items will never be fired.
403            //
404            // This doesn't make any difference for the item declared with `#[allow]`, as
405            // the lint firing will be a nop, as it will be silenced by the `#[allow]` of
406            // the item.
407            //
408            // However, for `#[expect]`, the presence or absence of the lint is relevant,
409            // so we don't add it to the list of live symbols when it comes from a
410            // `#[expect]`. This means that we will correctly report an item as live or not
411            // for the `#[expect]` case.
412            //
413            // Note that an item can and will be duplicated on the worklist with different
414            // `ComesFromAllowExpect`, particularly if it was added from the
415            // `effective_visibilities` query or from the `#[allow]`/`#[expect]` checks,
416            // this "duplication" is essential as otherwise a function with `#[expect]`
417            // called from a `pub fn` may be falsely reported as not live, falsely
418            // triggering the `unfulfilled_lint_expectations` lint.
419            match own {
420                ComesFromAllowExpect::Yes => {}
421                ComesFromAllowExpect::No => {
422                    self.live_symbols.insert(id);
423                }
424            }
425
426            if !self.scanned.insert((id, propagated)) {
427                continue;
428            } else if propagated == ComesFromAllowExpect::No {
429                // If the item is not coming from an `#[allow]` or `#[expect]`,
430                // we also mark it as scanned with `ComesFromAllowExpect::Yes`
431                // to avoid re-scanning it in the future.
432                self.scanned.insert((id, ComesFromAllowExpect::Yes));
433            }
434
435            // Avoid accessing the HIR for the synthesized associated type generated for RPITITs.
436            if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
437                self.live_symbols.insert(id);
438                continue;
439            }
440
441            self.visit_node(self.tcx.hir_node_by_def_id(id))?;
442        }
443
444        ControlFlow::Continue(())
445    }
446
447    /// Automatically generated items marked with `rustc_trivial_field_reads`
448    /// will be ignored for the purposes of dead code analysis (see PR #85200
449    /// for discussion).
450    fn should_ignore_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) -> bool {
451        if let hir::ImplItemImplKind::Trait { .. } = impl_item.impl_kind
452            && let impl_of = self.tcx.local_parent(impl_item.owner_id.def_id)
453            && self.tcx.is_automatically_derived(impl_of.to_def_id())
454            && let trait_ref =
455                self.tcx.impl_trait_ref(impl_of).instantiate_identity().skip_norm_wip()
456            && {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(trait_ref.def_id,
                        &self.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcTrivialFieldReads)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, trait_ref.def_id, RustcTrivialFieldReads)
457        {
458            if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
459                && let Some(adt_def_id) = adt_def.did().as_local()
460            {
461                self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
462            }
463            return true;
464        }
465
466        false
467    }
468
469    fn visit_node(
470        &mut self,
471        node: Node<'tcx>,
472    ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
473        if let Node::ImplItem(impl_item) = node
474            && self.should_ignore_impl_item(impl_item)
475        {
476            return ControlFlow::Continue(());
477        }
478
479        let unconditionally_treated_fields_as_live =
480            self.repr_unconditionally_treats_fields_as_live;
481        let had_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
482        self.repr_unconditionally_treats_fields_as_live = false;
483        self.repr_has_repr_simd_or_scalable = false;
484        let walk_result = match node {
485            Node::Item(item) => match item.kind {
486                hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
487                    let def = self.tcx.adt_def(item.owner_id);
488                    self.repr_unconditionally_treats_fields_as_live =
489                        def.repr().c() || def.repr().transparent();
490                    self.repr_has_repr_simd_or_scalable =
491                        def.repr().simd() || def.repr().scalable();
492
493                    intravisit::walk_item(self, item)
494                }
495                hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
496                hir::ItemKind::Trait { items: trait_item_refs, .. } => {
497                    // mark assoc ty live if the trait is live
498                    for trait_item in trait_item_refs {
499                        if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
500                            self.check_def_id(trait_item.owner_id.to_def_id());
501                        }
502                    }
503                    intravisit::walk_item(self, item)
504                }
505                _ => intravisit::walk_item(self, item),
506            },
507            Node::TraitItem(trait_item) => {
508                // mark the trait live
509                let trait_item_id = trait_item.owner_id.to_def_id();
510                if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
511                    self.check_def_id(trait_id);
512                }
513                intravisit::walk_trait_item(self, trait_item)
514            }
515            Node::ImplItem(impl_item) => {
516                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
517                if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
518                    //// If it's a type whose items are live, then it's live, too.
519                    //// This is done to handle the case where, for example, the static
520                    //// method of a private type is used, but the type itself is never
521                    //// called directly.
522                    let self_ty = self.tcx.type_of(item).instantiate_identity().skip_norm_wip();
523                    match *self_ty.kind() {
524                        ty::Adt(def, _) => self.check_def_id(def.did()),
525                        ty::Foreign(did) => self.check_def_id(did),
526                        ty::Dynamic(data, ..) => {
527                            if let Some(def_id) = data.principal_def_id() {
528                                self.check_def_id(def_id)
529                            }
530                        }
531                        _ => {}
532                    }
533                }
534                intravisit::walk_impl_item(self, impl_item)
535            }
536            Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
537            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
538            _ => ControlFlow::Continue(()),
539        };
540        self.repr_has_repr_simd_or_scalable = had_repr_simd_or_scalable;
541        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
542
543        walk_result
544    }
545
546    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
547        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
548            for field in fields {
549                let index = self.typeck_results().field_index(field.hir_id);
550                self.insert_def_id(adt.non_enum_variant().fields[index].did);
551            }
552        }
553    }
554
555    /// Returns whether `local_def_id` is potentially alive or not.
556    /// `local_def_id` points to an impl or an impl item,
557    /// both impl and impl item that may be passed to this function are of a trait,
558    /// and added into the unsolved_items during `create_and_seed_worklist`
559    fn check_impl_or_impl_item_live(
560        &self,
561        local_def_id: LocalDefId,
562        defer_seeds_come_from_allow: bool,
563    ) -> ImplItemCheckResult {
564        let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
565            // assoc impl items of traits are live if the corresponding trait items are live
566            DefKind::AssocConst { .. } | DefKind::AssocTy | DefKind::AssocFn => {
567                let trait_def_id =
568                    self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
569                (self.tcx.local_parent(local_def_id), trait_def_id)
570            }
571            // impl items are live if the corresponding traits are live
572            DefKind::Impl { of_trait: true } => {
573                (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
574            }
575            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
576        };
577
578        let mut trait_comes_from_allow = None;
579        if let Some(trait_def_id) = trait_def_id {
580            if defer_seeds_come_from_allow {
581                if !self.live_symbols.contains(&trait_def_id) {
582                    return ImplItemCheckResult::Dead { require: trait_def_id };
583                }
584            } else {
585                trait_comes_from_allow = has_allow_dead_code_or_lang_attr(self.tcx, trait_def_id);
586
587                if !self.live_symbols.contains(&trait_def_id) {
588                    return match trait_comes_from_allow {
589                        Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
590                        None => ImplItemCheckResult::Dead { require: trait_def_id },
591                    };
592                }
593            }
594        }
595
596        // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used.
597        if let ty::Adt(adt, _) =
598            self.tcx.type_of(impl_block_id).instantiate_identity().skip_norm_wip().kind()
599            && let Some(adt_def_id) = adt.did().as_local()
600            && !self.live_symbols.contains(&adt_def_id)
601        {
602            if defer_seeds_come_from_allow {
603                return ImplItemCheckResult::Dead { require: adt_def_id };
604            } else {
605                let comes_from_allow = trait_comes_from_allow
606                    .or_else(|| has_allow_dead_code_or_lang_attr(self.tcx, adt_def_id));
607
608                return match comes_from_allow {
609                    Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
610                    None => ImplItemCheckResult::Dead { require: adt_def_id },
611                };
612            }
613        }
614
615        ImplItemCheckResult::Live(ComesFromAllowExpect::No)
616    }
617
618    fn collect_live_items_from_unsolved_items(
619        &mut self,
620        defer_seeds_come_from_allow: bool,
621        unsolved_items: Vec<LocalDefId>,
622        unsolved_map: &mut FxHashMap<LocalDefId, Vec<LocalDefId>>,
623    ) -> Vec<(LocalDefId, ComesFromAllowExpect)> {
624        let mut items_to_check = ::alloc::vec::Vec::new()vec![];
625
626        for def_id in unsolved_items {
627            match self.check_impl_or_impl_item_live(def_id, defer_seeds_come_from_allow) {
628                ImplItemCheckResult::Live(comes_from_allow) => {
629                    items_to_check.push((def_id, comes_from_allow));
630                }
631                ImplItemCheckResult::Dead { require } => {
632                    unsolved_map.entry(require).or_default().push(def_id);
633                }
634            }
635        }
636        items_to_check
637    }
638
639    #[expect(
640        rustc::potential_query_instability,
641        reason = "The order of the unsolved items is not important, so we can just collect them into a vector."
642    )]
643    fn mark_live_symbols_and_ignored_derived_traits(
644        &mut self,
645        defer_seeds_come_from_allow: bool,
646    ) -> Result<(), ErrorGuaranteed> {
647        if let ControlFlow::Break(guar) = self.mark_live_symbols() {
648            return Err(guar);
649        }
650
651        // We have marked the primary seeds as live. We now need to process unsolved items from traits
652        // and trait impls: add them to the work list if the trait or the implemented type is live.
653        let unsolved_items = std::mem::take(&mut self.unsolved_items);
654        let mut unsolved_map = FxHashMap::default();
655        let mut items_to_check = self.collect_live_items_from_unsolved_items(
656            defer_seeds_come_from_allow,
657            unsolved_items,
658            &mut unsolved_map,
659        );
660
661        while !items_to_check.is_empty() {
662            self.worklist.extend(items_to_check.into_iter().map(|(id, comes_from_allow)| {
663                let own = if defer_seeds_come_from_allow {
664                    ComesFromAllowExpect::No
665                } else {
666                    has_allow_dead_code_or_lang_attr(self.tcx, id)
667                        .unwrap_or(ComesFromAllowExpect::No)
668                };
669
670                WorkItem { id, propagated: comes_from_allow, own }
671            }));
672            if let ControlFlow::Break(guar) = self.mark_live_symbols() {
673                return Err(guar);
674            }
675
676            let unsolved_items = unsolved_map
677                .extract_if(|require, _| self.live_symbols.contains(require))
678                .flat_map(|(_, items)| items)
679                .collect();
680
681            items_to_check = self.collect_live_items_from_unsolved_items(
682                defer_seeds_come_from_allow,
683                unsolved_items,
684                &mut unsolved_map,
685            );
686        }
687
688        self.unsolved_items = unsolved_map.into_values().flatten().collect();
689
690        Ok(())
691    }
692}
693
694impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
695    type Result = ControlFlow<ErrorGuaranteed>;
696
697    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
698        let typeck_results = self.tcx.typeck_body(body);
699
700        // The result shouldn't be tainted, otherwise it will cause ICE.
701        if let Some(guar) = typeck_results.tainted_by_errors {
702            return ControlFlow::Break(guar);
703        }
704
705        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
706        let body = self.tcx.hir_body(body);
707        let result = self.visit_body(body);
708        self.maybe_typeck_results = old_maybe_typeck_results;
709
710        result
711    }
712
713    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
714        let tcx = self.tcx;
715        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
716        let has_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
717        let effective_visibilities = &tcx.effective_visibilities(());
718        let live_fields = def.fields().iter().filter_map(|f| {
719            let def_id = f.def_id;
720            if unconditionally_treat_fields_as_live
721                || (f.is_positional() && has_repr_simd_or_scalable)
722            {
723                return Some(def_id);
724            }
725            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
726                return None;
727            }
728            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
729        });
730        self.live_symbols.extend(live_fields);
731
732        intravisit::walk_struct_def(self, def)
733    }
734
735    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
736        match expr.kind {
737            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
738                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
739                self.handle_res(res);
740            }
741            hir::ExprKind::MethodCall(..) => {
742                self.lookup_and_handle_method(expr.hir_id);
743            }
744            hir::ExprKind::Field(ref lhs, ..) => {
745                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
746                    self.handle_field_access(lhs, expr.hir_id);
747                } else {
748                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
749                }
750            }
751            hir::ExprKind::Struct(qpath, fields, _) => {
752                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
753                self.handle_res(res);
754                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
755                    self.mark_as_used_if_union(*adt, fields);
756                }
757            }
758            hir::ExprKind::Closure(cls) => {
759                self.insert_def_id(cls.def_id.to_def_id());
760            }
761            hir::ExprKind::OffsetOf(..) => {
762                self.handle_offset_of(expr);
763            }
764            hir::ExprKind::Assign(ref lhs, ..) => {
765                self.handle_assign(lhs);
766                self.check_for_self_assign(expr);
767            }
768            _ => (),
769        }
770
771        intravisit::walk_expr(self, expr)
772    }
773
774    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
775        // Inside the body, ignore constructions of variants
776        // necessary for the pattern to match. Those construction sites
777        // can't be reached unless the variant is constructed elsewhere.
778        let len = self.ignore_variant_stack.len();
779        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
780        let result = intravisit::walk_arm(self, arm);
781        self.ignore_variant_stack.truncate(len);
782
783        result
784    }
785
786    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
787        self.in_pat = true;
788        match pat.kind {
789            PatKind::Struct(ref path, fields, _) => {
790                let res = self.typeck_results().qpath_res(path, pat.hir_id);
791                self.handle_field_pattern_match(pat, res, fields);
792            }
793            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
794                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
795                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
796            }
797            _ => (),
798        }
799
800        let result = intravisit::walk_pat(self, pat);
801        self.in_pat = false;
802
803        result
804    }
805
806    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
807        match &expr.kind {
808            rustc_hir::PatExprKind::Path(qpath) => {
809                // mark the type of variant live when meeting E::V in expr
810                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
811                    self.check_def_id(adt.did());
812                }
813
814                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
815                self.handle_res(res);
816            }
817            _ => {}
818        }
819        intravisit::walk_pat_expr(self, expr)
820    }
821
822    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
823        self.handle_res(path.res);
824        intravisit::walk_path(self, path)
825    }
826
827    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
828        // When inline const blocks are used in pattern position, paths
829        // referenced by it should be considered as used.
830        let in_pat = mem::replace(&mut self.in_pat, false);
831
832        self.live_symbols.insert(c.def_id);
833        let result = intravisit::walk_anon_const(self, c);
834
835        self.in_pat = in_pat;
836
837        result
838    }
839
840    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
841        // When inline const blocks are used in pattern position, paths
842        // referenced by it should be considered as used.
843        let in_pat = mem::replace(&mut self.in_pat, false);
844
845        self.live_symbols.insert(c.def_id);
846        let result = intravisit::walk_inline_const(self, c);
847
848        self.in_pat = in_pat;
849
850        result
851    }
852
853    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
854        if let Some(trait_def_id) = t.path.res.opt_def_id()
855            && let Some(segment) = t.path.segments.last()
856            && let Some(args) = segment.args
857        {
858            for constraint in args.constraints {
859                if let Some(local_def_id) = self
860                    .tcx
861                    .associated_items(trait_def_id)
862                    .find_by_ident_and_kind(
863                        self.tcx,
864                        constraint.ident,
865                        AssocTag::Const,
866                        trait_def_id,
867                    )
868                    .and_then(|item| item.def_id.as_local())
869                {
870                    self.worklist.push(WorkItem {
871                        id: local_def_id,
872                        propagated: ComesFromAllowExpect::No,
873                        own: ComesFromAllowExpect::No,
874                    });
875                }
876            }
877        }
878
879        intravisit::walk_trait_ref(self, t)
880    }
881}
882
883fn has_allow_dead_code_or_lang_attr(
884    tcx: TyCtxt<'_>,
885    def_id: LocalDefId,
886) -> Option<ComesFromAllowExpect> {
887    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
888        let hir_id = tcx.local_def_id_to_hir_id(def_id);
889        let lint_level = tcx.lint_level_spec_at_node(DEAD_CODE, hir_id).level();
890        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
891    }
892
893    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
894        tcx.def_kind(def_id).has_codegen_attrs() && {
895            let cg_attrs = tcx.codegen_fn_attrs(def_id);
896
897            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
898            // forcefully, e.g., for placing it in a specific section.
899            cg_attrs.contains_extern_indicator()
900                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
901                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
902        }
903    }
904
905    if has_allow_expect_dead_code(tcx, def_id) {
906        Some(ComesFromAllowExpect::Yes)
907    } else if has_used_like_attr(tcx, def_id)
908        || {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Lang(..) |
                            RustcCanonicalSymbol) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, Lang(..) | RustcCanonicalSymbol)
909    {
910        Some(ComesFromAllowExpect::No)
911    } else {
912        None
913    }
914}
915
916/// Examine the given definition and record it in the worklist if it should be considered live.
917///
918/// We want to explicitly consider as live:
919/// * Item annotated with #[allow(dead_code)]
920///       This is done so that if we want to suppress warnings for a
921///       group of dead functions, we only have to annotate the "root".
922///       For example, if both `f` and `g` are dead and `f` calls `g`,
923///       then annotating `f` with `#[allow(dead_code)]` will suppress
924///       warning for both `f` and `g`.
925///
926/// * Item annotated with #[lang=".."]
927///       Lang items are always callable from elsewhere.
928///
929/// For trait methods and implementations of traits, we are not certain that the definitions are
930/// live at this stage. We record them in `unsolved_items` for later examination.
931fn maybe_record_as_seed<'tcx>(
932    tcx: TyCtxt<'tcx>,
933    owner_id: hir::OwnerId,
934    push_into_worklist: &mut impl FnMut(WorkItem),
935    unsolved_items: &mut Vec<LocalDefId>,
936) {
937    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
938    if let Some(comes_from_allow) = allow_dead_code {
939        push_into_worklist(WorkItem {
940            id: owner_id.def_id,
941            propagated: comes_from_allow,
942            own: comes_from_allow,
943        });
944    }
945
946    match tcx.def_kind(owner_id) {
947        DefKind::Enum => {
948            if let Some(comes_from_allow) = allow_dead_code {
949                let adt = tcx.adt_def(owner_id);
950                for variant in adt.variants().iter() {
951                    push_into_worklist(WorkItem {
952                        id: variant.def_id.expect_local(),
953                        propagated: comes_from_allow,
954                        own: comes_from_allow,
955                    });
956                }
957            }
958        }
959        DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy => {
960            if allow_dead_code.is_none() {
961                let parent = tcx.local_parent(owner_id.def_id);
962                match tcx.def_kind(parent) {
963                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
964                    DefKind::Impl { of_trait: true } => {
965                        // We only care about associated items of traits,
966                        // because they cannot be visited directly,
967                        // so we later mark them as live if their corresponding traits
968                        // or trait items and self types are both live,
969                        // but inherent associated items can be visited and marked directly.
970                        unsolved_items.push(owner_id.def_id);
971                    }
972                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
973                }
974            }
975        }
976        DefKind::Impl { of_trait: true } if allow_dead_code.is_none() => {
977            unsolved_items.push(owner_id.def_id);
978        }
979        DefKind::GlobalAsm => {
980            // global_asm! is always live.
981            push_into_worklist(WorkItem {
982                id: owner_id.def_id,
983                propagated: ComesFromAllowExpect::No,
984                own: ComesFromAllowExpect::No,
985            });
986        }
987        DefKind::Const { .. } => {
988            if tcx.item_name(owner_id.def_id) == kw::Underscore {
989                // `const _` is always live, as that syntax only exists for the side effects
990                // of type checking and evaluating the constant expression, and marking them
991                // as dead code would defeat that purpose.
992                push_into_worklist(WorkItem {
993                    id: owner_id.def_id,
994                    propagated: ComesFromAllowExpect::No,
995                    own: ComesFromAllowExpect::No,
996                });
997            }
998        }
999        _ => {}
1000    }
1001}
1002
1003#[derive(#[automatically_derived]
impl ::core::default::Default for DeferredSeeds {
    #[inline]
    fn default() -> DeferredSeeds {
        DeferredSeeds {
            pub_reachables: ::core::default::Default::default(),
            come_from_allow: ::core::default::Default::default(),
        }
    }
}Default)]
1004struct DeferredSeeds {
1005    pub_reachables: Vec<WorkItem>,
1006    come_from_allow: Vec<WorkItem>,
1007}
1008
1009struct SeedWorklists {
1010    worklist: Vec<WorkItem>,
1011    deferred_seeds: DeferredSeeds,
1012    unsolved_items: Vec<LocalDefId>,
1013}
1014
1015fn create_and_seed_worklist(tcx: TyCtxt<'_>) -> SeedWorklists {
1016    let mut unsolved_items = Vec::new();
1017    let mut deferred_seeds = DeferredSeeds::default();
1018    let mut worklist = Vec::new();
1019
1020    if let Some((def_id, _)) = tcx.entry_fn(())
1021        && let Some(local_def_id) = def_id.as_local()
1022    {
1023        worklist.push(WorkItem {
1024            id: local_def_id,
1025            propagated: ComesFromAllowExpect::No,
1026            own: ComesFromAllowExpect::No,
1027        });
1028    }
1029
1030    // Under `--test`, what `main` resolves to is the would-be entry point of a normal build,
1031    // so keep it live, unless a stripped user `#[rustc_main]` would have been the entry instead.
1032    if tcx.sess.is_test_crate()
1033        && !tcx.sess.removed_rustc_main_attr.load(Ordering::Relaxed)
1034        && let Some(main_def) = tcx.resolutions(()).main_def
1035        && let Some(def_id) = main_def.opt_fn_def_id()
1036        && let Some(local_def_id) = def_id.as_local()
1037    {
1038        worklist.push(WorkItem {
1039            id: local_def_id,
1040            propagated: ComesFromAllowExpect::No,
1041            own: ComesFromAllowExpect::No,
1042        });
1043    }
1044
1045    for (id, effective_vis) in tcx.effective_visibilities(()).iter() {
1046        if effective_vis.is_public_at_level(Level::Reachable) {
1047            deferred_seeds.pub_reachables.push(WorkItem {
1048                id: *id,
1049                propagated: ComesFromAllowExpect::No,
1050                own: ComesFromAllowExpect::No,
1051            });
1052        }
1053    }
1054
1055    let mut push_into_worklist = |work_item: WorkItem| match work_item.own {
1056        ComesFromAllowExpect::Yes => deferred_seeds.come_from_allow.push(work_item),
1057        ComesFromAllowExpect::No => worklist.push(work_item),
1058    };
1059    let crate_items = tcx.hir_crate_items(());
1060    for id in crate_items.owners() {
1061        maybe_record_as_seed(tcx, id, &mut push_into_worklist, &mut unsolved_items);
1062    }
1063
1064    SeedWorklists { worklist, deferred_seeds, unsolved_items }
1065}
1066
1067fn live_symbols_and_ignored_derived_traits(
1068    tcx: TyCtxt<'_>,
1069    (): (),
1070) -> Result<DeadCodeLivenessSummary, ErrorGuaranteed> {
1071    let SeedWorklists { worklist, deferred_seeds, unsolved_items } = create_and_seed_worklist(tcx);
1072    let mut symbol_visitor = MarkSymbolVisitor {
1073        worklist,
1074        tcx,
1075        maybe_typeck_results: None,
1076        scanned: Default::default(),
1077        live_symbols: Default::default(),
1078        repr_unconditionally_treats_fields_as_live: false,
1079        repr_has_repr_simd_or_scalable: false,
1080        in_pat: false,
1081        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
1082        ignored_derived_traits: Default::default(),
1083        propagated_comes_from_allow_expect: ComesFromAllowExpect::No,
1084        unsolved_items,
1085    };
1086    symbol_visitor.mark_live_symbols_and_ignored_derived_traits(true)?;
1087    let pre_deferred_seeding = DeadCodeLivenessSnapshot {
1088        live_symbols: symbol_visitor.live_symbols.clone(),
1089        ignored_derived_traits: symbol_visitor.ignored_derived_traits.clone(),
1090    };
1091
1092    if !deferred_seeds.pub_reachables.is_empty() {
1093        symbol_visitor.worklist.extend(deferred_seeds.pub_reachables);
1094        symbol_visitor.mark_live_symbols_and_ignored_derived_traits(true)?;
1095    }
1096
1097    if !deferred_seeds.come_from_allow.is_empty() {
1098        symbol_visitor.worklist.extend(deferred_seeds.come_from_allow);
1099        symbol_visitor.mark_live_symbols_and_ignored_derived_traits(false)?;
1100    }
1101
1102    Ok(DeadCodeLivenessSummary {
1103        pre_deferred_seeding,
1104        final_result: DeadCodeLivenessSnapshot {
1105            live_symbols: symbol_visitor.live_symbols,
1106            ignored_derived_traits: symbol_visitor.ignored_derived_traits,
1107        },
1108    })
1109}
1110
1111struct DeadItem {
1112    def_id: LocalDefId,
1113    name: Symbol,
1114    level_plus: (lint::Level, Option<StableLintExpectationId>),
1115}
1116
1117struct DeadVisitor<'tcx> {
1118    tcx: TyCtxt<'tcx>,
1119    target_lint: &'static Lint,
1120    live_symbols: &'tcx LocalDefIdSet,
1121    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1122}
1123
1124enum ShouldWarnAboutField {
1125    Yes,
1126    No,
1127}
1128
1129#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReportOn {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ReportOn::TupleField => "TupleField",
                ReportOn::NamedField => "NamedField",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReportOn { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ReportOn { }
#[automatically_derived]
impl ::core::clone::Clone for ReportOn {
    #[inline]
    fn clone(&self) -> ReportOn { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ReportOn { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ReportOn {
    #[inline]
    fn eq(&self, other: &ReportOn) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportOn {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
1130enum ReportOn {
1131    /// Report on something that hasn't got a proper name to refer to
1132    TupleField,
1133    /// Report on something that has got a name, which could be a field but also a method
1134    NamedField,
1135}
1136
1137impl<'tcx> DeadVisitor<'tcx> {
1138    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
1139        if self.live_symbols.contains(&field.did.expect_local()) {
1140            return ShouldWarnAboutField::No;
1141        }
1142        let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
1143        if field_type.is_phantom_data() {
1144            return ShouldWarnAboutField::No;
1145        }
1146        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
1147        if is_positional
1148            && self
1149                .tcx
1150                .layout_of(
1151                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
1152                        .as_query_input(field_type),
1153                )
1154                .map_or(true, |layout| layout.is_zst())
1155        {
1156            return ShouldWarnAboutField::No;
1157        }
1158        ShouldWarnAboutField::Yes
1159    }
1160
1161    fn def_lint_level_plus(
1162        &self,
1163        id: LocalDefId,
1164    ) -> (lint::Level, Option<StableLintExpectationId>) {
1165        let hir_id = self.tcx.local_def_id_to_hir_id(id);
1166        let level_spec = self.tcx.lint_level_spec_at_node(self.target_lint, hir_id);
1167        (level_spec.level(), level_spec.lint_id())
1168    }
1169
1170    fn dead_code_pub_in_binary_note(&self) -> Option<DeadCodePubInBinaryNote> {
1171        self.target_lint.name.eq(DEAD_CODE_PUB_IN_BINARY.name).then_some(DeadCodePubInBinaryNote)
1172    }
1173
1174    // # Panics
1175    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
1176    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
1177    // first local def id.
1178    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
1179    // since those methods group by lint level before calling this method.
1180    fn lint_at_single_level(
1181        &self,
1182        dead_codes: &[&DeadItem],
1183        participle: &str,
1184        parent_item: Option<LocalDefId>,
1185        report_on: ReportOn,
1186    ) {
1187        let Some(&first_item) = dead_codes.first() else { return };
1188        let tcx = self.tcx;
1189
1190        let first_lint_level_plus = first_item.level_plus;
1191        if !dead_codes.iter().skip(1).all(|item|
                item.level_plus == first_lint_level_plus) {
    ::core::panicking::panic("assertion failed: dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus)")
};assert!(dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus));
1192
1193        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1194        let spans: Vec<_> = dead_codes
1195            .iter()
1196            .map(|item| {
1197                let span = tcx.def_span(item.def_id);
1198                let ident_span = tcx.def_ident_span(item.def_id);
1199                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
1200                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
1201            })
1202            .collect();
1203
1204        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
1205        // `impl` blocks are "batched" and (unlike other batching) might
1206        // contain different kinds of associated items.
1207        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
1208            descr = "associated item"
1209        }
1210
1211        let num = dead_codes.len();
1212        let multiple = num > 6;
1213        let name_list = names.into();
1214
1215        let parent_info = parent_item.map(|parent_item| {
1216            let parent_descr = tcx.def_descr(parent_item.to_def_id());
1217            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1218                tcx.def_span(parent_item)
1219            } else {
1220                tcx.def_ident_span(parent_item).unwrap()
1221            };
1222            ParentInfo { num, descr, parent_descr, span }
1223        });
1224
1225        let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1226        // `ignored_derived_traits` is computed for the enum, not for the variants.
1227        if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1228            encl_def_id = tcx.local_parent(encl_def_id);
1229        }
1230
1231        let ignored_derived_impls =
1232            self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1233                let trait_list = ign_traits
1234                    .iter()
1235                    .map(|trait_id| self.tcx.item_name(*trait_id))
1236                    .collect::<Vec<_>>();
1237                let trait_list_len = trait_list.len();
1238                IgnoredDerivedImpls {
1239                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1240                    trait_list: trait_list.into(),
1241                    trait_list_len,
1242                }
1243            });
1244
1245        let diag = match report_on {
1246            ReportOn::TupleField => {
1247                let tuple_fields = if let Some(parent_id) = parent_item
1248                    && let node = tcx.hir_node_by_def_id(parent_id)
1249                    && let hir::Node::Item(hir::Item {
1250                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1251                        ..
1252                    }) = node
1253                {
1254                    *fields
1255                } else {
1256                    &[]
1257                };
1258
1259                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1260                    LocalDefIdSet::from_iter(
1261                        tuple_fields
1262                            .iter()
1263                            .skip(tuple_fields.len() - dead_codes.len())
1264                            .map(|f| f.def_id),
1265                    )
1266                } else {
1267                    LocalDefIdSet::default()
1268                };
1269
1270                let fields_suggestion =
1271                    // Suggest removal if all tuple fields are at the end.
1272                    // Otherwise suggest removal or changing to unit type
1273                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1274                        ChangeFields::Remove { num }
1275                    } else {
1276                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1277                    };
1278
1279                MultipleDeadCodes::UnusedTupleStructFields {
1280                    multiple,
1281                    num,
1282                    descr,
1283                    participle,
1284                    name_list,
1285                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1286                    change_fields_suggestion: fields_suggestion,
1287                    parent_info,
1288                    ignored_derived_impls,
1289                }
1290            }
1291            ReportOn::NamedField => {
1292                let enum_variants_with_same_name = dead_codes
1293                    .iter()
1294                    .filter_map(|dead_item| {
1295                        if let DefKind::AssocFn | DefKind::AssocConst { .. } =
1296                            tcx.def_kind(dead_item.def_id)
1297                            && let impl_did = tcx.local_parent(dead_item.def_id)
1298                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1299                            && let ty::Adt(maybe_enum, _) =
1300                                tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1301                            && maybe_enum.is_enum()
1302                            && let Some(variant) =
1303                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1304                        {
1305                            Some(crate::diagnostics::EnumVariantSameName {
1306                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1307                                dead_name: dead_item.name,
1308                                variant_span: tcx.def_span(variant.def_id),
1309                            })
1310                        } else {
1311                            None
1312                        }
1313                    })
1314                    .collect();
1315
1316                MultipleDeadCodes::DeadCodes {
1317                    multiple,
1318                    num,
1319                    descr,
1320                    participle,
1321                    name_list,
1322                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1323                    parent_info,
1324                    ignored_derived_impls,
1325                    enum_variants_with_same_name,
1326                }
1327            }
1328        };
1329
1330        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1331        self.tcx.emit_node_span_lint(self.target_lint, hir_id, MultiSpan::from_spans(spans), diag);
1332    }
1333
1334    fn warn_multiple(
1335        &self,
1336        def_id: LocalDefId,
1337        participle: &str,
1338        dead_codes: Vec<DeadItem>,
1339        report_on: ReportOn,
1340    ) {
1341        let mut dead_codes = dead_codes
1342            .iter()
1343            .filter(|v| !v.name.as_str().starts_with('_'))
1344            .collect::<Vec<&DeadItem>>();
1345        if dead_codes.is_empty() {
1346            return;
1347        }
1348        // FIXME: `dead_codes` should probably be morally equivalent to
1349        // `IndexMap<(Level, StableLintExpectationId), (DefId, Symbol)>`
1350        dead_codes.sort_by_key(|v| v.level_plus.0);
1351        for group in dead_codes.chunk_by(|a, b| a.level_plus == b.level_plus) {
1352            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1353        }
1354    }
1355
1356    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1357        let item = DeadItem {
1358            def_id: id,
1359            name: self.tcx.item_name(id.to_def_id()),
1360            level_plus: self.def_lint_level_plus(id),
1361        };
1362        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1363    }
1364
1365    fn check_definition(&mut self, def_id: LocalDefId) {
1366        if self.is_live_code(def_id) {
1367            return;
1368        }
1369        match self.tcx.def_kind(def_id) {
1370            DefKind::AssocConst { .. }
1371            | DefKind::AssocTy
1372            | DefKind::AssocFn
1373            | DefKind::Fn
1374            | DefKind::Static { .. }
1375            | DefKind::Const { .. }
1376            | DefKind::TyAlias
1377            | DefKind::Enum
1378            | DefKind::Union
1379            | DefKind::ForeignTy
1380            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1381            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1382            DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1383            _ => {}
1384        }
1385    }
1386
1387    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1388        // if we cannot get a name for the item, then we just assume that it is
1389        // live. I mean, we can't really emit a lint.
1390        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1391            return true;
1392        };
1393
1394        self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1395    }
1396}
1397
1398fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModId) {
1399    let Ok(DeadCodeLivenessSummary { pre_deferred_seeding, final_result }) =
1400        tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1401    else {
1402        return;
1403    };
1404
1405    let module_items = tcx.hir_module_items(module);
1406
1407    if tcx.crate_types().contains(&CrateType::Executable) {
1408        let is_unused_pub = |def_id: LocalDefId| {
1409            tcx.effective_visibilities(()).is_public_at_level(def_id, Level::Reachable)
1410                && !pre_deferred_seeding.live_symbols.contains(&def_id)
1411        };
1412
1413        lint_dead_codes(
1414            tcx,
1415            DEAD_CODE_PUB_IN_BINARY,
1416            module,
1417            &pre_deferred_seeding.live_symbols,
1418            &pre_deferred_seeding.ignored_derived_traits,
1419            module_items.free_items().filter(|free_item| is_unused_pub(free_item.owner_id.def_id)),
1420            module_items
1421                .foreign_items()
1422                .filter(|foreign_item| is_unused_pub(foreign_item.owner_id.def_id)),
1423        );
1424    }
1425
1426    lint_dead_codes(
1427        tcx,
1428        DEAD_CODE,
1429        module,
1430        &final_result.live_symbols,
1431        &final_result.ignored_derived_traits,
1432        module_items.free_items(),
1433        module_items.foreign_items(),
1434    );
1435}
1436
1437fn lint_dead_codes<'tcx>(
1438    tcx: TyCtxt<'tcx>,
1439    target_lint: &'static Lint,
1440    module: LocalModId,
1441    live_symbols: &'tcx LocalDefIdSet,
1442    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1443    free_items: impl Iterator<Item = ItemId>,
1444    foreign_items: impl Iterator<Item = ForeignItemId>,
1445) {
1446    let mut visitor = DeadVisitor { tcx, target_lint, live_symbols, ignored_derived_traits };
1447    for item in free_items {
1448        let def_kind = tcx.def_kind(item.owner_id);
1449
1450        let mut dead_codes = Vec::new();
1451        // Only diagnose unused assoc items in inherent impl and used trait,
1452        // for unused assoc items in impls of trait,
1453        // we have diagnosed them in the trait if they are unused,
1454        // for unused assoc items in unused trait,
1455        // we have diagnosed the unused trait.
1456        if def_kind == (DefKind::Impl { of_trait: false })
1457            || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1458        {
1459            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1460                if let Some(local_def_id) = def_id.as_local()
1461                    && !visitor.is_live_code(local_def_id)
1462                {
1463                    let name = tcx.item_name(def_id);
1464                    let level_plus = visitor.def_lint_level_plus(local_def_id);
1465                    dead_codes.push(DeadItem { def_id: local_def_id, name, level_plus });
1466                }
1467            }
1468        }
1469        if !dead_codes.is_empty() {
1470            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1471        }
1472
1473        if !live_symbols.contains(&item.owner_id.def_id) {
1474            let parent = tcx.local_parent(item.owner_id.def_id);
1475            if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1476                // We already have diagnosed something.
1477                continue;
1478            }
1479            visitor.check_definition(item.owner_id.def_id);
1480            continue;
1481        }
1482
1483        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1484            let adt = tcx.adt_def(item.owner_id);
1485            let mut dead_variants = Vec::new();
1486
1487            for variant in adt.variants() {
1488                let def_id = variant.def_id.expect_local();
1489                if !live_symbols.contains(&def_id) {
1490                    // Record to group diagnostics.
1491                    let level_plus = visitor.def_lint_level_plus(def_id);
1492                    dead_variants.push(DeadItem { def_id, name: variant.name, level_plus });
1493                    continue;
1494                }
1495
1496                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1497                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1498                });
1499                let report_on =
1500                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1501                let dead_fields = variant
1502                    .fields
1503                    .iter()
1504                    .filter_map(|field| {
1505                        let def_id = field.did.expect_local();
1506                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1507                            let level_plus = visitor.def_lint_level_plus(def_id);
1508                            Some(DeadItem { def_id, name: field.name, level_plus })
1509                        } else {
1510                            None
1511                        }
1512                    })
1513                    .collect();
1514                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1515            }
1516
1517            visitor.warn_multiple(
1518                item.owner_id.def_id,
1519                "constructed",
1520                dead_variants,
1521                ReportOn::NamedField,
1522            );
1523        }
1524    }
1525
1526    for foreign_item in foreign_items {
1527        visitor.check_definition(foreign_item.owner_id.def_id);
1528    }
1529}
1530
1531pub(crate) fn provide(providers: &mut Providers) {
1532    *providers =
1533        Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1534}