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.
5 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc::middle::privacy;
9 use rustc::ty::{self, DefIdTree, TyCtxt};
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_hir::def::{CtorOf, DefKind, Res};
13 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::{Node, PatKind, TyKind};
18 use rustc_span::symbol::sym;
19 use syntax::{ast, attr};
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<'_>, hir_id: hir::HirId) -> bool {
26 match tcx.hir().find(hir_id) {
28 | Some(Node::ImplItem(..))
29 | Some(Node::ForeignItem(..))
30 | Some(Node::TraitItem(..))
31 | Some(Node::Variant(..))
32 | Some(Node::AnonConst(..))
33 | Some(Node::Pat(..)) => true,
38 struct MarkSymbolVisitor<'a, 'tcx> {
39 worklist: Vec<hir::HirId>,
41 tables: &'a ty::TypeckTables<'tcx>,
42 live_symbols: FxHashSet<hir::HirId>,
43 repr_has_repr_c: bool,
45 inherited_pub_visibility: bool,
46 ignore_variant_stack: Vec<DefId>,
47 // maps from tuple struct constructors to tuple struct items
48 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
51 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
52 fn check_def_id(&mut self, def_id: DefId) {
53 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
54 if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
55 self.worklist.push(hir_id);
57 self.live_symbols.insert(hir_id);
61 fn insert_def_id(&mut self, def_id: DefId) {
62 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
63 debug_assert!(!should_explore(self.tcx, hir_id));
64 self.live_symbols.insert(hir_id);
68 fn handle_res(&mut self, res: Res) {
70 Res::Def(DefKind::Const, _)
71 | Res::Def(DefKind::AssocConst, _)
72 | Res::Def(DefKind::TyAlias, _) => {
73 self.check_def_id(res.def_id());
75 _ if self.in_pat => {}
76 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
77 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
78 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
79 let enum_id = self.tcx.parent(variant_id).unwrap();
80 self.check_def_id(enum_id);
81 if !self.ignore_variant_stack.contains(&ctor_def_id) {
82 self.check_def_id(variant_id);
85 Res::Def(DefKind::Variant, variant_id) => {
86 let enum_id = self.tcx.parent(variant_id).unwrap();
87 self.check_def_id(enum_id);
88 if !self.ignore_variant_stack.contains(&variant_id) {
89 self.check_def_id(variant_id);
92 Res::SelfTy(t, i) => {
100 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
102 self.check_def_id(res.def_id());
107 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
108 if let Some(def_id) = self.tables.type_dependent_def_id(id) {
109 self.check_def_id(def_id);
111 bug!("no type-dependent def for method");
115 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
116 match self.tables.expr_ty_adjusted(lhs).kind {
118 let index = self.tcx.field_index(hir_id, self.tables);
119 self.insert_def_id(def.non_enum_variant().fields[index].did);
122 _ => span_bug!(lhs.span, "named field access on non-ADT"),
126 fn handle_field_pattern_match(
130 pats: &[hir::FieldPat<'_>],
132 let variant = match self.tables.node_type(lhs.hir_id).kind {
133 ty::Adt(adt, _) => adt.variant_of_res(res),
134 _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
137 if let PatKind::Wild = pat.pat.kind {
140 let index = self.tcx.field_index(pat.hir_id, self.tables);
141 self.insert_def_id(variant.fields[index].did);
145 fn mark_live_symbols(&mut self) {
146 let mut scanned = FxHashSet::default();
147 while let Some(id) = self.worklist.pop() {
148 if !scanned.insert(id) {
152 // in the case of tuple struct constructors we want to check the item, not the generated
153 // tuple struct constructor function
154 let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
156 if let Some(node) = self.tcx.hir().find(id) {
157 self.live_symbols.insert(id);
158 self.visit_node(node);
163 fn visit_node(&mut self, node: Node<'tcx>) {
164 let had_repr_c = self.repr_has_repr_c;
165 self.repr_has_repr_c = false;
166 let had_inherited_pub_visibility = self.inherited_pub_visibility;
167 self.inherited_pub_visibility = false;
169 Node::Item(item) => match item.kind {
170 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
171 let def_id = self.tcx.hir().local_def_id(item.hir_id);
172 let def = self.tcx.adt_def(def_id);
173 self.repr_has_repr_c = def.repr.c();
175 intravisit::walk_item(self, &item);
177 hir::ItemKind::Enum(..) => {
178 self.inherited_pub_visibility = item.vis.node.is_pub();
180 intravisit::walk_item(self, &item);
182 hir::ItemKind::ForeignMod(..) => {}
184 intravisit::walk_item(self, &item);
187 Node::TraitItem(trait_item) => {
188 intravisit::walk_trait_item(self, trait_item);
190 Node::ImplItem(impl_item) => {
191 intravisit::walk_impl_item(self, impl_item);
193 Node::ForeignItem(foreign_item) => {
194 intravisit::walk_foreign_item(self, &foreign_item);
198 self.repr_has_repr_c = had_repr_c;
199 self.inherited_pub_visibility = had_inherited_pub_visibility;
202 fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &[hir::Field<'_>]) {
203 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
204 for field in fields {
205 let index = self.tcx.field_index(field.hir_id, self.tables);
206 self.insert_def_id(adt.non_enum_variant().fields[index].did);
212 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
213 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
214 NestedVisitorMap::None
217 fn visit_nested_body(&mut self, body: hir::BodyId) {
218 let old_tables = self.tables;
219 self.tables = self.tcx.body_tables(body);
220 let body = self.tcx.hir().body(body);
221 self.visit_body(body);
222 self.tables = old_tables;
225 fn visit_variant_data(
227 def: &'tcx hir::VariantData<'tcx>,
229 _: &hir::Generics<'_>,
233 let has_repr_c = self.repr_has_repr_c;
234 let inherited_pub_visibility = self.inherited_pub_visibility;
235 let live_fields = def
238 .filter(|f| has_repr_c || inherited_pub_visibility || f.vis.node.is_pub());
239 self.live_symbols.extend(live_fields.map(|f| f.hir_id));
241 intravisit::walk_struct_def(self, def);
244 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
246 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
247 let res = self.tables.qpath_res(qpath, expr.hir_id);
248 self.handle_res(res);
250 hir::ExprKind::MethodCall(..) => {
251 self.lookup_and_handle_method(expr.hir_id);
253 hir::ExprKind::Field(ref lhs, ..) => {
254 self.handle_field_access(&lhs, expr.hir_id);
256 hir::ExprKind::Struct(_, ref fields, _) => {
257 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind {
258 self.mark_as_used_if_union(adt, fields);
264 intravisit::walk_expr(self, expr);
267 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
268 // Inside the body, ignore constructions of variants
269 // necessary for the pattern to match. Those construction sites
270 // can't be reached unless the variant is constructed elsewhere.
271 let len = self.ignore_variant_stack.len();
272 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
273 intravisit::walk_arm(self, arm);
274 self.ignore_variant_stack.truncate(len);
277 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
279 PatKind::Struct(ref path, ref fields, _) => {
280 let res = self.tables.qpath_res(path, pat.hir_id);
281 self.handle_field_pattern_match(pat, res, fields);
283 PatKind::Path(ref qpath) => {
284 let res = self.tables.qpath_res(qpath, pat.hir_id);
285 self.handle_res(res);
291 intravisit::walk_pat(self, pat);
295 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
296 self.handle_res(path.res);
297 intravisit::walk_path(self, path);
300 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
302 TyKind::Def(item_id, _) => {
303 let item = self.tcx.hir().expect_item(item_id.id);
304 intravisit::walk_item(self, item);
308 intravisit::walk_ty(self, ty);
311 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
312 self.live_symbols.insert(c.hir_id);
313 intravisit::walk_anon_const(self, c);
317 fn has_allow_dead_code_or_lang_attr(
320 attrs: &[ast::Attribute],
322 if attr::contains_name(attrs, sym::lang) {
326 // Stable attribute for #[lang = "panic_impl"]
327 if attr::contains_name(attrs, sym::panic_handler) {
331 // (To be) stable attribute for #[lang = "oom"]
332 if attr::contains_name(attrs, sym::alloc_error_handler) {
336 let def_id = tcx.hir().local_def_id(id);
337 let cg_attrs = tcx.codegen_fn_attrs(def_id);
339 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
340 // forcefully, e.g., for placing it in a specific section.
341 if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
345 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
348 // This visitor seeds items that
349 // 1) We want to explicitly consider as live:
350 // * Item annotated with #[allow(dead_code)]
351 // - This is done so that if we want to suppress warnings for a
352 // group of dead functions, we only have to annotate the "root".
353 // For example, if both `f` and `g` are dead and `f` calls `g`,
354 // then annotating `f` with `#[allow(dead_code)]` will suppress
355 // warning for both `f` and `g`.
356 // * Item annotated with #[lang=".."]
357 // - This is because lang items are always callable from elsewhere.
359 // 2) We are not sure to be live or not
360 // * Implementation of a trait method
361 struct LifeSeeder<'k, 'tcx> {
362 worklist: Vec<hir::HirId>,
363 krate: &'k hir::Crate<'k>,
365 // see `MarkSymbolVisitor::struct_constructors`
366 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
369 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
370 fn visit_item(&mut self, item: &hir::Item<'_>) {
371 let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id, &item.attrs);
373 self.worklist.push(item.hir_id);
376 hir::ItemKind::Enum(ref enum_def, _) => {
378 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.id));
381 for variant in enum_def.variants {
382 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
383 self.struct_constructors.insert(ctor_hir_id, variant.id);
387 hir::ItemKind::Trait(.., trait_item_refs) => {
388 for trait_item_ref in trait_item_refs {
389 let trait_item = self.krate.trait_item(trait_item_ref.id);
390 match trait_item.kind {
391 hir::TraitItemKind::Const(_, Some(_))
392 | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
393 if has_allow_dead_code_or_lang_attr(
398 self.worklist.push(trait_item.hir_id);
405 hir::ItemKind::Impl(.., ref opt_trait, _, impl_item_refs) => {
406 for impl_item_ref in impl_item_refs {
407 let impl_item = self.krate.impl_item(impl_item_ref.id);
408 if opt_trait.is_some()
409 || has_allow_dead_code_or_lang_attr(
415 self.worklist.push(impl_item_ref.id.hir_id);
419 hir::ItemKind::Struct(ref variant_data, _) => {
420 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
421 self.struct_constructors.insert(ctor_hir_id, item.hir_id);
428 fn visit_trait_item(&mut self, _item: &hir::TraitItem<'_>) {
429 // ignore: we are handling this in `visit_item` above
432 fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
433 // ignore: we are handling this in `visit_item` above
437 fn create_and_seed_worklist<'tcx>(
439 access_levels: &privacy::AccessLevels,
440 krate: &hir::Crate<'_>,
441 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
442 let worklist = access_levels
447 if level >= &privacy::AccessLevel::Reachable { Some(id) } else { None }
452 tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap()),
454 .collect::<Vec<_>>();
456 // Seed implemented trait items
457 let mut life_seeder =
458 LifeSeeder { worklist, krate, tcx, struct_constructors: Default::default() };
459 krate.visit_all_item_likes(&mut life_seeder);
461 (life_seeder.worklist, life_seeder.struct_constructors)
466 access_levels: &privacy::AccessLevels,
467 krate: &hir::Crate<'_>,
468 ) -> FxHashSet<hir::HirId> {
469 let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
470 let mut symbol_visitor = MarkSymbolVisitor {
473 tables: &ty::TypeckTables::empty(None),
474 live_symbols: Default::default(),
475 repr_has_repr_c: false,
477 inherited_pub_visibility: false,
478 ignore_variant_stack: vec![],
481 symbol_visitor.mark_live_symbols();
482 symbol_visitor.live_symbols
485 struct DeadVisitor<'tcx> {
487 live_symbols: FxHashSet<hir::HirId>,
490 impl DeadVisitor<'tcx> {
491 fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
492 let should_warn = match item.kind {
493 hir::ItemKind::Static(..)
494 | hir::ItemKind::Const(..)
495 | hir::ItemKind::Fn(..)
496 | hir::ItemKind::TyAlias(..)
497 | hir::ItemKind::Enum(..)
498 | hir::ItemKind::Struct(..)
499 | hir::ItemKind::Union(..) => true,
502 should_warn && !self.symbol_is_live(item.hir_id)
505 fn should_warn_about_field(&mut self, field: &hir::StructField<'_>) -> bool {
506 let field_type = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
507 !field.is_positional()
508 && !self.symbol_is_live(field.hir_id)
509 && !field_type.is_phantom_data()
510 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
513 fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
514 !self.symbol_is_live(variant.id)
515 && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id, &variant.attrs)
518 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
519 !self.symbol_is_live(fi.hir_id)
520 && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
523 // id := HIR id of an item's definition.
524 fn symbol_is_live(&mut self, id: hir::HirId) -> bool {
525 if self.live_symbols.contains(&id) {
528 // If it's a type whose items are live, then it's live, too.
529 // This is done to handle the case where, for example, the static
530 // method of a private type is used, but the type itself is never
532 let def_id = self.tcx.hir().local_def_id(id);
533 let inherent_impls = self.tcx.inherent_impls(def_id);
534 for &impl_did in inherent_impls.iter() {
535 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
536 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
537 if self.live_symbols.contains(&item_hir_id) {
549 span: rustc_span::Span,
554 if !name.as_str().starts_with("_") {
556 lint::builtin::DEAD_CODE,
559 &format!("{} is never {}: `{}`", node_type, participle, name),
565 impl Visitor<'tcx> for DeadVisitor<'tcx> {
566 /// Walk nested items in place so that we don't report dead-code
567 /// on inner functions when the outer function is already getting
568 /// an error. We could do this also by checking the parents, but
569 /// this is how the code is setup and it seems harmless enough.
570 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
571 NestedVisitorMap::All(&self.tcx.hir())
574 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
575 if self.should_warn_about_item(item) {
576 // For most items, we want to highlight its identifier
577 let span = match item.kind {
578 hir::ItemKind::Fn(..)
579 | hir::ItemKind::Mod(..)
580 | hir::ItemKind::Enum(..)
581 | hir::ItemKind::Struct(..)
582 | hir::ItemKind::Union(..)
583 | hir::ItemKind::Trait(..)
584 | hir::ItemKind::Impl(..) => {
585 // FIXME(66095): Because item.span is annotated with things
586 // like expansion data, and ident.span isn't, we use the
587 // def_span method if it's part of a macro invocation
588 // (and thus has asource_callee set).
589 // We should probably annotate ident.span with the macro
590 // context, but that's a larger change.
591 if item.span.source_callee().is_some() {
592 self.tcx.sess.source_map().def_span(item.span)
599 let participle = match item.kind {
600 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
607 item.kind.descriptive_variant(),
611 // Only continue if we didn't warn
612 intravisit::walk_item(self, item);
618 variant: &'tcx hir::Variant<'tcx>,
619 g: &'tcx hir::Generics<'tcx>,
622 if self.should_warn_about_variant(&variant) {
631 intravisit::walk_variant(self, variant, g, id);
635 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
636 if self.should_warn_about_foreign_item(fi) {
641 fi.kind.descriptive_variant(),
645 intravisit::walk_foreign_item(self, fi);
648 fn visit_struct_field(&mut self, field: &'tcx hir::StructField<'tcx>) {
649 if self.should_warn_about_field(&field) {
650 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "read");
652 intravisit::walk_struct_field(self, field);
655 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
656 match impl_item.kind {
657 hir::ImplItemKind::Const(_, body_id) => {
658 if !self.symbol_is_live(impl_item.hir_id) {
662 impl_item.ident.name,
667 self.visit_nested_body(body_id)
669 hir::ImplItemKind::Method(_, body_id) => {
670 if !self.symbol_is_live(impl_item.hir_id) {
671 let span = self.tcx.sess.source_map().def_span(impl_item.span);
675 impl_item.ident.name,
680 self.visit_nested_body(body_id)
682 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => {}
686 // Overwrite so that we don't warn the trait item itself.
687 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
688 match trait_item.kind {
689 hir::TraitItemKind::Const(_, Some(body_id))
690 | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
691 self.visit_nested_body(body_id)
693 hir::TraitItemKind::Const(_, None)
694 | hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))
695 | hir::TraitItemKind::Type(..) => {}
700 pub fn check_crate(tcx: TyCtxt<'_>) {
701 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
702 let krate = tcx.hir().krate();
703 let live_symbols = find_live(tcx, access_levels, krate);
704 let mut visitor = DeadVisitor { tcx, live_symbols };
705 intravisit::walk_crate(&mut visitor, krate);