]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/dead.rs
Auto merge of #107443 - cjgillot:generator-less-query, r=compiler-errors
[rust.git] / compiler / rustc_passes / src / dead.rs
1 // This implements the dead-code warning pass. It follows middle::reachable
2 // closely. The idea is that all reachable symbols are live, codes called
3 // from live codes are live, and everything else is dead.
4
5 use itertools::Itertools;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::MultiSpan;
8 use rustc_hir as hir;
9 use rustc_hir::def::{CtorOf, DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId};
11 use rustc_hir::intravisit::{self, Visitor};
12 use rustc_hir::{Node, PatKind, TyKind};
13 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::middle::privacy::Level;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
17 use rustc_session::lint;
18 use rustc_span::symbol::{sym, Symbol};
19 use std::mem;
20
21 use crate::errors::{
22     ChangeFieldsToBeOfUnitType, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo,
23     UselessAssignment,
24 };
25
26 // Any local node that may call something in its body block should be
27 // explored. For example, if it's a live Node::Item that is a
28 // function, then we should explore its block to check for codes that
29 // may need to be marked as live.
30 fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
31     matches!(
32         tcx.hir().find_by_def_id(def_id),
33         Some(
34             Node::Item(..)
35                 | Node::ImplItem(..)
36                 | Node::ForeignItem(..)
37                 | Node::TraitItem(..)
38                 | Node::Variant(..)
39                 | Node::AnonConst(..)
40         )
41     )
42 }
43
44 struct MarkSymbolVisitor<'tcx> {
45     worklist: Vec<LocalDefId>,
46     tcx: TyCtxt<'tcx>,
47     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
48     live_symbols: FxHashSet<LocalDefId>,
49     repr_has_repr_c: bool,
50     repr_has_repr_simd: bool,
51     in_pat: bool,
52     ignore_variant_stack: Vec<DefId>,
53     // maps from tuple struct constructors to tuple struct items
54     struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
55     // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
56     // and the span of their respective impl (i.e., part of the derive
57     // macro)
58     ignored_derived_traits: FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
59 }
60
61 impl<'tcx> MarkSymbolVisitor<'tcx> {
62     /// Gets the type-checking results for the current body.
63     /// As this will ICE if called outside bodies, only call when working with
64     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
65     #[track_caller]
66     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
67         self.maybe_typeck_results
68             .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
69     }
70
71     fn check_def_id(&mut self, def_id: DefId) {
72         if let Some(def_id) = def_id.as_local() {
73             if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) {
74                 self.worklist.push(def_id);
75             }
76             self.live_symbols.insert(def_id);
77         }
78     }
79
80     fn insert_def_id(&mut self, def_id: DefId) {
81         if let Some(def_id) = def_id.as_local() {
82             debug_assert!(!should_explore(self.tcx, def_id));
83             self.live_symbols.insert(def_id);
84         }
85     }
86
87     fn handle_res(&mut self, res: Res) {
88         match res {
89             Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, def_id) => {
90                 self.check_def_id(def_id);
91             }
92             _ if self.in_pat => {}
93             Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
94             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
95                 let variant_id = self.tcx.parent(ctor_def_id);
96                 let enum_id = self.tcx.parent(variant_id);
97                 self.check_def_id(enum_id);
98                 if !self.ignore_variant_stack.contains(&ctor_def_id) {
99                     self.check_def_id(variant_id);
100                 }
101             }
102             Res::Def(DefKind::Variant, variant_id) => {
103                 let enum_id = self.tcx.parent(variant_id);
104                 self.check_def_id(enum_id);
105                 if !self.ignore_variant_stack.contains(&variant_id) {
106                     self.check_def_id(variant_id);
107                 }
108             }
109             Res::Def(_, def_id) => self.check_def_id(def_id),
110             Res::SelfTyParam { trait_: t } => self.check_def_id(t),
111             Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
112             Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
113         }
114     }
115
116     fn lookup_and_handle_method(&mut self, id: hir::HirId) {
117         if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
118             self.check_def_id(def_id);
119         } else {
120             bug!("no type-dependent def for method");
121         }
122     }
123
124     fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
125         match self.typeck_results().expr_ty_adjusted(lhs).kind() {
126             ty::Adt(def, _) => {
127                 let index = self.typeck_results().field_index(hir_id);
128                 self.insert_def_id(def.non_enum_variant().fields[index].did);
129             }
130             ty::Tuple(..) => {}
131             _ => span_bug!(lhs.span, "named field access on non-ADT"),
132         }
133     }
134
135     #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
136     fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
137         if self
138             .typeck_results()
139             .expr_adjustments(expr)
140             .iter()
141             .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
142         {
143             self.visit_expr(expr);
144         } else if let hir::ExprKind::Field(base, ..) = expr.kind {
145             // Ignore write to field
146             self.handle_assign(base);
147         } else {
148             self.visit_expr(expr);
149         }
150     }
151
152     #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
153     fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
154         fn check_for_self_assign_helper<'tcx>(
155             typeck_results: &'tcx ty::TypeckResults<'tcx>,
156             lhs: &'tcx hir::Expr<'tcx>,
157             rhs: &'tcx hir::Expr<'tcx>,
158         ) -> bool {
159             match (&lhs.kind, &rhs.kind) {
160                 (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => {
161                     if let (Res::Local(id_l), Res::Local(id_r)) = (
162                         typeck_results.qpath_res(qpath_l, lhs.hir_id),
163                         typeck_results.qpath_res(qpath_r, rhs.hir_id),
164                     ) {
165                         if id_l == id_r {
166                             return true;
167                         }
168                     }
169                     return false;
170                 }
171                 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
172                     if ident_l == ident_r {
173                         return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
174                     }
175                     return false;
176                 }
177                 _ => {
178                     return false;
179                 }
180             }
181         }
182
183         if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
184             && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
185                 && !assign.span.from_expansion()
186         {
187                 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
188                 self.tcx.emit_spanned_lint(
189                     lint::builtin::DEAD_CODE,
190                     assign.hir_id,
191                     assign.span,
192                     UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) }
193                 )
194         }
195     }
196
197     fn handle_field_pattern_match(
198         &mut self,
199         lhs: &hir::Pat<'_>,
200         res: Res,
201         pats: &[hir::PatField<'_>],
202     ) {
203         let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
204             ty::Adt(adt, _) => adt.variant_of_res(res),
205             _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
206         };
207         for pat in pats {
208             if let PatKind::Wild = pat.pat.kind {
209                 continue;
210             }
211             let index = self.typeck_results().field_index(pat.hir_id);
212             self.insert_def_id(variant.fields[index].did);
213         }
214     }
215
216     fn handle_tuple_field_pattern_match(
217         &mut self,
218         lhs: &hir::Pat<'_>,
219         res: Res,
220         pats: &[hir::Pat<'_>],
221         dotdot: hir::DotDotPos,
222     ) {
223         let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
224             ty::Adt(adt, _) => adt.variant_of_res(res),
225             _ => span_bug!(lhs.span, "non-ADT in tuple struct pattern"),
226         };
227         let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
228         let first_n = pats.iter().enumerate().take(dotdot);
229         let missing = variant.fields.len() - pats.len();
230         let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
231         for (idx, pat) in first_n.chain(last_n) {
232             if let PatKind::Wild = pat.kind {
233                 continue;
234             }
235             self.insert_def_id(variant.fields[idx].did);
236         }
237     }
238
239     fn mark_live_symbols(&mut self) {
240         let mut scanned = FxHashSet::default();
241         while let Some(id) = self.worklist.pop() {
242             if !scanned.insert(id) {
243                 continue;
244             }
245
246             // in the case of tuple struct constructors we want to check the item, not the generated
247             // tuple struct constructor function
248             let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
249
250             if let Some(node) = self.tcx.hir().find_by_def_id(id) {
251                 self.live_symbols.insert(id);
252                 self.visit_node(node);
253             }
254         }
255     }
256
257     /// Automatically generated items marked with `rustc_trivial_field_reads`
258     /// will be ignored for the purposes of dead code analysis (see PR #85200
259     /// for discussion).
260     fn should_ignore_item(&mut self, def_id: DefId) -> bool {
261         if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
262             if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
263                 return false;
264             }
265
266             if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of)
267                 && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads)
268             {
269                 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap().subst_identity();
270                 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
271                     && let Some(adt_def_id) = adt_def.did().as_local()
272                 {
273                     self.ignored_derived_traits
274                         .entry(adt_def_id)
275                         .or_default()
276                         .push((trait_of, impl_of));
277                 }
278                 return true;
279             }
280         }
281
282         return false;
283     }
284
285     fn visit_node(&mut self, node: Node<'tcx>) {
286         if let Node::ImplItem(hir::ImplItem { owner_id, .. }) = node
287             && self.should_ignore_item(owner_id.to_def_id())
288         {
289             return;
290         }
291
292         let had_repr_c = self.repr_has_repr_c;
293         let had_repr_simd = self.repr_has_repr_simd;
294         self.repr_has_repr_c = false;
295         self.repr_has_repr_simd = false;
296         match node {
297             Node::Item(item) => match item.kind {
298                 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
299                     let def = self.tcx.adt_def(item.owner_id);
300                     self.repr_has_repr_c = def.repr().c();
301                     self.repr_has_repr_simd = def.repr().simd();
302
303                     intravisit::walk_item(self, &item)
304                 }
305                 hir::ItemKind::ForeignMod { .. } => {}
306                 _ => intravisit::walk_item(self, &item),
307             },
308             Node::TraitItem(trait_item) => {
309                 intravisit::walk_trait_item(self, trait_item);
310             }
311             Node::ImplItem(impl_item) => {
312                 let item = self.tcx.local_parent(impl_item.owner_id.def_id);
313                 if self.tcx.impl_trait_ref(item).is_none() {
314                     //// If it's a type whose items are live, then it's live, too.
315                     //// This is done to handle the case where, for example, the static
316                     //// method of a private type is used, but the type itself is never
317                     //// called directly.
318                     let self_ty = self.tcx.type_of(item);
319                     match *self_ty.kind() {
320                         ty::Adt(def, _) => self.check_def_id(def.did()),
321                         ty::Foreign(did) => self.check_def_id(did),
322                         ty::Dynamic(data, ..) => {
323                             if let Some(def_id) = data.principal_def_id() {
324                                 self.check_def_id(def_id)
325                             }
326                         }
327                         _ => {}
328                     }
329                 }
330                 intravisit::walk_impl_item(self, impl_item);
331             }
332             Node::ForeignItem(foreign_item) => {
333                 intravisit::walk_foreign_item(self, &foreign_item);
334             }
335             _ => {}
336         }
337         self.repr_has_repr_simd = had_repr_simd;
338         self.repr_has_repr_c = had_repr_c;
339     }
340
341     fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
342         if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
343             for field in fields {
344                 let index = self.typeck_results().field_index(field.hir_id);
345                 self.insert_def_id(adt.non_enum_variant().fields[index].did);
346             }
347         }
348     }
349 }
350
351 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
352     fn visit_nested_body(&mut self, body: hir::BodyId) {
353         let old_maybe_typeck_results =
354             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
355         let body = self.tcx.hir().body(body);
356         self.visit_body(body);
357         self.maybe_typeck_results = old_maybe_typeck_results;
358     }
359
360     fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) {
361         let tcx = self.tcx;
362         let has_repr_c = self.repr_has_repr_c;
363         let has_repr_simd = self.repr_has_repr_simd;
364         let live_fields = def.fields().iter().filter_map(|f| {
365             let def_id = f.def_id;
366             if has_repr_c || (f.is_positional() && has_repr_simd) {
367                 return Some(def_id);
368             }
369             if !tcx.visibility(f.hir_id.owner.def_id).is_public() {
370                 return None;
371             }
372             if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
373         });
374         self.live_symbols.extend(live_fields);
375
376         intravisit::walk_struct_def(self, def);
377     }
378
379     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
380         match expr.kind {
381             hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
382                 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
383                 self.handle_res(res);
384             }
385             hir::ExprKind::MethodCall(..) => {
386                 self.lookup_and_handle_method(expr.hir_id);
387             }
388             hir::ExprKind::Field(ref lhs, ..) => {
389                 self.handle_field_access(&lhs, expr.hir_id);
390             }
391             hir::ExprKind::Struct(ref qpath, ref fields, _) => {
392                 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
393                 self.handle_res(res);
394                 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
395                     self.mark_as_used_if_union(*adt, fields);
396                 }
397             }
398             _ => (),
399         }
400
401         intravisit::walk_expr(self, expr);
402     }
403
404     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
405         // Inside the body, ignore constructions of variants
406         // necessary for the pattern to match. Those construction sites
407         // can't be reached unless the variant is constructed elsewhere.
408         let len = self.ignore_variant_stack.len();
409         self.ignore_variant_stack.extend(arm.pat.necessary_variants());
410         intravisit::walk_arm(self, arm);
411         self.ignore_variant_stack.truncate(len);
412     }
413
414     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
415         self.in_pat = true;
416         match pat.kind {
417             PatKind::Struct(ref path, ref fields, _) => {
418                 let res = self.typeck_results().qpath_res(path, pat.hir_id);
419                 self.handle_field_pattern_match(pat, res, fields);
420             }
421             PatKind::Path(ref qpath) => {
422                 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
423                 self.handle_res(res);
424             }
425             PatKind::TupleStruct(ref qpath, ref fields, dotdot) => {
426                 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
427                 self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
428             }
429             _ => (),
430         }
431
432         intravisit::walk_pat(self, pat);
433         self.in_pat = false;
434     }
435
436     fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) {
437         self.handle_res(path.res);
438         intravisit::walk_path(self, path);
439     }
440
441     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
442         if let TyKind::OpaqueDef(item_id, _, _) = ty.kind {
443             let item = self.tcx.hir().item(item_id);
444             intravisit::walk_item(self, item);
445         }
446         intravisit::walk_ty(self, ty);
447     }
448
449     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
450         // When inline const blocks are used in pattern position, paths
451         // referenced by it should be considered as used.
452         let in_pat = mem::replace(&mut self.in_pat, false);
453
454         self.live_symbols.insert(c.def_id);
455         intravisit::walk_anon_const(self, c);
456
457         self.in_pat = in_pat;
458     }
459 }
460
461 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
462     fn has_lang_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
463         tcx.has_attr(def_id.to_def_id(), sym::lang)
464             // Stable attribute for #[lang = "panic_impl"]
465             || tcx.has_attr(def_id.to_def_id(), sym::panic_handler)
466     }
467
468     fn has_allow_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
469         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
470         tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0 == lint::Allow
471     }
472
473     fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
474         tcx.def_kind(def_id).has_codegen_attrs() && {
475             let cg_attrs = tcx.codegen_fn_attrs(def_id);
476
477             // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
478             // forcefully, e.g., for placing it in a specific section.
479             cg_attrs.contains_extern_indicator()
480                 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED)
481                 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
482         }
483     }
484
485     has_allow_dead_code(tcx, def_id)
486         || has_used_like_attr(tcx, def_id)
487         || has_lang_attr(tcx, def_id)
488 }
489
490 // These check_* functions seeds items that
491 //   1) We want to explicitly consider as live:
492 //     * Item annotated with #[allow(dead_code)]
493 //         - This is done so that if we want to suppress warnings for a
494 //           group of dead functions, we only have to annotate the "root".
495 //           For example, if both `f` and `g` are dead and `f` calls `g`,
496 //           then annotating `f` with `#[allow(dead_code)]` will suppress
497 //           warning for both `f` and `g`.
498 //     * Item annotated with #[lang=".."]
499 //         - This is because lang items are always callable from elsewhere.
500 //   or
501 //   2) We are not sure to be live or not
502 //     * Implementations of traits and trait methods
503 fn check_item<'tcx>(
504     tcx: TyCtxt<'tcx>,
505     worklist: &mut Vec<LocalDefId>,
506     struct_constructors: &mut FxHashMap<LocalDefId, LocalDefId>,
507     id: hir::ItemId,
508 ) {
509     let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id);
510     if allow_dead_code {
511         worklist.push(id.owner_id.def_id);
512     }
513
514     match tcx.def_kind(id.owner_id) {
515         DefKind::Enum => {
516             let item = tcx.hir().item(id);
517             if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
518                 if allow_dead_code {
519                     worklist.extend(enum_def.variants.iter().map(|variant| variant.def_id));
520                 }
521
522                 for variant in enum_def.variants {
523                     if let Some(ctor_def_id) = variant.data.ctor_def_id() {
524                         struct_constructors.insert(ctor_def_id, variant.def_id);
525                     }
526                 }
527             }
528         }
529         DefKind::Impl => {
530             let of_trait = tcx.impl_trait_ref(id.owner_id);
531
532             if of_trait.is_some() {
533                 worklist.push(id.owner_id.def_id);
534             }
535
536             // get DefIds from another query
537             let local_def_ids = tcx
538                 .associated_item_def_ids(id.owner_id)
539                 .iter()
540                 .filter_map(|def_id| def_id.as_local());
541
542             // And we access the Map here to get HirId from LocalDefId
543             for id in local_def_ids {
544                 if of_trait.is_some() || has_allow_dead_code_or_lang_attr(tcx, id) {
545                     worklist.push(id);
546                 }
547             }
548         }
549         DefKind::Struct => {
550             let item = tcx.hir().item(id);
551             if let hir::ItemKind::Struct(ref variant_data, _) = item.kind
552                 && let Some(ctor_def_id) = variant_data.ctor_def_id()
553             {
554                 struct_constructors.insert(ctor_def_id, item.owner_id.def_id);
555             }
556         }
557         DefKind::GlobalAsm => {
558             // global_asm! is always live.
559             worklist.push(id.owner_id.def_id);
560         }
561         _ => {}
562     }
563 }
564
565 fn check_trait_item(tcx: TyCtxt<'_>, worklist: &mut Vec<LocalDefId>, id: hir::TraitItemId) {
566     use hir::TraitItemKind::{Const, Fn};
567     if matches!(tcx.def_kind(id.owner_id), DefKind::AssocConst | DefKind::AssocFn) {
568         let trait_item = tcx.hir().trait_item(id);
569         if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
570             && has_allow_dead_code_or_lang_attr(tcx, trait_item.owner_id.def_id)
571         {
572             worklist.push(trait_item.owner_id.def_id);
573         }
574     }
575 }
576
577 fn check_foreign_item(tcx: TyCtxt<'_>, worklist: &mut Vec<LocalDefId>, id: hir::ForeignItemId) {
578     if matches!(tcx.def_kind(id.owner_id), DefKind::Static(_) | DefKind::Fn)
579         && has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id)
580     {
581         worklist.push(id.owner_id.def_id);
582     }
583 }
584
585 fn create_and_seed_worklist(
586     tcx: TyCtxt<'_>,
587 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
588     let effective_visibilities = &tcx.effective_visibilities(());
589     // see `MarkSymbolVisitor::struct_constructors`
590     let mut struct_constructors = Default::default();
591     let mut worklist = effective_visibilities
592         .iter()
593         .filter_map(|(&id, effective_vis)| {
594             effective_vis.is_public_at_level(Level::Reachable).then_some(id)
595         })
596         // Seed entry point
597         .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
598         .collect::<Vec<_>>();
599
600     let crate_items = tcx.hir_crate_items(());
601     for id in crate_items.items() {
602         check_item(tcx, &mut worklist, &mut struct_constructors, id);
603     }
604
605     for id in crate_items.trait_items() {
606         check_trait_item(tcx, &mut worklist, id);
607     }
608
609     for id in crate_items.foreign_items() {
610         check_foreign_item(tcx, &mut worklist, id);
611     }
612
613     (worklist, struct_constructors)
614 }
615
616 fn live_symbols_and_ignored_derived_traits(
617     tcx: TyCtxt<'_>,
618     (): (),
619 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
620     let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
621     let mut symbol_visitor = MarkSymbolVisitor {
622         worklist,
623         tcx,
624         maybe_typeck_results: None,
625         live_symbols: Default::default(),
626         repr_has_repr_c: false,
627         repr_has_repr_simd: false,
628         in_pat: false,
629         ignore_variant_stack: vec![],
630         struct_constructors,
631         ignored_derived_traits: FxHashMap::default(),
632     };
633     symbol_visitor.mark_live_symbols();
634     (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
635 }
636
637 struct DeadVariant {
638     def_id: LocalDefId,
639     name: Symbol,
640     level: lint::Level,
641 }
642
643 struct DeadVisitor<'tcx> {
644     tcx: TyCtxt<'tcx>,
645     live_symbols: &'tcx FxHashSet<LocalDefId>,
646     ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
647 }
648
649 enum ShouldWarnAboutField {
650     Yes(bool), // positional?
651     No,
652 }
653
654 impl<'tcx> DeadVisitor<'tcx> {
655     fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
656         if self.live_symbols.contains(&field.did.expect_local()) {
657             return ShouldWarnAboutField::No;
658         }
659         let field_type = self.tcx.type_of(field.did);
660         if field_type.is_phantom_data() {
661             return ShouldWarnAboutField::No;
662         }
663         let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
664         if is_positional
665             && self
666                 .tcx
667                 .layout_of(self.tcx.param_env(field.did).and(field_type))
668                 .map_or(true, |layout| layout.is_zst())
669         {
670             return ShouldWarnAboutField::No;
671         }
672         ShouldWarnAboutField::Yes(is_positional)
673     }
674
675     fn warn_multiple_dead_codes(
676         &self,
677         dead_codes: &[LocalDefId],
678         participle: &str,
679         parent_item: Option<LocalDefId>,
680         is_positional: bool,
681     ) {
682         let Some(&first_id) = dead_codes.first() else {
683             return;
684         };
685         let tcx = self.tcx;
686         let names: Vec<_> =
687             dead_codes.iter().map(|&def_id| tcx.item_name(def_id.to_def_id())).collect();
688         let spans: Vec<_> = dead_codes
689             .iter()
690             .map(|&def_id| match tcx.def_ident_span(def_id) {
691                 Some(s) => s.with_ctxt(tcx.def_span(def_id).ctxt()),
692                 None => tcx.def_span(def_id),
693             })
694             .collect();
695
696         let descr = tcx.def_kind(first_id).descr(first_id.to_def_id());
697         let num = dead_codes.len();
698         let multiple = num > 6;
699         let name_list = names.into();
700
701         let lint = if is_positional {
702             lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS
703         } else {
704             lint::builtin::DEAD_CODE
705         };
706
707         let parent_info = if let Some(parent_item) = parent_item {
708             let parent_descr = tcx.def_kind(parent_item).descr(parent_item.to_def_id());
709             Some(ParentInfo {
710                 num,
711                 descr,
712                 parent_descr,
713                 span: tcx.def_ident_span(parent_item).unwrap(),
714             })
715         } else {
716             None
717         };
718
719         let encl_def_id = parent_item.unwrap_or(first_id);
720         let ignored_derived_impls =
721             if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
722                 let trait_list = ign_traits
723                     .iter()
724                     .map(|(trait_id, _)| self.tcx.item_name(*trait_id))
725                     .collect::<Vec<_>>();
726                 let trait_list_len = trait_list.len();
727                 Some(IgnoredDerivedImpls {
728                     name: self.tcx.item_name(encl_def_id.to_def_id()),
729                     trait_list: trait_list.into(),
730                     trait_list_len,
731                 })
732             } else {
733                 None
734             };
735
736         let diag = if is_positional {
737             MultipleDeadCodes::UnusedTupleStructFields {
738                 multiple,
739                 num,
740                 descr,
741                 participle,
742                 name_list,
743                 change_fields_suggestion: ChangeFieldsToBeOfUnitType { num, spans: spans.clone() },
744                 parent_info,
745                 ignored_derived_impls,
746             }
747         } else {
748             MultipleDeadCodes::DeadCodes {
749                 multiple,
750                 num,
751                 descr,
752                 participle,
753                 name_list,
754                 parent_info,
755                 ignored_derived_impls,
756             }
757         };
758
759         self.tcx.emit_spanned_lint(
760             lint,
761             tcx.hir().local_def_id_to_hir_id(first_id),
762             MultiSpan::from_spans(spans),
763             diag,
764         );
765     }
766
767     fn warn_dead_fields_and_variants(
768         &self,
769         def_id: LocalDefId,
770         participle: &str,
771         dead_codes: Vec<DeadVariant>,
772         is_positional: bool,
773     ) {
774         let mut dead_codes = dead_codes
775             .iter()
776             .filter(|v| !v.name.as_str().starts_with('_'))
777             .collect::<Vec<&DeadVariant>>();
778         if dead_codes.is_empty() {
779             return;
780         }
781         dead_codes.sort_by_key(|v| v.level);
782         for (_, group) in &dead_codes.into_iter().group_by(|v| v.level) {
783             self.warn_multiple_dead_codes(
784                 &group.map(|v| v.def_id).collect::<Vec<_>>(),
785                 participle,
786                 Some(def_id),
787                 is_positional,
788             );
789         }
790     }
791
792     fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
793         self.warn_multiple_dead_codes(&[id], participle, None, false);
794     }
795
796     fn check_definition(&mut self, def_id: LocalDefId) {
797         if self.live_symbols.contains(&def_id) {
798             return;
799         }
800         if has_allow_dead_code_or_lang_attr(self.tcx, def_id) {
801             return;
802         }
803         let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
804             return
805         };
806         if name.as_str().starts_with('_') {
807             return;
808         }
809         match self.tcx.def_kind(def_id) {
810             DefKind::AssocConst
811             | DefKind::AssocFn
812             | DefKind::Fn
813             | DefKind::Static(_)
814             | DefKind::Const
815             | DefKind::TyAlias
816             | DefKind::Enum
817             | DefKind::Union
818             | DefKind::ForeignTy => self.warn_dead_code(def_id, "used"),
819             DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
820             DefKind::Variant | DefKind::Field => bug!("should be handled specially"),
821             _ => {}
822         }
823     }
824 }
825
826 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
827     let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
828     let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
829
830     let module_items = tcx.hir_module_items(module);
831
832     for item in module_items.items() {
833         if !live_symbols.contains(&item.owner_id.def_id) {
834             let parent = tcx.local_parent(item.owner_id.def_id);
835             if parent != module && !live_symbols.contains(&parent) {
836                 // We already have diagnosed something.
837                 continue;
838             }
839             visitor.check_definition(item.owner_id.def_id);
840             continue;
841         }
842
843         let def_kind = tcx.def_kind(item.owner_id);
844         if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
845             let adt = tcx.adt_def(item.owner_id);
846             let mut dead_variants = Vec::new();
847
848             for variant in adt.variants() {
849                 let def_id = variant.def_id.expect_local();
850                 if !live_symbols.contains(&def_id) {
851                     // Record to group diagnostics.
852                     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
853                     let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0;
854                     dead_variants.push(DeadVariant { def_id, name: variant.name, level });
855                     continue;
856                 }
857
858                 let mut is_positional = false;
859                 let dead_fields = variant
860                     .fields
861                     .iter()
862                     .filter_map(|field| {
863                         let def_id = field.did.expect_local();
864                         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
865                         if let ShouldWarnAboutField::Yes(is_pos) =
866                             visitor.should_warn_about_field(&field)
867                         {
868                             let level = tcx
869                                 .lint_level_at_node(
870                                     if is_pos {
871                                         is_positional = true;
872                                         lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS
873                                     } else {
874                                         lint::builtin::DEAD_CODE
875                                     },
876                                     hir_id,
877                                 )
878                                 .0;
879                             Some(DeadVariant { def_id, name: field.name, level })
880                         } else {
881                             None
882                         }
883                     })
884                     .collect();
885                 visitor.warn_dead_fields_and_variants(def_id, "read", dead_fields, is_positional)
886             }
887
888             visitor.warn_dead_fields_and_variants(
889                 item.owner_id.def_id,
890                 "constructed",
891                 dead_variants,
892                 false,
893             );
894         }
895     }
896
897     for impl_item in module_items.impl_items() {
898         visitor.check_definition(impl_item.owner_id.def_id);
899     }
900
901     for foreign_item in module_items.foreign_items() {
902         visitor.check_definition(foreign_item.owner_id.def_id);
903     }
904
905     // We do not warn trait items.
906 }
907
908 pub(crate) fn provide(providers: &mut Providers) {
909     *providers =
910         Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
911 }