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