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.
6 use crate::hir::{self, PatKind, TyKind};
7 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
8 use crate::hir::itemlikevisit::ItemLikeVisitor;
10 use crate::hir::def::{CtorOf, Res, DefKind};
11 use crate::hir::CodegenFnAttrFlags;
12 use crate::hir::def_id::{DefId, LOCAL_CRATE};
14 use crate::middle::privacy;
15 use crate::ty::{self, DefIdTree, TyCtxt};
16 use crate::util::nodemap::FxHashSet;
18 use rustc_data_structures::fx::FxHashMap;
20 use syntax::{ast, source_map};
22 use syntax::symbol::sym;
25 // Any local node that may call something in its body block should be
26 // explored. For example, if it's a live Node::Item that is a
27 // function, then we should explore its block to check for codes that
28 // may need to be marked as live.
29 fn should_explore<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
30 hir_id: hir::HirId) -> bool {
31 match tcx.hir().find_by_hir_id(hir_id) {
32 Some(Node::Item(..)) |
33 Some(Node::ImplItem(..)) |
34 Some(Node::ForeignItem(..)) |
35 Some(Node::TraitItem(..)) =>
42 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
43 worklist: Vec<hir::HirId>,
44 tcx: TyCtxt<'a, 'tcx, 'tcx>,
45 tables: &'a ty::TypeckTables<'tcx>,
46 live_symbols: FxHashSet<hir::HirId>,
47 repr_has_repr_c: bool,
49 inherited_pub_visibility: bool,
50 ignore_variant_stack: Vec<DefId>,
51 // maps from tuple struct constructors to tuple struct items
52 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
55 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
56 fn check_def_id(&mut self, def_id: DefId) {
57 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
58 if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
59 self.worklist.push(hir_id);
61 self.live_symbols.insert(hir_id);
65 fn insert_def_id(&mut self, def_id: DefId) {
66 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
67 debug_assert!(!should_explore(self.tcx, hir_id));
68 self.live_symbols.insert(hir_id);
72 fn handle_res(&mut self, res: Res) {
74 Res::Def(DefKind::Const, _)
75 | Res::Def(DefKind::AssocConst, _)
76 | Res::Def(DefKind::TyAlias, _) => {
77 self.check_def_id(res.def_id());
79 _ if self.in_pat => {},
80 Res::PrimTy(..) | Res::SelfTy(..) | Res::SelfCtor(..) |
81 Res::Local(..) | Res::Upvar(..) => {}
82 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
83 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
84 let enum_id = self.tcx.parent(variant_id).unwrap();
85 self.check_def_id(enum_id);
86 if !self.ignore_variant_stack.contains(&ctor_def_id) {
87 self.check_def_id(variant_id);
90 Res::Def(DefKind::Variant, variant_id) => {
91 let enum_id = self.tcx.parent(variant_id).unwrap();
92 self.check_def_id(enum_id);
93 if !self.ignore_variant_stack.contains(&variant_id) {
94 self.check_def_id(variant_id);
97 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
99 self.check_def_id(res.def_id());
104 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
105 if let Some(def_id) = self.tables.type_dependent_def_id(id) {
106 self.check_def_id(def_id);
108 bug!("no type-dependent def for method");
112 fn handle_field_access(&mut self, lhs: &hir::Expr, hir_id: hir::HirId) {
113 match self.tables.expr_ty_adjusted(lhs).sty {
115 let index = self.tcx.field_index(hir_id, self.tables);
116 self.insert_def_id(def.non_enum_variant().fields[index].did);
119 _ => span_bug!(lhs.span, "named field access on non-ADT"),
123 fn handle_field_pattern_match(&mut self, lhs: &hir::Pat, res: Res,
124 pats: &[source_map::Spanned<hir::FieldPat>]) {
125 let variant = match self.tables.node_type(lhs.hir_id).sty {
126 ty::Adt(adt, _) => adt.variant_of_res(res),
127 _ => span_bug!(lhs.span, "non-ADT in struct pattern")
130 if let PatKind::Wild = pat.node.pat.node {
133 let index = self.tcx.field_index(pat.node.hir_id, self.tables);
134 self.insert_def_id(variant.fields[index].did);
138 fn mark_live_symbols(&mut self) {
139 let mut scanned = FxHashSet::default();
140 while let Some(id) = self.worklist.pop() {
141 if !scanned.insert(id) {
145 // in the case of tuple struct constructors we want to check the item, not the generated
146 // tuple struct constructor function
147 let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
149 if let Some(node) = self.tcx.hir().find_by_hir_id(id) {
150 self.live_symbols.insert(id);
151 self.visit_node(node);
156 fn visit_node(&mut self, node: Node<'tcx>) {
157 let had_repr_c = self.repr_has_repr_c;
158 self.repr_has_repr_c = false;
159 let had_inherited_pub_visibility = self.inherited_pub_visibility;
160 self.inherited_pub_visibility = false;
162 Node::Item(item) => {
164 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
165 let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
166 let def = self.tcx.adt_def(def_id);
167 self.repr_has_repr_c = def.repr.c();
169 intravisit::walk_item(self, &item);
171 hir::ItemKind::Enum(..) => {
172 self.inherited_pub_visibility = item.vis.node.is_pub();
174 intravisit::walk_item(self, &item);
176 hir::ItemKind::ForeignMod(..) => {}
178 intravisit::walk_item(self, &item);
182 Node::TraitItem(trait_item) => {
183 intravisit::walk_trait_item(self, trait_item);
185 Node::ImplItem(impl_item) => {
186 intravisit::walk_impl_item(self, impl_item);
188 Node::ForeignItem(foreign_item) => {
189 intravisit::walk_foreign_item(self, &foreign_item);
193 self.repr_has_repr_c = had_repr_c;
194 self.inherited_pub_visibility = had_inherited_pub_visibility;
197 fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &hir::HirVec<hir::Field>) {
198 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
199 for field in fields {
200 let index = self.tcx.field_index(field.hir_id, self.tables);
201 self.insert_def_id(adt.non_enum_variant().fields[index].did);
207 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
208 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
209 NestedVisitorMap::None
212 fn visit_nested_body(&mut self, body: hir::BodyId) {
213 let old_tables = self.tables;
214 self.tables = self.tcx.body_tables(body);
215 let body = self.tcx.hir().body(body);
216 self.visit_body(body);
217 self.tables = old_tables;
220 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name,
221 _: &hir::Generics, _: hir::HirId, _: syntax_pos::Span) {
222 let has_repr_c = self.repr_has_repr_c;
223 let inherited_pub_visibility = self.inherited_pub_visibility;
224 let live_fields = def.fields().iter().filter(|f| {
225 has_repr_c || inherited_pub_visibility || f.vis.node.is_pub()
227 self.live_symbols.extend(live_fields.map(|f| f.hir_id));
229 intravisit::walk_struct_def(self, def);
232 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
234 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
235 let res = self.tables.qpath_res(qpath, expr.hir_id);
236 self.handle_res(res);
238 hir::ExprKind::MethodCall(..) => {
239 self.lookup_and_handle_method(expr.hir_id);
241 hir::ExprKind::Field(ref lhs, ..) => {
242 self.handle_field_access(&lhs, expr.hir_id);
244 hir::ExprKind::Struct(_, ref fields, _) => {
245 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).sty {
246 self.mark_as_used_if_union(adt, fields);
252 intravisit::walk_expr(self, expr);
255 fn visit_arm(&mut self, arm: &'tcx hir::Arm) {
256 if arm.pats.len() == 1 {
257 let variants = arm.pats[0].necessary_variants();
259 // Inside the body, ignore constructions of variants
260 // necessary for the pattern to match. Those construction sites
261 // can't be reached unless the variant is constructed elsewhere.
262 let len = self.ignore_variant_stack.len();
263 self.ignore_variant_stack.extend_from_slice(&variants);
264 intravisit::walk_arm(self, arm);
265 self.ignore_variant_stack.truncate(len);
267 intravisit::walk_arm(self, arm);
271 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
273 PatKind::Struct(hir::QPath::Resolved(_, ref path), ref fields, _) => {
274 self.handle_field_pattern_match(pat, path.res, fields);
276 PatKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
277 let res = self.tables.qpath_res(qpath, pat.hir_id);
278 self.handle_res(res);
284 intravisit::walk_pat(self, pat);
288 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
289 self.handle_res(path.res);
290 intravisit::walk_path(self, path);
293 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
295 TyKind::Def(item_id, _) => {
296 let item = self.tcx.hir().expect_item_by_hir_id(item_id.id);
297 intravisit::walk_item(self, item);
301 intravisit::walk_ty(self, ty);
305 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_, '_, '_>,
307 attrs: &[ast::Attribute]) -> bool {
308 if attr::contains_name(attrs, sym::lang) {
312 // Stable attribute for #[lang = "panic_impl"]
313 if attr::contains_name(attrs, sym::panic_handler) {
317 // (To be) stable attribute for #[lang = "oom"]
318 if attr::contains_name(attrs, sym::alloc_error_handler) {
322 // Don't lint about global allocators
323 if attr::contains_name(attrs, sym::global_allocator) {
327 let def_id = tcx.hir().local_def_id_from_hir_id(id);
328 let cg_attrs = tcx.codegen_fn_attrs(def_id);
330 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
331 // forcefully, e.g., for placing it in a specific section.
332 if cg_attrs.contains_extern_indicator() ||
333 cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
337 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
340 // This visitor seeds items that
341 // 1) We want to explicitly consider as live:
342 // * Item annotated with #[allow(dead_code)]
343 // - This is done so that if we want to suppress warnings for a
344 // group of dead functions, we only have to annotate the "root".
345 // For example, if both `f` and `g` are dead and `f` calls `g`,
346 // then annotating `f` with `#[allow(dead_code)]` will suppress
347 // warning for both `f` and `g`.
348 // * Item annotated with #[lang=".."]
349 // - This is because lang items are always callable from elsewhere.
351 // 2) We are not sure to be live or not
352 // * Implementation of a trait method
353 struct LifeSeeder<'k, 'tcx: 'k> {
354 worklist: Vec<hir::HirId>,
355 krate: &'k hir::Crate,
356 tcx: TyCtxt<'k, 'tcx, 'tcx>,
357 // see `MarkSymbolVisitor::struct_constructors`
358 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
361 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
362 fn visit_item(&mut self, item: &hir::Item) {
363 let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx,
367 self.worklist.push(item.hir_id);
370 hir::ItemKind::Enum(ref enum_def, _) => {
372 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.node.id));
375 for variant in &enum_def.variants {
376 if let Some(ctor_hir_id) = variant.node.data.ctor_hir_id() {
377 self.struct_constructors.insert(ctor_hir_id, variant.node.id);
381 hir::ItemKind::Trait(.., ref trait_item_refs) => {
382 for trait_item_ref in trait_item_refs {
383 let trait_item = self.krate.trait_item(trait_item_ref.id);
384 match trait_item.node {
385 hir::TraitItemKind::Const(_, Some(_)) |
386 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
387 if has_allow_dead_code_or_lang_attr(self.tcx,
390 self.worklist.push(trait_item.hir_id);
397 hir::ItemKind::Impl(.., ref opt_trait, _, ref impl_item_refs) => {
398 for impl_item_ref in impl_item_refs {
399 let impl_item = self.krate.impl_item(impl_item_ref.id);
400 if opt_trait.is_some() ||
401 has_allow_dead_code_or_lang_attr(self.tcx,
404 self.worklist.push(impl_item_ref.id.hir_id);
408 hir::ItemKind::Struct(ref variant_data, _) => {
409 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
410 self.struct_constructors.insert(ctor_hir_id, item.hir_id);
417 fn visit_trait_item(&mut self, _item: &hir::TraitItem) {
418 // ignore: we are handling this in `visit_item` above
421 fn visit_impl_item(&mut self, _item: &hir::ImplItem) {
422 // ignore: we are handling this in `visit_item` above
426 fn create_and_seed_worklist<'a, 'tcx>(
427 tcx: TyCtxt<'a, 'tcx, 'tcx>,
428 access_levels: &privacy::AccessLevels,
430 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
431 let worklist = access_levels.map.iter().filter_map(|(&id, level)| {
432 if level >= &privacy::AccessLevel::Reachable {
439 tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap())
440 ).collect::<Vec<_>>();
442 // Seed implemented trait items
443 let mut life_seeder = LifeSeeder {
447 struct_constructors: Default::default(),
449 krate.visit_all_item_likes(&mut life_seeder);
451 (life_seeder.worklist, life_seeder.struct_constructors)
454 fn find_live<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
455 access_levels: &privacy::AccessLevels,
457 -> FxHashSet<hir::HirId> {
458 let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
459 let mut symbol_visitor = MarkSymbolVisitor {
462 tables: &ty::TypeckTables::empty(None),
463 live_symbols: Default::default(),
464 repr_has_repr_c: false,
466 inherited_pub_visibility: false,
467 ignore_variant_stack: vec![],
470 symbol_visitor.mark_live_symbols();
471 symbol_visitor.live_symbols
474 struct DeadVisitor<'a, 'tcx: 'a> {
475 tcx: TyCtxt<'a, 'tcx, 'tcx>,
476 live_symbols: FxHashSet<hir::HirId>,
479 impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
480 fn should_warn_about_item(&mut self, item: &hir::Item) -> bool {
481 let should_warn = match item.node {
482 hir::ItemKind::Static(..)
483 | hir::ItemKind::Const(..)
484 | hir::ItemKind::Fn(..)
485 | hir::ItemKind::Ty(..)
486 | hir::ItemKind::Enum(..)
487 | hir::ItemKind::Struct(..)
488 | hir::ItemKind::Union(..) => true,
491 should_warn && !self.symbol_is_live(item.hir_id)
494 fn should_warn_about_field(&mut self, field: &hir::StructField) -> bool {
495 let field_type = self.tcx.type_of(self.tcx.hir().local_def_id_from_hir_id(field.hir_id));
496 !field.is_positional()
497 && !self.symbol_is_live(field.hir_id)
498 && !field_type.is_phantom_data()
499 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
502 fn should_warn_about_variant(&mut self, variant: &hir::VariantKind) -> bool {
503 !self.symbol_is_live(variant.id)
504 && !has_allow_dead_code_or_lang_attr(self.tcx,
509 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem) -> bool {
510 !self.symbol_is_live(fi.hir_id)
511 && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
514 // id := HIR id of an item's definition.
519 if self.live_symbols.contains(&id) {
522 // If it's a type whose items are live, then it's live, too.
523 // This is done to handle the case where, for example, the static
524 // method of a private type is used, but the type itself is never
526 let def_id = self.tcx.hir().local_def_id_from_hir_id(id);
527 let inherent_impls = self.tcx.inherent_impls(def_id);
528 for &impl_did in inherent_impls.iter() {
529 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
530 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
531 if self.live_symbols.contains(&item_hir_id) {
540 fn warn_dead_code(&mut self,
542 span: syntax_pos::Span,
546 if !name.as_str().starts_with("_") {
548 .lint_hir(lint::builtin::DEAD_CODE,
551 &format!("{} is never {}: `{}`",
552 node_type, participle, name));
557 impl<'a, 'tcx> Visitor<'tcx> for DeadVisitor<'a, 'tcx> {
558 /// Walk nested items in place so that we don't report dead-code
559 /// on inner functions when the outer function is already getting
560 /// an error. We could do this also by checking the parents, but
561 /// this is how the code is setup and it seems harmless enough.
562 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
563 NestedVisitorMap::All(&self.tcx.hir())
566 fn visit_item(&mut self, item: &'tcx hir::Item) {
567 if self.should_warn_about_item(item) {
568 // For items that have a definition with a signature followed by a
569 // block, point only at the signature.
570 let span = match item.node {
571 hir::ItemKind::Fn(..) |
572 hir::ItemKind::Mod(..) |
573 hir::ItemKind::Enum(..) |
574 hir::ItemKind::Struct(..) |
575 hir::ItemKind::Union(..) |
576 hir::ItemKind::Trait(..) |
577 hir::ItemKind::Impl(..) => self.tcx.sess.source_map().def_span(item.span),
580 let participle = match item.node {
581 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
588 item.node.descriptive_variant(),
592 // Only continue if we didn't warn
593 intravisit::walk_item(self, item);
597 fn visit_variant(&mut self,
598 variant: &'tcx hir::Variant,
599 g: &'tcx hir::Generics,
601 if self.should_warn_about_variant(&variant.node) {
602 self.warn_dead_code(variant.node.id, variant.span, variant.node.ident.name,
603 "variant", "constructed");
605 intravisit::walk_variant(self, variant, g, id);
609 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
610 if self.should_warn_about_foreign_item(fi) {
611 self.warn_dead_code(fi.hir_id, fi.span, fi.ident.name,
612 fi.node.descriptive_variant(), "used");
614 intravisit::walk_foreign_item(self, fi);
617 fn visit_struct_field(&mut self, field: &'tcx hir::StructField) {
618 if self.should_warn_about_field(&field) {
619 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "used");
621 intravisit::walk_struct_field(self, field);
624 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
625 match impl_item.node {
626 hir::ImplItemKind::Const(_, body_id) => {
627 if !self.symbol_is_live(impl_item.hir_id) {
628 self.warn_dead_code(impl_item.hir_id,
630 impl_item.ident.name,
634 self.visit_nested_body(body_id)
636 hir::ImplItemKind::Method(_, body_id) => {
637 if !self.symbol_is_live(impl_item.hir_id) {
638 let span = self.tcx.sess.source_map().def_span(impl_item.span);
639 self.warn_dead_code(impl_item.hir_id, span, impl_item.ident.name, "method",
642 self.visit_nested_body(body_id)
644 hir::ImplItemKind::Existential(..) |
645 hir::ImplItemKind::Type(..) => {}
649 // Overwrite so that we don't warn the trait item itself.
650 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
651 match trait_item.node {
652 hir::TraitItemKind::Const(_, Some(body_id)) |
653 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
654 self.visit_nested_body(body_id)
656 hir::TraitItemKind::Const(_, None) |
657 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
658 hir::TraitItemKind::Type(..) => {}
663 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
664 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
665 let krate = tcx.hir().krate();
666 let live_symbols = find_live(tcx, access_levels, krate);
667 let mut visitor = DeadVisitor {
671 intravisit::walk_crate(&mut visitor, krate);