rustc_mir_transform/
lint.rs

1//! This pass statically detects code which has undefined behaviour or is likely to be erroneous.
2//! It can be used to locate problems in MIR building or optimizations. It assumes that all code
3//! can be executed, so it has false positives.
4
5use std::borrow::Cow;
6
7use rustc_data_structures::fx::FxHashSet;
8use rustc_index::bit_set::DenseBitSet;
9use rustc_middle::mir::visit::{PlaceContext, VisitPlacesWith, Visitor};
10use rustc_middle::mir::*;
11use rustc_middle::ty::TyCtxt;
12use rustc_mir_dataflow::impls::{MaybeStorageDead, MaybeStorageLive, always_storage_live_locals};
13use rustc_mir_dataflow::{Analysis, ResultsCursor};
14
15pub(super) fn lint_body<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, when: String) {
16    let always_live_locals = &always_storage_live_locals(body);
17
18    let maybe_storage_live = MaybeStorageLive::new(Cow::Borrowed(always_live_locals))
19        .iterate_to_fixpoint(tcx, body, None)
20        .into_results_cursor(body);
21
22    let maybe_storage_dead = MaybeStorageDead::new(Cow::Borrowed(always_live_locals))
23        .iterate_to_fixpoint(tcx, body, None)
24        .into_results_cursor(body);
25
26    let mut lint = Lint {
27        tcx,
28        when,
29        body,
30        is_fn_like: tcx.def_kind(body.source.def_id()).is_fn_like(),
31        always_live_locals,
32        maybe_storage_live,
33        maybe_storage_dead,
34        places: Default::default(),
35    };
36    for (bb, data) in traversal::reachable(body) {
37        lint.visit_basic_block_data(bb, data);
38    }
39}
40
41struct Lint<'a, 'tcx> {
42    tcx: TyCtxt<'tcx>,
43    when: String,
44    body: &'a Body<'tcx>,
45    is_fn_like: bool,
46    always_live_locals: &'a DenseBitSet<Local>,
47    maybe_storage_live: ResultsCursor<'a, 'tcx, MaybeStorageLive<'a>>,
48    maybe_storage_dead: ResultsCursor<'a, 'tcx, MaybeStorageDead<'a>>,
49    places: FxHashSet<PlaceRef<'tcx>>,
50}
51
52impl<'a, 'tcx> Lint<'a, 'tcx> {
53    #[track_caller]
54    fn fail(&self, location: Location, msg: impl AsRef<str>) {
55        let span = self.body.source_info(location).span;
56        self.tcx.sess.dcx().span_delayed_bug(
57            span,
58            format!(
59                "broken MIR in {:?} ({}) at {:?}:\n{}",
60                self.body.source.instance,
61                self.when,
62                location,
63                msg.as_ref()
64            ),
65        );
66    }
67}
68
69impl<'a, 'tcx> Visitor<'tcx> for Lint<'a, 'tcx> {
70    fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
71        if context.is_use() {
72            self.maybe_storage_dead.seek_after_primary_effect(location);
73            if self.maybe_storage_dead.get().contains(local) {
74                self.fail(location, format!("use of local {local:?}, which has no storage here"));
75            }
76        }
77    }
78
79    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
80        match &statement.kind {
81            StatementKind::Assign(box (dest, rvalue)) => {
82                let forbid_aliasing = match rvalue {
83                    Rvalue::Use(..)
84                    | Rvalue::CopyForDeref(..)
85                    | Rvalue::Repeat(..)
86                    | Rvalue::Aggregate(..)
87                    | Rvalue::Cast(..)
88                    | Rvalue::ShallowInitBox(..)
89                    | Rvalue::WrapUnsafeBinder(..) => true,
90                    Rvalue::ThreadLocalRef(..)
91                    | Rvalue::UnaryOp(..)
92                    | Rvalue::BinaryOp(..)
93                    | Rvalue::Ref(..)
94                    | Rvalue::RawPtr(..)
95                    | Rvalue::Discriminant(..) => false,
96                };
97                // The sides of an assignment must not alias.
98                if forbid_aliasing {
99                    VisitPlacesWith(|src: Place<'tcx>, _| {
100                        if *dest == src
101                            || (dest.local == src.local
102                                && !dest.is_indirect()
103                                && !src.is_indirect())
104                        {
105                            self.fail(
106                                location,
107                                format!(
108                                    "encountered `{statement:?}` statement with overlapping memory"
109                                ),
110                            );
111                        }
112                    })
113                    .visit_rvalue(rvalue, location);
114                }
115            }
116            StatementKind::StorageLive(local) => {
117                self.maybe_storage_live.seek_before_primary_effect(location);
118                if self.maybe_storage_live.get().contains(*local) {
119                    self.fail(
120                        location,
121                        format!("StorageLive({local:?}) which already has storage here"),
122                    );
123                }
124            }
125            _ => {}
126        }
127
128        self.super_statement(statement, location);
129    }
130
131    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
132        match &terminator.kind {
133            TerminatorKind::Return => {
134                if self.is_fn_like {
135                    self.maybe_storage_live.seek_after_primary_effect(location);
136                    for local in self.maybe_storage_live.get().iter() {
137                        if !self.always_live_locals.contains(local) {
138                            self.fail(
139                                location,
140                                format!(
141                                    "local {local:?} still has storage when returning from function"
142                                ),
143                            );
144                        }
145                    }
146                }
147            }
148            TerminatorKind::Call { args, destination, .. } => {
149                // The call destination place and Operand::Move place used as an argument might be
150                // passed by a reference to the callee. Consequently they must be non-overlapping.
151                // Currently this simply checks for duplicate places.
152                self.places.clear();
153                self.places.insert(destination.as_ref());
154                let mut has_duplicates = false;
155                for arg in args {
156                    if let Operand::Move(place) = &arg.node {
157                        has_duplicates |= !self.places.insert(place.as_ref());
158                    }
159                }
160                if has_duplicates {
161                    self.fail(
162                        location,
163                        format!(
164                            "encountered overlapping memory in `Move` arguments to `Call` terminator: {:?}",
165                            terminator.kind,
166                        ),
167                    );
168                }
169            }
170            _ => {}
171        }
172
173        self.super_terminator(terminator, location);
174    }
175}