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_attr_ir::find_attr;
13use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
14use rustc_errors::{ErrorGuaranteed, MultiSpan};
15use rustc_hir::def::{CtorOf, DefKind, Res};
16use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
17use rustc_hir::intravisit::{self, Visitor};
18use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath};
19use rustc_lint_defs::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
20use rustc_lint_defs::{self as lint, Lint, StableLintExpectationId};
21use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
22use rustc_middle::middle::dead_code::{DeadCodeLivenessSnapshot, DeadCodeLivenessSummary};
23use rustc_middle::middle::privacy::Level;
24use rustc_middle::query::Providers;
25use rustc_middle::ty::{self, AssocTag, TyCtxt};
26use rustc_span::{Symbol, bug, kw, span_bug};
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) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for ComesFromAllowExpect { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ComesFromAllowExpect { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ComesFromAllowExpect {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for ComesFromAllowExpect {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            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) -> Self {
        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: &Self) -> 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_span::macros::bug_impl(Some(lhs.span),
    format_args!("named field access on non-ADT: {0:?}", kind),
    Location::caller())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_span::macros::bug_impl(Some(lhs.span),
    format_args!("non-ADT in struct pattern"), Location::caller())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_span::macros::bug_impl(Some(expr.span),
    format_args!("named field access on non-ADT"), Location::caller())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_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())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            }
605
606            return match trait_comes_from_allow {
607                Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
608                None => ImplItemCheckResult::Dead { require: adt_def_id },
609            };
610        }
611
612        ImplItemCheckResult::Live(ComesFromAllowExpect::No)
613    }
614
615    fn collect_live_items_from_unsolved_items(
616        &mut self,
617        defer_seeds_come_from_allow: bool,
618        unsolved_items: Vec<LocalDefId>,
619        unsolved_map: &mut FxHashMap<LocalDefId, Vec<LocalDefId>>,
620    ) -> Vec<(LocalDefId, ComesFromAllowExpect)> {
621        let mut items_to_check = ::alloc::vec::Vec::new()vec![];
622
623        for def_id in unsolved_items {
624            match self.check_impl_or_impl_item_live(def_id, defer_seeds_come_from_allow) {
625                ImplItemCheckResult::Live(comes_from_allow) => {
626                    items_to_check.push((def_id, comes_from_allow));
627                }
628                ImplItemCheckResult::Dead { require } => {
629                    unsolved_map.entry(require).or_default().push(def_id);
630                }
631            }
632        }
633        items_to_check
634    }
635
636    #[expect(
637        rustc::potential_query_instability,
638        reason = "The order of the unsolved items is not important, so we can just collect them into a vector."
639    )]
640    fn mark_live_symbols_and_ignored_derived_traits(
641        &mut self,
642        defer_seeds_come_from_allow: bool,
643    ) -> Result<(), ErrorGuaranteed> {
644        if let ControlFlow::Break(guar) = self.mark_live_symbols() {
645            return Err(guar);
646        }
647
648        // We have marked the primary seeds as live. We now need to process unsolved items from traits
649        // and trait impls: add them to the work list if the trait or the implemented type is live.
650        let unsolved_items = std::mem::take(&mut self.unsolved_items);
651        let mut unsolved_map = FxHashMap::default();
652        let mut items_to_check = self.collect_live_items_from_unsolved_items(
653            defer_seeds_come_from_allow,
654            unsolved_items,
655            &mut unsolved_map,
656        );
657
658        while !items_to_check.is_empty() {
659            self.worklist.extend(items_to_check.into_iter().map(|(id, comes_from_allow)| {
660                let own = if defer_seeds_come_from_allow {
661                    ComesFromAllowExpect::No
662                } else {
663                    has_allow_dead_code_or_lang_attr(self.tcx, id)
664                        .unwrap_or(ComesFromAllowExpect::No)
665                };
666
667                WorkItem { id, propagated: comes_from_allow, own }
668            }));
669            if let ControlFlow::Break(guar) = self.mark_live_symbols() {
670                return Err(guar);
671            }
672
673            let unsolved_items = unsolved_map
674                .extract_if(|require, _| self.live_symbols.contains(require))
675                .flat_map(|(_, items)| items)
676                .collect();
677
678            items_to_check = self.collect_live_items_from_unsolved_items(
679                defer_seeds_come_from_allow,
680                unsolved_items,
681                &mut unsolved_map,
682            );
683        }
684
685        self.unsolved_items = unsolved_map.into_values().flatten().collect();
686
687        Ok(())
688    }
689}
690
691impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
692    type Result = ControlFlow<ErrorGuaranteed>;
693
694    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
695        let typeck_results = self.tcx.typeck_body(body);
696
697        // The result shouldn't be tainted, otherwise it will cause ICE.
698        if let Some(guar) = typeck_results.tainted_by_errors {
699            return ControlFlow::Break(guar);
700        }
701
702        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
703        let body = self.tcx.hir_body(body);
704        let result = self.visit_body(body);
705        self.maybe_typeck_results = old_maybe_typeck_results;
706
707        result
708    }
709
710    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
711        let tcx = self.tcx;
712        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
713        let has_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
714        let effective_visibilities = &tcx.effective_visibilities(());
715        let live_fields = def.fields().iter().filter_map(|f| {
716            let def_id = f.def_id;
717            if unconditionally_treat_fields_as_live
718                || (f.is_positional() && has_repr_simd_or_scalable)
719            {
720                return Some(def_id);
721            }
722            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
723                return None;
724            }
725            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
726        });
727        self.live_symbols.extend(live_fields);
728
729        intravisit::walk_struct_def(self, def)
730    }
731
732    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
733        match expr.kind {
734            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
735                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
736                self.handle_res(res);
737            }
738            hir::ExprKind::MethodCall(..) => {
739                self.lookup_and_handle_method(expr.hir_id);
740            }
741            hir::ExprKind::Field(ref lhs, ..) => {
742                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
743                    self.handle_field_access(lhs, expr.hir_id);
744                } else {
745                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
746                }
747            }
748            hir::ExprKind::Struct(qpath, fields, _) => {
749                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
750                self.handle_res(res);
751                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
752                    self.mark_as_used_if_union(*adt, fields);
753                }
754            }
755            hir::ExprKind::Closure(cls) => {
756                self.insert_def_id(cls.def_id.to_def_id());
757            }
758            hir::ExprKind::OffsetOf(..) => {
759                self.handle_offset_of(expr);
760            }
761            hir::ExprKind::Assign(ref lhs, ..) => {
762                self.handle_assign(lhs);
763                self.check_for_self_assign(expr);
764            }
765            _ => (),
766        }
767
768        intravisit::walk_expr(self, expr)
769    }
770
771    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
772        // Inside the body, ignore constructions of variants
773        // necessary for the pattern to match. Those construction sites
774        // can't be reached unless the variant is constructed elsewhere.
775        let len = self.ignore_variant_stack.len();
776        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
777        let result = intravisit::walk_arm(self, arm);
778        self.ignore_variant_stack.truncate(len);
779
780        result
781    }
782
783    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
784        self.in_pat = true;
785        match pat.kind {
786            PatKind::Struct(ref path, fields, _) => {
787                let res = self.typeck_results().qpath_res(path, pat.hir_id);
788                self.handle_field_pattern_match(pat, res, fields);
789            }
790            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
791                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
792                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
793            }
794            _ => (),
795        }
796
797        let result = intravisit::walk_pat(self, pat);
798        self.in_pat = false;
799
800        result
801    }
802
803    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
804        match &expr.kind {
805            rustc_hir::PatExprKind::Path(qpath) => {
806                // mark the type of variant live when meeting E::V in expr
807                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
808                    self.check_def_id(adt.did());
809                }
810
811                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
812                self.handle_res(res);
813            }
814            _ => {}
815        }
816        intravisit::walk_pat_expr(self, expr)
817    }
818
819    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
820        self.handle_res(path.res);
821        intravisit::walk_path(self, path)
822    }
823
824    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
825        // When inline const blocks are used in pattern position, paths
826        // referenced by it should be considered as used.
827        let in_pat = mem::replace(&mut self.in_pat, false);
828
829        self.live_symbols.insert(c.def_id);
830        let result = intravisit::walk_anon_const(self, c);
831
832        self.in_pat = in_pat;
833
834        result
835    }
836
837    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
838        // When inline const blocks are used in pattern position, paths
839        // referenced by it should be considered as used.
840        let in_pat = mem::replace(&mut self.in_pat, false);
841
842        self.live_symbols.insert(c.def_id);
843        let result = intravisit::walk_inline_const(self, c);
844
845        self.in_pat = in_pat;
846
847        result
848    }
849
850    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
851        if let Some(trait_def_id) = t.path.res.opt_def_id()
852            && let Some(segment) = t.path.segments.last()
853            && let Some(args) = segment.args
854        {
855            for constraint in args.constraints {
856                if let Some(local_def_id) = self
857                    .tcx
858                    .associated_items(trait_def_id)
859                    .find_by_ident_and_kind(
860                        self.tcx,
861                        constraint.ident,
862                        AssocTag::Const,
863                        trait_def_id,
864                    )
865                    .and_then(|item| item.def_id.as_local())
866                {
867                    self.worklist.push(WorkItem {
868                        id: local_def_id,
869                        propagated: ComesFromAllowExpect::No,
870                        own: ComesFromAllowExpect::No,
871                    });
872                }
873            }
874        }
875
876        intravisit::walk_trait_ref(self, t)
877    }
878}
879
880fn has_allow_dead_code_or_lang_attr(
881    tcx: TyCtxt<'_>,
882    def_id: LocalDefId,
883) -> Option<ComesFromAllowExpect> {
884    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
885        let hir_id = tcx.local_def_id_to_hir_id(def_id);
886        let lint_level = tcx.lint_level_spec_at_node(DEAD_CODE, hir_id).level();
887        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
888    }
889
890    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
891        tcx.def_kind(def_id).has_codegen_attrs() && {
892            let cg_attrs = tcx.codegen_fn_attrs(def_id);
893
894            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
895            // forcefully, e.g., for placing it in a specific section.
896            cg_attrs.contains_extern_indicator()
897                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
898                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
899        }
900    }
901
902    if has_allow_expect_dead_code(tcx, def_id) {
903        Some(ComesFromAllowExpect::Yes)
904    } else if has_used_like_attr(tcx, def_id)
905        || {
        {
            '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)
906    {
907        Some(ComesFromAllowExpect::No)
908    } else {
909        None
910    }
911}
912
913/// Examine the given definition and record it in the worklist if it should be considered live.
914///
915/// We want to explicitly consider as live:
916/// * Item annotated with #[allow(dead_code)]
917///       This is done so that if we want to suppress warnings for a
918///       group of dead functions, we only have to annotate the "root".
919///       For example, if both `f` and `g` are dead and `f` calls `g`,
920///       then annotating `f` with `#[allow(dead_code)]` will suppress
921///       warning for both `f` and `g`.
922///
923/// * Item annotated with #[lang=".."]
924///       Lang items are always callable from elsewhere.
925///
926/// For trait methods and implementations of traits, we are not certain that the definitions are
927/// live at this stage. We record them in `unsolved_items` for later examination.
928fn maybe_record_as_seed<'tcx>(
929    tcx: TyCtxt<'tcx>,
930    owner_id: hir::OwnerId,
931    push_into_worklist: &mut impl FnMut(WorkItem),
932    unsolved_items: &mut Vec<LocalDefId>,
933) {
934    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
935    if let Some(comes_from_allow) = allow_dead_code {
936        push_into_worklist(WorkItem {
937            id: owner_id.def_id,
938            propagated: comes_from_allow,
939            own: comes_from_allow,
940        });
941    }
942
943    match tcx.def_kind(owner_id) {
944        DefKind::Enum => {
945            if let Some(comes_from_allow) = allow_dead_code {
946                let adt = tcx.adt_def(owner_id);
947                for variant in adt.variants().iter() {
948                    push_into_worklist(WorkItem {
949                        id: variant.def_id.expect_local(),
950                        propagated: comes_from_allow,
951                        own: comes_from_allow,
952                    });
953                }
954            }
955        }
956        DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => {
957            if allow_dead_code.is_none() {
958                let parent = tcx.local_parent(owner_id.def_id);
959                match tcx.def_kind(parent) {
960                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
961                    DefKind::Impl { of_trait: true } => {
962                        // We only care about associated items of traits,
963                        // because they cannot be visited directly,
964                        // so we later mark them as live if their corresponding traits
965                        // or trait items and self types are both live,
966                        // but inherent associated items can be visited and marked directly.
967                        unsolved_items.push(owner_id.def_id);
968                    }
969                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
970                }
971            }
972        }
973        DefKind::Impl { of_trait: true } if allow_dead_code.is_none() => {
974            unsolved_items.push(owner_id.def_id);
975        }
976        DefKind::GlobalAsm => {
977            // global_asm! is always live.
978            push_into_worklist(WorkItem {
979                id: owner_id.def_id,
980                propagated: ComesFromAllowExpect::No,
981                own: ComesFromAllowExpect::No,
982            });
983        }
984        DefKind::Const => {
985            if tcx.item_name(owner_id.def_id) == kw::Underscore {
986                // `const _` is always live, as that syntax only exists for the side effects
987                // of type checking and evaluating the constant expression, and marking them
988                // as dead code would defeat that purpose.
989                push_into_worklist(WorkItem {
990                    id: owner_id.def_id,
991                    propagated: ComesFromAllowExpect::No,
992                    own: ComesFromAllowExpect::No,
993                });
994            }
995        }
996        _ => {}
997    }
998}
999
1000#[derive(#[automatically_derived]
impl ::core::default::Default for DeferredSeeds {
    #[inline]
    fn default() -> Self {
        Self {
            pub_reachables: ::core::default::Default::default(),
            come_from_allow: ::core::default::Default::default(),
        }
    }
}Default)]
1001struct DeferredSeeds {
1002    pub_reachables: Vec<WorkItem>,
1003    come_from_allow: Vec<WorkItem>,
1004}
1005
1006struct SeedWorklists {
1007    worklist: Vec<WorkItem>,
1008    deferred_seeds: DeferredSeeds,
1009    unsolved_items: Vec<LocalDefId>,
1010}
1011
1012fn create_and_seed_worklist(tcx: TyCtxt<'_>) -> SeedWorklists {
1013    let mut unsolved_items = Vec::new();
1014    let mut deferred_seeds = DeferredSeeds::default();
1015    let mut worklist = Vec::new();
1016
1017    if let Some((def_id, _)) = tcx.entry_fn(())
1018        && let Some(local_def_id) = def_id.as_local()
1019    {
1020        worklist.push(WorkItem {
1021            id: local_def_id,
1022            propagated: ComesFromAllowExpect::No,
1023            own: ComesFromAllowExpect::No,
1024        });
1025    }
1026
1027    // Under `--test`, what `main` resolves to is the would-be entry point of a normal build,
1028    // so keep it live, unless a stripped user `#[rustc_main]` would have been the entry instead.
1029    if tcx.sess.is_test_crate()
1030        && !tcx.sess.removed_rustc_main_attr.load(Ordering::Relaxed)
1031        && let Some(main_def) = tcx.resolutions(()).main_def
1032        && let Some(def_id) = main_def.opt_fn_def_id()
1033        && let Some(local_def_id) = def_id.as_local()
1034    {
1035        worklist.push(WorkItem {
1036            id: local_def_id,
1037            propagated: ComesFromAllowExpect::No,
1038            own: ComesFromAllowExpect::No,
1039        });
1040    }
1041
1042    for (id, effective_vis) in tcx.effective_visibilities(()).iter() {
1043        if effective_vis.is_public_at_level(Level::Reachable) {
1044            deferred_seeds.pub_reachables.push(WorkItem {
1045                id: *id,
1046                propagated: ComesFromAllowExpect::No,
1047                own: ComesFromAllowExpect::No,
1048            });
1049        }
1050    }
1051
1052    let mut push_into_worklist = |work_item: WorkItem| match work_item.own {
1053        ComesFromAllowExpect::Yes => deferred_seeds.come_from_allow.push(work_item),
1054        ComesFromAllowExpect::No => worklist.push(work_item),
1055    };
1056    let crate_items = tcx.hir_crate_items(());
1057    for id in crate_items.owners() {
1058        maybe_record_as_seed(tcx, id, &mut push_into_worklist, &mut unsolved_items);
1059    }
1060
1061    SeedWorklists { worklist, deferred_seeds, unsolved_items }
1062}
1063
1064fn live_symbols_and_ignored_derived_traits(
1065    tcx: TyCtxt<'_>,
1066    (): (),
1067) -> Result<DeadCodeLivenessSummary, ErrorGuaranteed> {
1068    let SeedWorklists { worklist, deferred_seeds, unsolved_items } = create_and_seed_worklist(tcx);
1069    let mut symbol_visitor = MarkSymbolVisitor {
1070        worklist,
1071        tcx,
1072        maybe_typeck_results: None,
1073        scanned: Default::default(),
1074        live_symbols: Default::default(),
1075        repr_unconditionally_treats_fields_as_live: false,
1076        repr_has_repr_simd_or_scalable: false,
1077        in_pat: false,
1078        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
1079        ignored_derived_traits: Default::default(),
1080        propagated_comes_from_allow_expect: ComesFromAllowExpect::No,
1081        unsolved_items,
1082    };
1083    symbol_visitor.mark_live_symbols_and_ignored_derived_traits(true)?;
1084    let pre_deferred_seeding = DeadCodeLivenessSnapshot {
1085        live_symbols: symbol_visitor.live_symbols.clone(),
1086        ignored_derived_traits: symbol_visitor.ignored_derived_traits.clone(),
1087    };
1088
1089    if !deferred_seeds.pub_reachables.is_empty() {
1090        symbol_visitor.worklist.extend(deferred_seeds.pub_reachables);
1091        symbol_visitor.mark_live_symbols_and_ignored_derived_traits(true)?;
1092    }
1093
1094    if !deferred_seeds.come_from_allow.is_empty() {
1095        symbol_visitor.worklist.extend(deferred_seeds.come_from_allow);
1096        symbol_visitor.mark_live_symbols_and_ignored_derived_traits(false)?;
1097    }
1098
1099    Ok(DeadCodeLivenessSummary {
1100        pre_deferred_seeding,
1101        final_result: DeadCodeLivenessSnapshot {
1102            live_symbols: symbol_visitor.live_symbols,
1103            ignored_derived_traits: symbol_visitor.ignored_derived_traits,
1104        },
1105    })
1106}
1107
1108struct DeadItem {
1109    def_id: LocalDefId,
1110    name: Symbol,
1111    level_plus: (lint::Level, Option<StableLintExpectationId>),
1112}
1113
1114struct DeadVisitor<'tcx> {
1115    tcx: TyCtxt<'tcx>,
1116    target_lint: &'static Lint,
1117    live_symbols: &'tcx LocalDefIdSet,
1118    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1119}
1120
1121enum ShouldWarnAboutField {
1122    Yes,
1123    No,
1124}
1125
1126#[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) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ReportOn { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ReportOn {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportOn { }Eq)]
1127enum ReportOn {
1128    /// Report on something that hasn't got a proper name to refer to
1129    TupleField,
1130    /// Report on something that has got a name, which could be a field but also a method
1131    NamedField,
1132}
1133
1134impl<'tcx> DeadVisitor<'tcx> {
1135    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
1136        if self.live_symbols.contains(&field.did.expect_local()) {
1137            return ShouldWarnAboutField::No;
1138        }
1139        let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
1140        if field_type.is_phantom_data() {
1141            return ShouldWarnAboutField::No;
1142        }
1143        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
1144        if is_positional
1145            && self
1146                .tcx
1147                .layout_of(
1148                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
1149                        .as_query_input(field_type),
1150                )
1151                .map_or(true, |layout| layout.is_zst())
1152        {
1153            return ShouldWarnAboutField::No;
1154        }
1155        ShouldWarnAboutField::Yes
1156    }
1157
1158    fn def_lint_level_plus(
1159        &self,
1160        id: LocalDefId,
1161    ) -> (lint::Level, Option<StableLintExpectationId>) {
1162        let hir_id = self.tcx.local_def_id_to_hir_id(id);
1163        let level_spec = self.tcx.lint_level_spec_at_node(self.target_lint, hir_id);
1164        (level_spec.level(), level_spec.lint_id())
1165    }
1166
1167    fn fulfill_dead_code_expectations(&self, def_id: LocalDefId, include: bool) {
1168        let fulfill_if_expected = |node: DefId| {
1169            // Only consider local, dead symbols where lint level carries an expectation
1170            if let Some(node) = node.as_local()
1171                && !self.live_symbols.contains(&node)
1172                && let (_, Some(expectation)) = self.def_lint_level_plus(node)
1173            {
1174                // Same mechanism as LintContext::fulfill_expectation.
1175                self.tcx.dcx().fulfill_expectation(expectation);
1176            }
1177        };
1178
1179        if include {
1180            fulfill_if_expected(def_id.to_def_id());
1181        }
1182
1183        match self.tcx.def_kind(def_id) {
1184            DefKind::Struct | DefKind::Union | DefKind::Enum => {
1185                let adt = self.tcx.adt_def(def_id);
1186                for variant in adt.variants() {
1187                    if variant.def_id != def_id.to_def_id() {
1188                        fulfill_if_expected(variant.def_id);
1189                    }
1190                    for field in &variant.fields {
1191                        fulfill_if_expected(field.did);
1192                    }
1193                }
1194            }
1195            DefKind::Variant => {
1196                let parent_enum = self.tcx.local_parent(def_id);
1197                let variant = self.tcx.adt_def(parent_enum).variant_with_id(def_id.to_def_id());
1198                //Check to see if fields carry expectation
1199                for field in &variant.fields {
1200                    fulfill_if_expected(field.did);
1201                }
1202            }
1203            DefKind::Trait => {
1204                for &assoc_def_id in self.tcx.associated_item_def_ids(def_id) {
1205                    fulfill_if_expected(assoc_def_id);
1206                }
1207            }
1208            _ => {}
1209        }
1210    }
1211
1212    fn dead_code_pub_in_binary_note(&self) -> Option<DeadCodePubInBinaryNote> {
1213        self.target_lint.name.eq(DEAD_CODE_PUB_IN_BINARY.name).then_some(DeadCodePubInBinaryNote)
1214    }
1215
1216    // # Panics
1217    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
1218    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
1219    // first local def id.
1220    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
1221    // since those methods group by lint level before calling this method.
1222    fn lint_at_single_level(
1223        &self,
1224        dead_codes: &[&DeadItem],
1225        participle: &str,
1226        parent_item: Option<LocalDefId>,
1227        report_on: ReportOn,
1228    ) {
1229        let Some(&first_item) = dead_codes.first() else { return };
1230        let tcx = self.tcx;
1231
1232        let first_lint_level_plus = first_item.level_plus;
1233        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));
1234
1235        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1236        let spans: Vec<_> = dead_codes
1237            .iter()
1238            .map(|item| {
1239                let span = tcx.def_span(item.def_id);
1240                let ident_span = tcx.def_ident_span(item.def_id);
1241                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
1242                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
1243            })
1244            .collect();
1245
1246        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
1247        // `impl` blocks are "batched" and (unlike other batching) might
1248        // contain different kinds of associated items.
1249        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
1250            descr = "associated item"
1251        }
1252
1253        let num = dead_codes.len();
1254        let multiple = num > 6;
1255        let name_list = names.into();
1256
1257        let parent_info = parent_item.map(|parent_item| {
1258            let parent_descr = tcx.def_descr(parent_item.to_def_id());
1259            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1260                tcx.def_span(parent_item)
1261            } else {
1262                tcx.def_ident_span(parent_item).unwrap()
1263            };
1264            ParentInfo { num, descr, parent_descr, span }
1265        });
1266
1267        let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1268        // `ignored_derived_traits` is computed for the enum, not for the variants.
1269        if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1270            encl_def_id = tcx.local_parent(encl_def_id);
1271        }
1272
1273        let ignored_derived_impls =
1274            self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1275                let trait_list = ign_traits
1276                    .iter()
1277                    .map(|trait_id| self.tcx.item_name(*trait_id))
1278                    .collect::<Vec<_>>();
1279                let trait_list_len = trait_list.len();
1280                IgnoredDerivedImpls {
1281                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1282                    trait_list: trait_list.into(),
1283                    trait_list_len,
1284                }
1285            });
1286
1287        let diag = match report_on {
1288            ReportOn::TupleField => {
1289                let tuple_fields = if let Some(parent_id) = parent_item
1290                    && let node = tcx.hir_node_by_def_id(parent_id)
1291                    && let hir::Node::Item(hir::Item {
1292                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1293                        ..
1294                    }) = node
1295                {
1296                    *fields
1297                } else {
1298                    &[]
1299                };
1300
1301                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1302                    LocalDefIdSet::from_iter(
1303                        tuple_fields
1304                            .iter()
1305                            .skip(tuple_fields.len() - dead_codes.len())
1306                            .map(|f| f.def_id),
1307                    )
1308                } else {
1309                    LocalDefIdSet::default()
1310                };
1311
1312                let fields_suggestion =
1313                    // Suggest removal if all tuple fields are at the end.
1314                    // Otherwise suggest removal or changing to unit type
1315                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1316                        ChangeFields::Remove { num }
1317                    } else {
1318                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1319                    };
1320
1321                MultipleDeadCodes::UnusedTupleStructFields {
1322                    multiple,
1323                    num,
1324                    descr,
1325                    participle,
1326                    name_list,
1327                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1328                    change_fields_suggestion: fields_suggestion,
1329                    parent_info,
1330                    ignored_derived_impls,
1331                }
1332            }
1333            ReportOn::NamedField => {
1334                let enum_variants_with_same_name = dead_codes
1335                    .iter()
1336                    .filter_map(|dead_item| {
1337                        if let DefKind::AssocFn | DefKind::AssocConst =
1338                            tcx.def_kind(dead_item.def_id)
1339                            && let impl_did = tcx.local_parent(dead_item.def_id)
1340                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1341                            && let ty::Adt(maybe_enum, _) =
1342                                tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1343                            && maybe_enum.is_enum()
1344                            && let Some(variant) =
1345                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1346                        {
1347                            Some(crate::diagnostics::EnumVariantSameName {
1348                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1349                                dead_name: dead_item.name,
1350                                variant_span: tcx.def_span(variant.def_id),
1351                            })
1352                        } else {
1353                            None
1354                        }
1355                    })
1356                    .collect();
1357
1358                MultipleDeadCodes::DeadCodes {
1359                    multiple,
1360                    num,
1361                    descr,
1362                    participle,
1363                    name_list,
1364                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1365                    parent_info,
1366                    ignored_derived_impls,
1367                    enum_variants_with_same_name,
1368                }
1369            }
1370        };
1371
1372        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1373        self.tcx.emit_node_span_lint(self.target_lint, hir_id, MultiSpan::from_spans(spans), diag);
1374    }
1375
1376    fn warn_multiple(
1377        &self,
1378        def_id: LocalDefId,
1379        participle: &str,
1380        dead_codes: Vec<DeadItem>,
1381        report_on: ReportOn,
1382    ) {
1383        let mut dead_codes = dead_codes
1384            .iter()
1385            .filter(|v| !v.name.as_str().starts_with('_'))
1386            .collect::<Vec<&DeadItem>>();
1387        if dead_codes.is_empty() {
1388            return;
1389        }
1390        // FIXME: `dead_codes` should probably be morally equivalent to
1391        // `IndexMap<(Level, StableLintExpectationId), (DefId, Symbol)>`
1392        dead_codes.sort_by_key(|v| v.level_plus.0);
1393        for group in dead_codes.chunk_by(|a, b| a.level_plus == b.level_plus) {
1394            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1395        }
1396    }
1397
1398    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1399        let item = DeadItem {
1400            def_id: id,
1401            name: self.tcx.item_name(id.to_def_id()),
1402            level_plus: self.def_lint_level_plus(id),
1403        };
1404        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1405    }
1406
1407    fn check_definition(&mut self, def_id: LocalDefId) {
1408        if self.is_live_code(def_id) {
1409            return;
1410        }
1411        match self.tcx.def_kind(def_id) {
1412            DefKind::AssocConst
1413            | DefKind::AssocTy
1414            | DefKind::AssocFn
1415            | DefKind::Fn
1416            | DefKind::Static { .. }
1417            | DefKind::Const
1418            | DefKind::TyAlias
1419            | DefKind::Enum
1420            | DefKind::Union
1421            | DefKind::ForeignTy
1422            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1423            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1424            DefKind::Variant | DefKind::Field => ::rustc_span::macros::bug_impl(None,
    format_args!("should be handled specially"), Location::caller())bug!("should be handled specially"),
1425            _ => {}
1426        }
1427    }
1428
1429    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1430        // if we cannot get a name for the item, then we just assume that it is
1431        // live. I mean, we can't really emit a lint.
1432        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1433            return true;
1434        };
1435
1436        self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1437    }
1438}
1439
1440fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModId) {
1441    let Ok(DeadCodeLivenessSummary { pre_deferred_seeding, final_result }) =
1442        tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1443    else {
1444        return;
1445    };
1446
1447    let module_items = tcx.hir_module_items(module);
1448
1449    if tcx.crate_types().contains(&CrateType::Executable) {
1450        let is_unused_pub = |def_id: LocalDefId| {
1451            tcx.effective_visibilities(()).is_public_at_level(def_id, Level::Reachable)
1452                && !pre_deferred_seeding.live_symbols.contains(&def_id)
1453        };
1454
1455        lint_dead_codes(
1456            tcx,
1457            DEAD_CODE_PUB_IN_BINARY,
1458            module,
1459            &pre_deferred_seeding.live_symbols,
1460            &pre_deferred_seeding.ignored_derived_traits,
1461            module_items.free_items().filter(|free_item| is_unused_pub(free_item.owner_id.def_id)),
1462            module_items
1463                .foreign_items()
1464                .filter(|foreign_item| is_unused_pub(foreign_item.owner_id.def_id)),
1465        );
1466    }
1467
1468    lint_dead_codes(
1469        tcx,
1470        DEAD_CODE,
1471        module,
1472        &final_result.live_symbols,
1473        &final_result.ignored_derived_traits,
1474        module_items.free_items(),
1475        module_items.foreign_items(),
1476    );
1477}
1478
1479fn lint_dead_codes<'tcx>(
1480    tcx: TyCtxt<'tcx>,
1481    target_lint: &'static Lint,
1482    module: LocalModId,
1483    live_symbols: &'tcx LocalDefIdSet,
1484    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1485    free_items: impl Iterator<Item = ItemId>,
1486    foreign_items: impl Iterator<Item = ForeignItemId>,
1487) {
1488    let mut visitor = DeadVisitor { tcx, target_lint, live_symbols, ignored_derived_traits };
1489    for item in free_items {
1490        let def_kind = tcx.def_kind(item.owner_id);
1491
1492        let mut dead_codes = Vec::new();
1493        // Only diagnose unused assoc items in inherent impl and used trait,
1494        // for unused assoc items in impls of trait,
1495        // we have diagnosed them in the trait if they are unused,
1496        // for unused assoc items in unused trait,
1497        // we have diagnosed the unused trait.
1498        if def_kind == (DefKind::Impl { of_trait: false })
1499            || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1500        {
1501            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1502                if let Some(local_def_id) = def_id.as_local()
1503                    && !visitor.is_live_code(local_def_id)
1504                {
1505                    let name = tcx.item_name(def_id);
1506                    let level_plus = visitor.def_lint_level_plus(local_def_id);
1507                    dead_codes.push(DeadItem { def_id: local_def_id, name, level_plus });
1508                }
1509            }
1510        }
1511        if !dead_codes.is_empty() {
1512            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1513        }
1514
1515        if !live_symbols.contains(&item.owner_id.def_id) {
1516            let parent = tcx.local_parent(item.owner_id.def_id);
1517            if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1518                // We already have diagnosed something, but check parent's field for #[expect]
1519                visitor.fulfill_dead_code_expectations(item.owner_id.def_id, true);
1520                continue;
1521            }
1522            visitor.check_definition(item.owner_id.def_id);
1523            visitor.fulfill_dead_code_expectations(item.owner_id.def_id, false);
1524            continue;
1525        }
1526
1527        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1528            let adt = tcx.adt_def(item.owner_id);
1529            let mut dead_variants = Vec::new();
1530
1531            for variant in adt.variants() {
1532                let def_id = variant.def_id.expect_local();
1533                if !live_symbols.contains(&def_id) {
1534                    // Record to group diagnostics.
1535                    let level_plus = visitor.def_lint_level_plus(def_id);
1536                    dead_variants.push(DeadItem { def_id, name: variant.name, level_plus });
1537                    visitor.fulfill_dead_code_expectations(def_id, false);
1538                    continue;
1539                }
1540
1541                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1542                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1543                });
1544                let report_on =
1545                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1546                let dead_fields = variant
1547                    .fields
1548                    .iter()
1549                    .filter_map(|field| {
1550                        let def_id = field.did.expect_local();
1551                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1552                            let level_plus = visitor.def_lint_level_plus(def_id);
1553                            Some(DeadItem { def_id, name: field.name, level_plus })
1554                        } else {
1555                            None
1556                        }
1557                    })
1558                    .collect();
1559                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1560            }
1561
1562            visitor.warn_multiple(
1563                item.owner_id.def_id,
1564                "constructed",
1565                dead_variants,
1566                ReportOn::NamedField,
1567            );
1568        }
1569    }
1570
1571    for foreign_item in foreign_items {
1572        visitor.check_definition(foreign_item.owner_id.def_id);
1573    }
1574}
1575
1576pub(crate) fn provide(providers: &mut Providers) {
1577    *providers =
1578        Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1579}