]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/dead.rs
e136bb000919e18a2f7190088191a5aea7bedc2a
[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 rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::pluralize;
7 use rustc_hir as hir;
8 use rustc_hir::def::{CtorOf, DefKind, Res};
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::intravisit::{self, Visitor};
11 use rustc_hir::{Node, PatKind, TyKind};
12 use rustc_middle::hir::nested_filter;
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 rustc_span::Span;
20 use std::mem;
21
22 // Any local node that may call something in its body block should be
23 // explored. For example, if it's a live Node::Item that is a
24 // function, then we should explore its block to check for codes that
25 // may need to be marked as live.
26 fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
27     matches!(
28         tcx.hir().find_by_def_id(def_id),
29         Some(
30             Node::Item(..)
31                 | Node::ImplItem(..)
32                 | Node::ForeignItem(..)
33                 | Node::TraitItem(..)
34                 | Node::Variant(..)
35                 | Node::AnonConst(..)
36         )
37     )
38 }
39
40 struct MarkSymbolVisitor<'tcx> {
41     worklist: Vec<LocalDefId>,
42     tcx: TyCtxt<'tcx>,
43     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
44     live_symbols: FxHashSet<LocalDefId>,
45     repr_has_repr_c: 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, _) => {
85                 self.check_def_id(res.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::SelfTy { trait_: t, alias_to: i } => {
105                 if let Some(t) = t {
106                     self.check_def_id(t);
107                 }
108                 if let Some((i, _)) = i {
109                     self.check_def_id(i);
110                 }
111             }
112             Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
113             _ => {
114                 self.check_def_id(res.def_id());
115             }
116         }
117     }
118
119     fn lookup_and_handle_method(&mut self, id: hir::HirId) {
120         if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
121             self.check_def_id(def_id);
122         } else {
123             bug!("no type-dependent def for method");
124         }
125     }
126
127     fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
128         match self.typeck_results().expr_ty_adjusted(lhs).kind() {
129             ty::Adt(def, _) => {
130                 let index = self.tcx.field_index(hir_id, self.typeck_results());
131                 self.insert_def_id(def.non_enum_variant().fields[index].did);
132             }
133             ty::Tuple(..) => {}
134             _ => span_bug!(lhs.span, "named field access on non-ADT"),
135         }
136     }
137
138     #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
139     fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
140         if self
141             .typeck_results()
142             .expr_adjustments(expr)
143             .iter()
144             .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
145         {
146             self.visit_expr(expr);
147         } else if let hir::ExprKind::Field(base, ..) = expr.kind {
148             // Ignore write to field
149             self.handle_assign(base);
150         } else {
151             self.visit_expr(expr);
152         }
153     }
154
155     #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
156     fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
157         fn check_for_self_assign_helper<'tcx>(
158             typeck_results: &'tcx ty::TypeckResults<'tcx>,
159             lhs: &'tcx hir::Expr<'tcx>,
160             rhs: &'tcx hir::Expr<'tcx>,
161         ) -> bool {
162             match (&lhs.kind, &rhs.kind) {
163                 (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => {
164                     if let (Res::Local(id_l), Res::Local(id_r)) = (
165                         typeck_results.qpath_res(qpath_l, lhs.hir_id),
166                         typeck_results.qpath_res(qpath_r, rhs.hir_id),
167                     ) {
168                         if id_l == id_r {
169                             return true;
170                         }
171                     }
172                     return false;
173                 }
174                 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
175                     if ident_l == ident_r {
176                         return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
177                     }
178                     return false;
179                 }
180                 _ => {
181                     return false;
182                 }
183             }
184         }
185
186         if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind {
187             if check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
188                 && !assign.span.from_expansion()
189             {
190                 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
191                 self.tcx.struct_span_lint_hir(
192                     lint::builtin::DEAD_CODE,
193                     assign.hir_id,
194                     assign.span,
195                     |lint| {
196                         lint.build(&format!(
197                             "useless assignment of {} of type `{}` to itself",
198                             if is_field_assign { "field" } else { "variable" },
199                             self.typeck_results().expr_ty(lhs),
200                         ))
201                         .emit();
202                     },
203                 )
204             }
205         }
206     }
207
208     fn handle_field_pattern_match(
209         &mut self,
210         lhs: &hir::Pat<'_>,
211         res: Res,
212         pats: &[hir::PatField<'_>],
213     ) {
214         let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
215             ty::Adt(adt, _) => adt.variant_of_res(res),
216             _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
217         };
218         for pat in pats {
219             if let PatKind::Wild = pat.pat.kind {
220                 continue;
221             }
222             let index = self.tcx.field_index(pat.hir_id, self.typeck_results());
223             self.insert_def_id(variant.fields[index].did);
224         }
225     }
226
227     fn mark_live_symbols(&mut self) {
228         let mut scanned = FxHashSet::default();
229         while let Some(id) = self.worklist.pop() {
230             if !scanned.insert(id) {
231                 continue;
232             }
233
234             // in the case of tuple struct constructors we want to check the item, not the generated
235             // tuple struct constructor function
236             let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
237
238             if let Some(node) = self.tcx.hir().find_by_def_id(id) {
239                 self.live_symbols.insert(id);
240                 self.visit_node(node);
241             }
242         }
243     }
244
245     /// Automatically generated items marked with `rustc_trivial_field_reads`
246     /// will be ignored for the purposes of dead code analysis (see PR #85200
247     /// for discussion).
248     fn should_ignore_item(&mut self, def_id: DefId) -> bool {
249         if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
250             if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
251                 return false;
252             }
253
254             if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of) {
255                 if self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads) {
256                     let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap();
257                     if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() {
258                         if let Some(adt_def_id) = adt_def.did().as_local() {
259                             self.ignored_derived_traits
260                                 .entry(adt_def_id)
261                                 .or_default()
262                                 .push((trait_of, impl_of));
263                         }
264                     }
265                     return true;
266                 }
267             }
268         }
269
270         return false;
271     }
272
273     fn visit_node(&mut self, node: Node<'tcx>) {
274         if let Some(item_def_id) = match node {
275             Node::ImplItem(hir::ImplItem { def_id, .. }) => Some(def_id.to_def_id()),
276             _ => None,
277         } {
278             if self.should_ignore_item(item_def_id) {
279                 return;
280             }
281         }
282
283         let had_repr_c = self.repr_has_repr_c;
284         self.repr_has_repr_c = false;
285         match node {
286             Node::Item(item) => match item.kind {
287                 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
288                     let def = self.tcx.adt_def(item.def_id);
289                     self.repr_has_repr_c = def.repr().c();
290
291                     intravisit::walk_item(self, &item);
292                 }
293                 hir::ItemKind::Enum(..) => {
294                     intravisit::walk_item(self, &item);
295                 }
296                 hir::ItemKind::ForeignMod { .. } => {}
297                 _ => {
298                     intravisit::walk_item(self, &item);
299                 }
300             },
301             Node::TraitItem(trait_item) => {
302                 intravisit::walk_trait_item(self, trait_item);
303             }
304             Node::ImplItem(impl_item) => {
305                 intravisit::walk_impl_item(self, impl_item);
306             }
307             Node::ForeignItem(foreign_item) => {
308                 intravisit::walk_foreign_item(self, &foreign_item);
309             }
310             _ => {}
311         }
312         self.repr_has_repr_c = had_repr_c;
313     }
314
315     fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
316         if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
317             for field in fields {
318                 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
319                 self.insert_def_id(adt.non_enum_variant().fields[index].did);
320             }
321         }
322     }
323 }
324
325 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
326     fn visit_nested_body(&mut self, body: hir::BodyId) {
327         let old_maybe_typeck_results =
328             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
329         let body = self.tcx.hir().body(body);
330         self.visit_body(body);
331         self.maybe_typeck_results = old_maybe_typeck_results;
332     }
333
334     fn visit_variant_data(
335         &mut self,
336         def: &'tcx hir::VariantData<'tcx>,
337         _: Symbol,
338         _: &hir::Generics<'_>,
339         _: hir::HirId,
340         _: rustc_span::Span,
341     ) {
342         let tcx = self.tcx;
343         let has_repr_c = self.repr_has_repr_c;
344         let live_fields = def.fields().iter().filter_map(|f| {
345             let def_id = tcx.hir().local_def_id(f.hir_id);
346             if has_repr_c {
347                 return Some(def_id);
348             }
349             if !tcx.visibility(f.hir_id.owner).is_public() {
350                 return None;
351             }
352             if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
353         });
354         self.live_symbols.extend(live_fields);
355
356         intravisit::walk_struct_def(self, def);
357     }
358
359     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
360         match expr.kind {
361             hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
362                 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
363                 self.handle_res(res);
364             }
365             hir::ExprKind::MethodCall(..) => {
366                 self.lookup_and_handle_method(expr.hir_id);
367             }
368             hir::ExprKind::Field(ref lhs, ..) => {
369                 self.handle_field_access(&lhs, expr.hir_id);
370             }
371             hir::ExprKind::Struct(ref qpath, ref fields, _) => {
372                 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
373                 self.handle_res(res);
374                 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
375                     self.mark_as_used_if_union(*adt, fields);
376                 }
377             }
378             _ => (),
379         }
380
381         intravisit::walk_expr(self, expr);
382     }
383
384     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
385         // Inside the body, ignore constructions of variants
386         // necessary for the pattern to match. Those construction sites
387         // can't be reached unless the variant is constructed elsewhere.
388         let len = self.ignore_variant_stack.len();
389         self.ignore_variant_stack.extend(arm.pat.necessary_variants());
390         intravisit::walk_arm(self, arm);
391         self.ignore_variant_stack.truncate(len);
392     }
393
394     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
395         self.in_pat = true;
396         match pat.kind {
397             PatKind::Struct(ref path, ref fields, _) => {
398                 let res = self.typeck_results().qpath_res(path, pat.hir_id);
399                 self.handle_field_pattern_match(pat, res, fields);
400             }
401             PatKind::Path(ref qpath) => {
402                 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
403                 self.handle_res(res);
404             }
405             _ => (),
406         }
407
408         intravisit::walk_pat(self, pat);
409         self.in_pat = false;
410     }
411
412     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
413         self.handle_res(path.res);
414         intravisit::walk_path(self, path);
415     }
416
417     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
418         if let TyKind::OpaqueDef(item_id, _) = ty.kind {
419             let item = self.tcx.hir().item(item_id);
420             intravisit::walk_item(self, item);
421         }
422         intravisit::walk_ty(self, ty);
423     }
424
425     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
426         // When inline const blocks are used in pattern position, paths
427         // referenced by it should be considered as used.
428         let in_pat = mem::replace(&mut self.in_pat, false);
429
430         self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
431         intravisit::walk_anon_const(self, c);
432
433         self.in_pat = in_pat;
434     }
435 }
436
437 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
438     let attrs = tcx.hir().attrs(id);
439     if tcx.sess.contains_name(attrs, sym::lang) {
440         return true;
441     }
442
443     // Stable attribute for #[lang = "panic_impl"]
444     if tcx.sess.contains_name(attrs, sym::panic_handler) {
445         return true;
446     }
447
448     // (To be) stable attribute for #[lang = "oom"]
449     if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
450         return true;
451     }
452
453     let def_id = tcx.hir().local_def_id(id);
454     if tcx.def_kind(def_id).has_codegen_attrs() {
455         let cg_attrs = tcx.codegen_fn_attrs(def_id);
456
457         // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
458         // forcefully, e.g., for placing it in a specific section.
459         if cg_attrs.contains_extern_indicator()
460             || cg_attrs.flags.contains(CodegenFnAttrFlags::USED)
461             || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
462         {
463             return true;
464         }
465     }
466
467     tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
468 }
469
470 // These check_* functions seeds items that
471 //   1) We want to explicitly consider as live:
472 //     * Item annotated with #[allow(dead_code)]
473 //         - This is done so that if we want to suppress warnings for a
474 //           group of dead functions, we only have to annotate the "root".
475 //           For example, if both `f` and `g` are dead and `f` calls `g`,
476 //           then annotating `f` with `#[allow(dead_code)]` will suppress
477 //           warning for both `f` and `g`.
478 //     * Item annotated with #[lang=".."]
479 //         - This is because lang items are always callable from elsewhere.
480 //   or
481 //   2) We are not sure to be live or not
482 //     * Implementations of traits and trait methods
483 fn check_item<'tcx>(
484     tcx: TyCtxt<'tcx>,
485     worklist: &mut Vec<LocalDefId>,
486     struct_constructors: &mut FxHashMap<LocalDefId, LocalDefId>,
487     id: hir::ItemId,
488 ) {
489     let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.hir_id());
490     if allow_dead_code {
491         worklist.push(id.def_id);
492     }
493
494     match tcx.hir().def_kind(id.def_id) {
495         DefKind::Enum => {
496             let item = tcx.hir().item(id);
497             if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
498                 let hir = tcx.hir();
499                 if allow_dead_code {
500                     worklist.extend(
501                         enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
502                     );
503                 }
504
505                 for variant in enum_def.variants {
506                     if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
507                         struct_constructors
508                             .insert(hir.local_def_id(ctor_hir_id), hir.local_def_id(variant.id));
509                     }
510                 }
511             }
512         }
513         DefKind::Impl => {
514             let item = tcx.hir().item(id);
515             if let hir::ItemKind::Impl(hir::Impl { ref of_trait, items, .. }) = item.kind {
516                 if of_trait.is_some() {
517                     worklist.push(item.def_id);
518                 }
519                 for impl_item_ref in *items {
520                     let impl_item = tcx.hir().impl_item(impl_item_ref.id);
521                     if of_trait.is_some()
522                         || has_allow_dead_code_or_lang_attr(tcx, impl_item.hir_id())
523                     {
524                         worklist.push(impl_item_ref.id.def_id);
525                     }
526                 }
527             }
528         }
529         DefKind::Struct => {
530             let item = tcx.hir().item(id);
531             if let hir::ItemKind::Struct(ref variant_data, _) = item.kind {
532                 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
533                     struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.def_id);
534                 }
535             }
536         }
537         DefKind::GlobalAsm => {
538             // global_asm! is always live.
539             worklist.push(id.def_id);
540         }
541         _ => {}
542     }
543 }
544
545 fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec<LocalDefId>, id: hir::TraitItemId) {
546     use hir::TraitItemKind::{Const, Fn};
547     if matches!(tcx.hir().def_kind(id.def_id), DefKind::AssocConst | DefKind::AssocFn) {
548         let trait_item = tcx.hir().trait_item(id);
549         if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
550             && has_allow_dead_code_or_lang_attr(tcx, trait_item.hir_id())
551         {
552             worklist.push(trait_item.def_id);
553         }
554     }
555 }
556
557 fn check_foreign_item<'tcx>(
558     tcx: TyCtxt<'tcx>,
559     worklist: &mut Vec<LocalDefId>,
560     id: hir::ForeignItemId,
561 ) {
562     if matches!(tcx.hir().def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn)
563         && has_allow_dead_code_or_lang_attr(tcx, id.hir_id())
564     {
565         worklist.push(id.def_id);
566     }
567 }
568
569 fn create_and_seed_worklist<'tcx>(
570     tcx: TyCtxt<'tcx>,
571 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
572     let access_levels = &tcx.privacy_access_levels(());
573     // see `MarkSymbolVisitor::struct_constructors`
574     let mut struct_constructors = Default::default();
575     let mut worklist = access_levels
576         .map
577         .iter()
578         .filter_map(
579             |(&id, &level)| {
580                 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
581             },
582         )
583         // Seed entry point
584         .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
585         .collect::<Vec<_>>();
586
587     let crate_items = tcx.hir_crate_items(());
588     for id in crate_items.items() {
589         check_item(tcx, &mut worklist, &mut struct_constructors, id);
590     }
591
592     for id in crate_items.trait_items() {
593         check_trait_item(tcx, &mut worklist, id);
594     }
595
596     for id in crate_items.foreign_items() {
597         check_foreign_item(tcx, &mut worklist, id);
598     }
599
600     (worklist, struct_constructors)
601 }
602
603 fn live_symbols_and_ignored_derived_traits<'tcx>(
604     tcx: TyCtxt<'tcx>,
605     (): (),
606 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
607     let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
608     let mut symbol_visitor = MarkSymbolVisitor {
609         worklist,
610         tcx,
611         maybe_typeck_results: None,
612         live_symbols: Default::default(),
613         repr_has_repr_c: false,
614         in_pat: false,
615         ignore_variant_stack: vec![],
616         struct_constructors,
617         ignored_derived_traits: FxHashMap::default(),
618     };
619     symbol_visitor.mark_live_symbols();
620     (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
621 }
622
623 struct DeadVisitor<'tcx> {
624     tcx: TyCtxt<'tcx>,
625     live_symbols: &'tcx FxHashSet<LocalDefId>,
626     ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
627 }
628
629 impl<'tcx> DeadVisitor<'tcx> {
630     fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
631         let should_warn = matches!(
632             item.kind,
633             hir::ItemKind::Static(..)
634                 | hir::ItemKind::Const(..)
635                 | hir::ItemKind::Fn(..)
636                 | hir::ItemKind::TyAlias(..)
637                 | hir::ItemKind::Enum(..)
638                 | hir::ItemKind::Struct(..)
639                 | hir::ItemKind::Union(..)
640         );
641         should_warn && !self.symbol_is_live(item.def_id)
642     }
643
644     fn should_warn_about_field(&mut self, field: &hir::FieldDef<'_>) -> bool {
645         let def_id = self.tcx.hir().local_def_id(field.hir_id);
646         let field_type = self.tcx.type_of(def_id);
647         !field.is_positional()
648             && !self.symbol_is_live(def_id)
649             && !field_type.is_phantom_data()
650             && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id)
651     }
652
653     fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
654         let def_id = self.tcx.hir().local_def_id(variant.id);
655         !self.symbol_is_live(def_id) && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id)
656     }
657
658     fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
659         !self.symbol_is_live(fi.def_id) && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id())
660     }
661
662     // id := HIR id of an item's definition.
663     fn symbol_is_live(&mut self, def_id: LocalDefId) -> bool {
664         if self.live_symbols.contains(&def_id) {
665             return true;
666         }
667         // If it's a type whose items are live, then it's live, too.
668         // This is done to handle the case where, for example, the static
669         // method of a private type is used, but the type itself is never
670         // called directly.
671         let inherent_impls = self.tcx.inherent_impls(def_id);
672         for &impl_did in inherent_impls.iter() {
673             for item_did in self.tcx.associated_item_def_ids(impl_did) {
674                 if let Some(def_id) = item_did.as_local() {
675                     if self.live_symbols.contains(&def_id) {
676                         return true;
677                     }
678                 }
679             }
680         }
681         false
682     }
683
684     fn warn_dead_code(
685         &mut self,
686         id: hir::HirId,
687         span: rustc_span::Span,
688         name: Symbol,
689         participle: &str,
690     ) {
691         if !name.as_str().starts_with('_') {
692             self.tcx.struct_span_lint_hir(lint::builtin::DEAD_CODE, id, span, |lint| {
693                 let def_id = self.tcx.hir().local_def_id(id);
694                 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
695                 let mut err = lint.build(&format!("{} is never {}: `{}`", descr, participle, name));
696                 let hir = self.tcx.hir();
697                 if let Some(encl_scope) = hir.get_enclosing_scope(id)
698                     && let Some(encl_def_id) = hir.opt_local_def_id(encl_scope)
699                     && let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id)
700                 {
701                     let traits_str = ign_traits
702                         .iter()
703                         .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
704                         .collect::<Vec<_>>()
705                         .join(" and ");
706                     let plural_s = pluralize!(ign_traits.len());
707                     let article = if ign_traits.len() > 1 { "" } else { "a " };
708                     let is_are = if ign_traits.len() > 1 { "these are" } else { "this is" };
709                     let msg = format!(
710                         "`{}` has {}derived impl{} for the trait{} {}, but {} \
711                         intentionally ignored during dead code analysis",
712                         self.tcx.item_name(encl_def_id.to_def_id()),
713                         article,
714                         plural_s,
715                         plural_s,
716                         traits_str,
717                         is_are
718                     );
719                     let multispan = ign_traits
720                         .iter()
721                         .map(|(_, impl_id)| self.tcx.def_span(*impl_id))
722                         .collect::<Vec<_>>();
723                     err.span_note(multispan, &msg);
724                 }
725                 err.emit();
726             });
727         }
728     }
729 }
730
731 impl<'tcx> Visitor<'tcx> for DeadVisitor<'tcx> {
732     type NestedFilter = nested_filter::All;
733
734     /// Walk nested items in place so that we don't report dead-code
735     /// on inner functions when the outer function is already getting
736     /// an error. We could do this also by checking the parents, but
737     /// this is how the code is setup and it seems harmless enough.
738     fn nested_visit_map(&mut self) -> Self::Map {
739         self.tcx.hir()
740     }
741
742     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
743         if self.should_warn_about_item(item) {
744             // For most items, we want to highlight its identifier
745             let span = match item.kind {
746                 hir::ItemKind::Fn(..)
747                 | hir::ItemKind::Mod(..)
748                 | hir::ItemKind::Enum(..)
749                 | hir::ItemKind::Struct(..)
750                 | hir::ItemKind::Union(..)
751                 | hir::ItemKind::Trait(..)
752                 | hir::ItemKind::Impl { .. } => {
753                     // FIXME(66095): Because item.span is annotated with things
754                     // like expansion data, and ident.span isn't, we use the
755                     // def_span method if it's part of a macro invocation
756                     // (and thus has a source_callee set).
757                     // We should probably annotate ident.span with the macro
758                     // context, but that's a larger change.
759                     if item.span.source_callee().is_some() {
760                         self.tcx.sess.source_map().guess_head_span(item.span)
761                     } else {
762                         item.ident.span
763                     }
764                 }
765                 _ => item.span,
766             };
767             let participle = match item.kind {
768                 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
769                 _ => "used",
770             };
771             self.warn_dead_code(item.hir_id(), span, item.ident.name, participle);
772         } else {
773             // Only continue if we didn't warn
774             intravisit::walk_item(self, item);
775         }
776     }
777
778     // This visitor should only visit a single module at a time.
779     fn visit_mod(&mut self, _: &'tcx hir::Mod<'tcx>, _: Span, _: hir::HirId) {}
780
781     fn visit_variant(
782         &mut self,
783         variant: &'tcx hir::Variant<'tcx>,
784         g: &'tcx hir::Generics<'tcx>,
785         id: hir::HirId,
786     ) {
787         if self.should_warn_about_variant(&variant) {
788             self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed");
789         } else {
790             intravisit::walk_variant(self, variant, g, id);
791         }
792     }
793
794     fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
795         if self.should_warn_about_foreign_item(fi) {
796             self.warn_dead_code(fi.hir_id(), fi.span, fi.ident.name, "used");
797         }
798         intravisit::walk_foreign_item(self, fi);
799     }
800
801     fn visit_field_def(&mut self, field: &'tcx hir::FieldDef<'tcx>) {
802         if self.should_warn_about_field(&field) {
803             self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read");
804         }
805         intravisit::walk_field_def(self, field);
806     }
807
808     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
809         match impl_item.kind {
810             hir::ImplItemKind::Const(_, body_id) => {
811                 if !self.symbol_is_live(impl_item.def_id) {
812                     self.warn_dead_code(
813                         impl_item.hir_id(),
814                         impl_item.span,
815                         impl_item.ident.name,
816                         "used",
817                     );
818                 }
819                 self.visit_nested_body(body_id)
820             }
821             hir::ImplItemKind::Fn(_, body_id) => {
822                 if !self.symbol_is_live(impl_item.def_id) {
823                     // FIXME(66095): Because impl_item.span is annotated with things
824                     // like expansion data, and ident.span isn't, we use the
825                     // def_span method if it's part of a macro invocation
826                     // (and thus has a source_callee set).
827                     // We should probably annotate ident.span with the macro
828                     // context, but that's a larger change.
829                     let span = if impl_item.span.source_callee().is_some() {
830                         self.tcx.sess.source_map().guess_head_span(impl_item.span)
831                     } else {
832                         impl_item.ident.span
833                     };
834                     self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident.name, "used");
835                 }
836                 self.visit_nested_body(body_id)
837             }
838             hir::ImplItemKind::TyAlias(..) => {}
839         }
840     }
841
842     // Overwrite so that we don't warn the trait item itself.
843     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
844         match trait_item.kind {
845             hir::TraitItemKind::Const(_, Some(body_id))
846             | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
847                 self.visit_nested_body(body_id)
848             }
849             hir::TraitItemKind::Const(_, None)
850             | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
851             | hir::TraitItemKind::Type(..) => {}
852         }
853     }
854 }
855
856 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
857     let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
858     let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
859     let (module, _, module_id) = tcx.hir().get_module(module);
860     // Do not use an ItemLikeVisitor since we may want to skip visiting some items
861     // when a surrounding one is warned against or `_`.
862     intravisit::walk_mod(&mut visitor, module, module_id);
863 }
864
865 pub(crate) fn provide(providers: &mut Providers) {
866     *providers =
867         Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
868 }