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, Def};
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};
24 // Any local node that may call something in its body block should be
25 // explored. For example, if it's a live Node::Item that is a
26 // function, then we should explore its block to check for codes that
27 // may need to be marked as live.
28 fn should_explore<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
29 hir_id: hir::HirId) -> bool {
30 match tcx.hir().find_by_hir_id(hir_id) {
31 Some(Node::Item(..)) |
32 Some(Node::ImplItem(..)) |
33 Some(Node::ForeignItem(..)) |
34 Some(Node::TraitItem(..)) =>
41 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
42 worklist: Vec<hir::HirId>,
43 tcx: TyCtxt<'a, 'tcx, 'tcx>,
44 tables: &'a ty::TypeckTables<'tcx>,
45 live_symbols: FxHashSet<hir::HirId>,
46 repr_has_repr_c: bool,
48 inherited_pub_visibility: bool,
49 ignore_variant_stack: Vec<DefId>,
50 // maps from tuple struct constructors to tuple struct items
51 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
54 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
55 fn check_def_id(&mut self, def_id: DefId) {
56 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
57 if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
58 self.worklist.push(hir_id);
60 self.live_symbols.insert(hir_id);
64 fn insert_def_id(&mut self, def_id: DefId) {
65 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
66 debug_assert!(!should_explore(self.tcx, hir_id));
67 self.live_symbols.insert(hir_id);
71 fn handle_definition(&mut self, def: Def) {
73 Def::Const(_) | Def::AssociatedConst(..) | Def::TyAlias(_) => {
74 self.check_def_id(def.def_id());
76 _ if self.in_pat => (),
77 Def::PrimTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) |
78 Def::Local(..) | Def::Upvar(..) => {}
79 Def::Ctor(ctor_def_id, CtorOf::Variant, ..) => {
80 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
81 let enum_id = self.tcx.parent(variant_id).unwrap();
82 self.check_def_id(enum_id);
83 if !self.ignore_variant_stack.contains(&ctor_def_id) {
84 self.check_def_id(variant_id);
87 Def::Variant(variant_id) => {
88 let enum_id = self.tcx.parent(variant_id).unwrap();
89 self.check_def_id(enum_id);
90 if !self.ignore_variant_stack.contains(&variant_id) {
91 self.check_def_id(variant_id);
95 self.check_def_id(def.def_id());
100 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
101 if let Some(def_id) = self.tables.type_dependent_def_id(id) {
102 self.check_def_id(def_id);
104 bug!("no type-dependent def for method");
108 fn handle_field_access(&mut self, lhs: &hir::Expr, hir_id: hir::HirId) {
109 match self.tables.expr_ty_adjusted(lhs).sty {
111 let index = self.tcx.field_index(hir_id, self.tables);
112 self.insert_def_id(def.non_enum_variant().fields[index].did);
115 _ => span_bug!(lhs.span, "named field access on non-ADT"),
119 fn handle_field_pattern_match(&mut self, lhs: &hir::Pat, def: Def,
120 pats: &[source_map::Spanned<hir::FieldPat>]) {
121 let variant = match self.tables.node_type(lhs.hir_id).sty {
122 ty::Adt(adt, _) => adt.variant_of_def(def),
123 _ => span_bug!(lhs.span, "non-ADT in struct pattern")
126 if let PatKind::Wild = pat.node.pat.node {
129 let index = self.tcx.field_index(pat.node.hir_id, self.tables);
130 self.insert_def_id(variant.fields[index].did);
134 fn mark_live_symbols(&mut self) {
135 let mut scanned = FxHashSet::default();
136 while let Some(id) = self.worklist.pop() {
137 if !scanned.insert(id) {
141 // in the case of tuple struct constructors we want to check the item, not the generated
142 // tuple struct constructor function
143 let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
145 if let Some(node) = self.tcx.hir().find_by_hir_id(id) {
146 self.live_symbols.insert(id);
147 self.visit_node(node);
152 fn visit_node(&mut self, node: Node<'tcx>) {
153 let had_repr_c = self.repr_has_repr_c;
154 self.repr_has_repr_c = false;
155 let had_inherited_pub_visibility = self.inherited_pub_visibility;
156 self.inherited_pub_visibility = false;
158 Node::Item(item) => {
160 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
161 let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
162 let def = self.tcx.adt_def(def_id);
163 self.repr_has_repr_c = def.repr.c();
165 intravisit::walk_item(self, &item);
167 hir::ItemKind::Enum(..) => {
168 self.inherited_pub_visibility = item.vis.node.is_pub();
169 intravisit::walk_item(self, &item);
171 hir::ItemKind::Fn(..)
172 | hir::ItemKind::Ty(..)
173 | hir::ItemKind::Static(..)
174 | hir::ItemKind::Existential(..)
175 | hir::ItemKind::Const(..) => {
176 intravisit::walk_item(self, &item);
181 Node::TraitItem(trait_item) => {
182 intravisit::walk_trait_item(self, trait_item);
184 Node::ImplItem(impl_item) => {
185 intravisit::walk_impl_item(self, impl_item);
187 Node::ForeignItem(foreign_item) => {
188 intravisit::walk_foreign_item(self, &foreign_item);
192 self.repr_has_repr_c = had_repr_c;
193 self.inherited_pub_visibility = had_inherited_pub_visibility;
196 fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &hir::HirVec<hir::Field>) {
197 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
198 for field in fields {
199 let index = self.tcx.field_index(field.hir_id, self.tables);
200 self.insert_def_id(adt.non_enum_variant().fields[index].did);
206 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
207 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
208 NestedVisitorMap::None
211 fn visit_nested_body(&mut self, body: hir::BodyId) {
212 let old_tables = self.tables;
213 self.tables = self.tcx.body_tables(body);
214 let body = self.tcx.hir().body(body);
215 self.visit_body(body);
216 self.tables = old_tables;
219 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name,
220 _: &hir::Generics, _: hir::HirId, _: syntax_pos::Span) {
221 let has_repr_c = self.repr_has_repr_c;
222 let inherited_pub_visibility = self.inherited_pub_visibility;
223 let live_fields = def.fields().iter().filter(|f| {
224 has_repr_c || inherited_pub_visibility || f.vis.node.is_pub()
226 self.live_symbols.extend(live_fields.map(|f| f.hir_id));
228 intravisit::walk_struct_def(self, def);
231 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
233 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
234 let def = self.tables.qpath_def(qpath, expr.hir_id);
235 self.handle_definition(def);
237 hir::ExprKind::MethodCall(..) => {
238 self.lookup_and_handle_method(expr.hir_id);
240 hir::ExprKind::Field(ref lhs, ..) => {
241 self.handle_field_access(&lhs, expr.hir_id);
243 hir::ExprKind::Struct(_, ref fields, _) => {
244 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).sty {
245 self.mark_as_used_if_union(adt, fields);
251 intravisit::walk_expr(self, expr);
254 fn visit_arm(&mut self, arm: &'tcx hir::Arm) {
255 if arm.pats.len() == 1 {
256 let variants = arm.pats[0].necessary_variants();
258 // Inside the body, ignore constructions of variants
259 // necessary for the pattern to match. Those construction sites
260 // can't be reached unless the variant is constructed elsewhere.
261 let len = self.ignore_variant_stack.len();
262 self.ignore_variant_stack.extend_from_slice(&variants);
263 intravisit::walk_arm(self, arm);
264 self.ignore_variant_stack.truncate(len);
266 intravisit::walk_arm(self, arm);
270 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
272 PatKind::Struct(hir::QPath::Resolved(_, ref path), ref fields, _) => {
273 self.handle_field_pattern_match(pat, path.def, fields);
275 PatKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
276 let def = self.tables.qpath_def(qpath, pat.hir_id);
277 self.handle_definition(def);
283 intravisit::walk_pat(self, pat);
287 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
288 self.handle_definition(path.def);
289 intravisit::walk_path(self, path);
292 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
294 TyKind::Def(item_id, _) => {
295 let item = self.tcx.hir().expect_item_by_hir_id(item_id.id);
296 intravisit::walk_item(self, item);
300 intravisit::walk_ty(self, ty);
304 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_, '_, '_>,
306 attrs: &[ast::Attribute]) -> bool {
307 if attr::contains_name(attrs, "lang") {
311 // Stable attribute for #[lang = "panic_impl"]
312 if attr::contains_name(attrs, "panic_handler") {
316 // (To be) stable attribute for #[lang = "oom"]
317 if attr::contains_name(attrs, "alloc_error_handler") {
321 // Don't lint about global allocators
322 if attr::contains_name(attrs, "global_allocator") {
326 let def_id = tcx.hir().local_def_id_from_hir_id(id);
327 let cg_attrs = tcx.codegen_fn_attrs(def_id);
329 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
330 // forcefully, e.g., for placing it in a specific section.
331 if cg_attrs.contains_extern_indicator() ||
332 cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
336 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
339 // This visitor seeds items that
340 // 1) We want to explicitly consider as live:
341 // * Item annotated with #[allow(dead_code)]
342 // - This is done so that if we want to suppress warnings for a
343 // group of dead functions, we only have to annotate the "root".
344 // For example, if both `f` and `g` are dead and `f` calls `g`,
345 // then annotating `f` with `#[allow(dead_code)]` will suppress
346 // warning for both `f` and `g`.
347 // * Item annotated with #[lang=".."]
348 // - This is because lang items are always callable from elsewhere.
350 // 2) We are not sure to be live or not
351 // * Implementation of a trait method
352 struct LifeSeeder<'k, 'tcx: 'k> {
353 worklist: Vec<hir::HirId>,
354 krate: &'k hir::Crate,
355 tcx: TyCtxt<'k, 'tcx, 'tcx>,
356 // see `MarkSymbolVisitor::struct_constructors`
357 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
360 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
361 fn visit_item(&mut self, item: &hir::Item) {
362 let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx,
366 self.worklist.push(item.hir_id);
369 hir::ItemKind::Enum(ref enum_def, _) => {
371 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.node.id));
374 for variant in &enum_def.variants {
375 if let Some(ctor_hir_id) = variant.node.data.ctor_hir_id() {
376 self.struct_constructors.insert(ctor_hir_id, variant.node.id);
380 hir::ItemKind::Trait(.., ref trait_item_refs) => {
381 for trait_item_ref in trait_item_refs {
382 let trait_item = self.krate.trait_item(trait_item_ref.id);
383 match trait_item.node {
384 hir::TraitItemKind::Const(_, Some(_)) |
385 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
386 if has_allow_dead_code_or_lang_attr(self.tcx,
389 self.worklist.push(trait_item.hir_id);
396 hir::ItemKind::Impl(.., ref opt_trait, _, ref impl_item_refs) => {
397 for impl_item_ref in impl_item_refs {
398 let impl_item = self.krate.impl_item(impl_item_ref.id);
399 if opt_trait.is_some() ||
400 has_allow_dead_code_or_lang_attr(self.tcx,
403 self.worklist.push(impl_item_ref.id.hir_id);
407 hir::ItemKind::Struct(ref variant_data, _) => {
408 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
409 self.struct_constructors.insert(ctor_hir_id, item.hir_id);
416 fn visit_trait_item(&mut self, _item: &hir::TraitItem) {
417 // ignore: we are handling this in `visit_item` above
420 fn visit_impl_item(&mut self, _item: &hir::ImplItem) {
421 // ignore: we are handling this in `visit_item` above
425 fn create_and_seed_worklist<'a, 'tcx>(
426 tcx: TyCtxt<'a, 'tcx, 'tcx>,
427 access_levels: &privacy::AccessLevels,
429 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
430 let worklist = access_levels.map.iter().filter_map(|(&id, level)| {
431 if level >= &privacy::AccessLevel::Reachable {
438 tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap())
439 ).collect::<Vec<_>>();
441 // Seed implemented trait items
442 let mut life_seeder = LifeSeeder {
446 struct_constructors: Default::default(),
448 krate.visit_all_item_likes(&mut life_seeder);
450 (life_seeder.worklist, life_seeder.struct_constructors)
453 fn find_live<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
454 access_levels: &privacy::AccessLevels,
456 -> FxHashSet<hir::HirId> {
457 let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
458 let mut symbol_visitor = MarkSymbolVisitor {
461 tables: &ty::TypeckTables::empty(None),
462 live_symbols: Default::default(),
463 repr_has_repr_c: false,
465 inherited_pub_visibility: false,
466 ignore_variant_stack: vec![],
469 symbol_visitor.mark_live_symbols();
470 symbol_visitor.live_symbols
473 struct DeadVisitor<'a, 'tcx: 'a> {
474 tcx: TyCtxt<'a, 'tcx, 'tcx>,
475 live_symbols: FxHashSet<hir::HirId>,
478 impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
479 fn should_warn_about_item(&mut self, item: &hir::Item) -> bool {
480 let should_warn = match item.node {
481 hir::ItemKind::Static(..)
482 | hir::ItemKind::Const(..)
483 | hir::ItemKind::Fn(..)
484 | hir::ItemKind::Ty(..)
485 | hir::ItemKind::Enum(..)
486 | hir::ItemKind::Struct(..)
487 | hir::ItemKind::Union(..) => true,
490 should_warn && !self.symbol_is_live(item.hir_id)
493 fn should_warn_about_field(&mut self, field: &hir::StructField) -> bool {
494 let field_type = self.tcx.type_of(self.tcx.hir().local_def_id_from_hir_id(field.hir_id));
495 !field.is_positional()
496 && !self.symbol_is_live(field.hir_id)
497 && !field_type.is_phantom_data()
498 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
501 fn should_warn_about_variant(&mut self, variant: &hir::VariantKind) -> bool {
502 !self.symbol_is_live(variant.id)
503 && !has_allow_dead_code_or_lang_attr(self.tcx,
508 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem) -> bool {
509 !self.symbol_is_live(fi.hir_id)
510 && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
513 // id := HIR id of an item's definition.
518 if self.live_symbols.contains(&id) {
521 // If it's a type whose items are live, then it's live, too.
522 // This is done to handle the case where, for example, the static
523 // method of a private type is used, but the type itself is never
525 let def_id = self.tcx.hir().local_def_id_from_hir_id(id);
526 let inherent_impls = self.tcx.inherent_impls(def_id);
527 for &impl_did in inherent_impls.iter() {
528 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
529 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
530 if self.live_symbols.contains(&item_hir_id) {
539 fn warn_dead_code(&mut self,
541 span: syntax_pos::Span,
545 if !name.as_str().starts_with("_") {
547 .lint_hir(lint::builtin::DEAD_CODE,
550 &format!("{} is never {}: `{}`",
551 node_type, participle, name));
556 impl<'a, 'tcx> Visitor<'tcx> for DeadVisitor<'a, 'tcx> {
557 /// Walk nested items in place so that we don't report dead-code
558 /// on inner functions when the outer function is already getting
559 /// an error. We could do this also by checking the parents, but
560 /// this is how the code is setup and it seems harmless enough.
561 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
562 NestedVisitorMap::All(&self.tcx.hir())
565 fn visit_item(&mut self, item: &'tcx hir::Item) {
566 if self.should_warn_about_item(item) {
567 // For items that have a definition with a signature followed by a
568 // block, point only at the signature.
569 let span = match item.node {
570 hir::ItemKind::Fn(..) |
571 hir::ItemKind::Mod(..) |
572 hir::ItemKind::Enum(..) |
573 hir::ItemKind::Struct(..) |
574 hir::ItemKind::Union(..) |
575 hir::ItemKind::Trait(..) |
576 hir::ItemKind::Impl(..) => self.tcx.sess.source_map().def_span(item.span),
579 let participle = match item.node {
580 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
587 item.node.descriptive_variant(),
591 // Only continue if we didn't warn
592 intravisit::walk_item(self, item);
596 fn visit_variant(&mut self,
597 variant: &'tcx hir::Variant,
598 g: &'tcx hir::Generics,
600 if self.should_warn_about_variant(&variant.node) {
601 self.warn_dead_code(variant.node.id, variant.span, variant.node.ident.name,
602 "variant", "constructed");
604 intravisit::walk_variant(self, variant, g, id);
608 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
609 if self.should_warn_about_foreign_item(fi) {
610 self.warn_dead_code(fi.hir_id, fi.span, fi.ident.name,
611 fi.node.descriptive_variant(), "used");
613 intravisit::walk_foreign_item(self, fi);
616 fn visit_struct_field(&mut self, field: &'tcx hir::StructField) {
617 if self.should_warn_about_field(&field) {
618 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "used");
620 intravisit::walk_struct_field(self, field);
623 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
624 match impl_item.node {
625 hir::ImplItemKind::Const(_, body_id) => {
626 if !self.symbol_is_live(impl_item.hir_id) {
627 self.warn_dead_code(impl_item.hir_id,
629 impl_item.ident.name,
633 self.visit_nested_body(body_id)
635 hir::ImplItemKind::Method(_, body_id) => {
636 if !self.symbol_is_live(impl_item.hir_id) {
637 let span = self.tcx.sess.source_map().def_span(impl_item.span);
638 self.warn_dead_code(impl_item.hir_id, span, impl_item.ident.name, "method",
641 self.visit_nested_body(body_id)
643 hir::ImplItemKind::Existential(..) |
644 hir::ImplItemKind::Type(..) => {}
648 // Overwrite so that we don't warn the trait item itself.
649 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
650 match trait_item.node {
651 hir::TraitItemKind::Const(_, Some(body_id)) |
652 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
653 self.visit_nested_body(body_id)
655 hir::TraitItemKind::Const(_, None) |
656 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
657 hir::TraitItemKind::Type(..) => {}
662 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
663 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
664 let krate = tcx.hir().krate();
665 let live_symbols = find_live(tcx, access_levels, krate);
666 let mut visitor = DeadVisitor {
670 intravisit::walk_crate(&mut visitor, krate);