rustc_mir_dataflow/move_paths/
mod.rs

1//! [`MovePath`]s track the initialization state of places and their sub-paths.
2
3use std::fmt;
4use std::ops::{Index, IndexMut};
5
6use rustc_abi::{FieldIdx, VariantIdx};
7use rustc_data_structures::fx::FxHashMap;
8use rustc_index::{IndexSlice, IndexVec};
9use rustc_middle::mir::*;
10use rustc_middle::ty::{Ty, TyCtxt};
11use rustc_span::Span;
12use smallvec::SmallVec;
13
14use crate::un_derefer::UnDerefer;
15
16rustc_index::newtype_index! {
17    #[orderable]
18    #[debug_format = "mp{}"]
19    pub struct MovePathIndex {}
20}
21
22impl polonius_engine::Atom for MovePathIndex {
23    fn index(self) -> usize {
24        rustc_index::Idx::index(self)
25    }
26}
27
28rustc_index::newtype_index! {
29    #[orderable]
30    #[debug_format = "mo{}"]
31    pub struct MoveOutIndex {}
32}
33
34rustc_index::newtype_index! {
35    #[debug_format = "in{}"]
36    pub struct InitIndex {}
37}
38
39impl MoveOutIndex {
40    pub fn move_path_index(self, move_data: &MoveData<'_>) -> MovePathIndex {
41        move_data.moves[self].path
42    }
43}
44
45/// `MovePath` is a canonicalized representation of a path that is
46/// moved or assigned to.
47///
48/// It follows a tree structure.
49///
50/// Given `struct X { m: M, n: N }` and `x: X`, moves like `drop x.m;`
51/// move *out* of the place `x.m`.
52///
53/// The MovePaths representing `x.m` and `x.n` are siblings (that is,
54/// one of them will link to the other via the `next_sibling` field,
55/// and the other will have no entry in its `next_sibling` field), and
56/// they both have the MovePath representing `x` as their parent.
57#[derive(Clone)]
58pub struct MovePath<'tcx> {
59    pub next_sibling: Option<MovePathIndex>,
60    pub first_child: Option<MovePathIndex>,
61    pub parent: Option<MovePathIndex>,
62    pub place: Place<'tcx>,
63}
64
65impl<'tcx> MovePath<'tcx> {
66    /// Returns an iterator over the parents of `self`.
67    pub fn parents<'a>(
68        &self,
69        move_paths: &'a IndexSlice<MovePathIndex, MovePath<'tcx>>,
70    ) -> impl 'a + Iterator<Item = (MovePathIndex, &'a MovePath<'tcx>)> {
71        let first = self.parent.map(|mpi| (mpi, &move_paths[mpi]));
72        MovePathLinearIter {
73            next: first,
74            fetch_next: move |_, parent: &MovePath<'_>| {
75                parent.parent.map(|mpi| (mpi, &move_paths[mpi]))
76            },
77        }
78    }
79
80    /// Returns an iterator over the immediate children of `self`.
81    pub fn children<'a>(
82        &self,
83        move_paths: &'a IndexSlice<MovePathIndex, MovePath<'tcx>>,
84    ) -> impl 'a + Iterator<Item = (MovePathIndex, &'a MovePath<'tcx>)> {
85        let first = self.first_child.map(|mpi| (mpi, &move_paths[mpi]));
86        MovePathLinearIter {
87            next: first,
88            fetch_next: move |_, child: &MovePath<'_>| {
89                child.next_sibling.map(|mpi| (mpi, &move_paths[mpi]))
90            },
91        }
92    }
93
94    /// Finds the closest descendant of `self` for which `f` returns `true` using a breadth-first
95    /// search.
96    ///
97    /// `f` will **not** be called on `self`.
98    pub fn find_descendant(
99        &self,
100        move_paths: &IndexSlice<MovePathIndex, MovePath<'_>>,
101        f: impl Fn(MovePathIndex) -> bool,
102    ) -> Option<MovePathIndex> {
103        let Some(child) = self.first_child else { return None };
104        let mut todo = vec![child];
105
106        while let Some(mpi) = todo.pop() {
107            if f(mpi) {
108                return Some(mpi);
109            }
110
111            let move_path = &move_paths[mpi];
112            if let Some(child) = move_path.first_child {
113                todo.push(child);
114            }
115
116            // After we've processed the original `mpi`, we should always
117            // traverse the siblings of any of its children.
118            if let Some(sibling) = move_path.next_sibling {
119                todo.push(sibling);
120            }
121        }
122
123        None
124    }
125}
126
127impl<'tcx> fmt::Debug for MovePath<'tcx> {
128    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
129        write!(w, "MovePath {{")?;
130        if let Some(parent) = self.parent {
131            write!(w, " parent: {parent:?},")?;
132        }
133        if let Some(first_child) = self.first_child {
134            write!(w, " first_child: {first_child:?},")?;
135        }
136        if let Some(next_sibling) = self.next_sibling {
137            write!(w, " next_sibling: {next_sibling:?}")?;
138        }
139        write!(w, " place: {:?} }}", self.place)
140    }
141}
142
143impl<'tcx> fmt::Display for MovePath<'tcx> {
144    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
145        write!(w, "{:?}", self.place)
146    }
147}
148
149struct MovePathLinearIter<'a, 'tcx, F> {
150    next: Option<(MovePathIndex, &'a MovePath<'tcx>)>,
151    fetch_next: F,
152}
153
154impl<'a, 'tcx, F> Iterator for MovePathLinearIter<'a, 'tcx, F>
155where
156    F: FnMut(MovePathIndex, &'a MovePath<'tcx>) -> Option<(MovePathIndex, &'a MovePath<'tcx>)>,
157{
158    type Item = (MovePathIndex, &'a MovePath<'tcx>);
159
160    fn next(&mut self) -> Option<Self::Item> {
161        let ret = self.next.take()?;
162        self.next = (self.fetch_next)(ret.0, ret.1);
163        Some(ret)
164    }
165}
166
167#[derive(Debug)]
168pub struct MoveData<'tcx> {
169    pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
170    pub moves: IndexVec<MoveOutIndex, MoveOut>,
171    /// Each Location `l` is mapped to the MoveOut's that are effects
172    /// of executing the code at `l`. (There can be multiple MoveOut's
173    /// for a given `l` because each MoveOut is associated with one
174    /// particular path being moved.)
175    pub loc_map: LocationMap<SmallVec<[MoveOutIndex; 4]>>,
176    pub path_map: IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
177    pub rev_lookup: MovePathLookup<'tcx>,
178    pub inits: IndexVec<InitIndex, Init>,
179    /// Each Location `l` is mapped to the Inits that are effects
180    /// of executing the code at `l`. Only very rarely (e.g. inline asm)
181    /// is there more than one Init at any `l`.
182    pub init_loc_map: LocationMap<SmallVec<[InitIndex; 1]>>,
183    pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
184}
185
186pub trait HasMoveData<'tcx> {
187    fn move_data(&self) -> &MoveData<'tcx>;
188}
189
190#[derive(Debug)]
191pub struct LocationMap<T> {
192    /// Location-indexed (BasicBlock for outer index, index within BB
193    /// for inner index) map.
194    pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
195}
196
197impl<T> Index<Location> for LocationMap<T> {
198    type Output = T;
199    fn index(&self, index: Location) -> &Self::Output {
200        &self.map[index.block][index.statement_index]
201    }
202}
203
204impl<T> IndexMut<Location> for LocationMap<T> {
205    fn index_mut(&mut self, index: Location) -> &mut Self::Output {
206        &mut self.map[index.block][index.statement_index]
207    }
208}
209
210impl<T> LocationMap<T>
211where
212    T: Default + Clone,
213{
214    fn new(body: &Body<'_>) -> Self {
215        LocationMap {
216            map: body
217                .basic_blocks
218                .iter()
219                .map(|block| vec![T::default(); block.statements.len() + 1])
220                .collect(),
221        }
222    }
223}
224
225/// `MoveOut` represents a point in a program that moves out of some
226/// L-value; i.e., "creates" uninitialized memory.
227///
228/// With respect to dataflow analysis:
229/// - Generated by moves and declaration of uninitialized variables.
230/// - Killed by assignments to the memory.
231#[derive(Copy, Clone)]
232pub struct MoveOut {
233    /// path being moved
234    pub path: MovePathIndex,
235    /// location of move
236    pub source: Location,
237}
238
239impl fmt::Debug for MoveOut {
240    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
241        write!(fmt, "{:?}@{:?}", self.path, self.source)
242    }
243}
244
245/// `Init` represents a point in a program that initializes some L-value;
246#[derive(Copy, Clone)]
247pub struct Init {
248    /// path being initialized
249    pub path: MovePathIndex,
250    /// location of initialization
251    pub location: InitLocation,
252    /// Extra information about this initialization
253    pub kind: InitKind,
254}
255
256/// Initializations can be from an argument or from a statement. Arguments
257/// do not have locations, in those cases the `Local` is kept..
258#[derive(Copy, Clone, Debug, PartialEq, Eq)]
259pub enum InitLocation {
260    Argument(Local),
261    Statement(Location),
262}
263
264/// Additional information about the initialization.
265#[derive(Copy, Clone, Debug, PartialEq, Eq)]
266pub enum InitKind {
267    /// Deep init, even on panic
268    Deep,
269    /// Only does a shallow init
270    Shallow,
271    /// This doesn't initialize the variable on panic (and a panic is possible).
272    NonPanicPathOnly,
273}
274
275impl fmt::Debug for Init {
276    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
277        write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
278    }
279}
280
281impl Init {
282    pub fn span<'tcx>(&self, body: &Body<'tcx>) -> Span {
283        match self.location {
284            InitLocation::Argument(local) => body.local_decls[local].source_info.span,
285            InitLocation::Statement(location) => body.source_info(location).span,
286        }
287    }
288}
289
290/// Tables mapping from a place to its MovePathIndex.
291#[derive(Debug)]
292pub struct MovePathLookup<'tcx> {
293    locals: IndexVec<Local, Option<MovePathIndex>>,
294
295    /// projections are made from a base-place and a projection
296    /// elem. The base-place will have a unique MovePathIndex; we use
297    /// the latter as the index into the outer vector (narrowing
298    /// subsequent search so that it is solely relative to that
299    /// base-place). For the remaining lookup, we map the projection
300    /// elem to the associated MovePathIndex.
301    projections: FxHashMap<(MovePathIndex, MoveSubPath), MovePathIndex>,
302
303    un_derefer: UnDerefer<'tcx>,
304}
305
306mod builder;
307
308#[derive(Copy, Clone, Debug)]
309pub enum LookupResult {
310    Exact(MovePathIndex),
311    Parent(Option<MovePathIndex>),
312}
313
314impl<'tcx> MovePathLookup<'tcx> {
315    // Unlike the builder `fn move_path_for` below, this lookup
316    // alternative will *not* create a MovePath on the fly for an
317    // unknown place, but will rather return the nearest available
318    // parent.
319    pub fn find(&self, place: PlaceRef<'tcx>) -> LookupResult {
320        let Some(mut result) = self.find_local(place.local) else {
321            return LookupResult::Parent(None);
322        };
323
324        for (_, elem) in self.un_derefer.iter_projections(place) {
325            let subpath = match MoveSubPath::of(elem.kind()) {
326                MoveSubPathResult::One(kind) => self.projections.get(&(result, kind)),
327                MoveSubPathResult::Subslice { .. } => None, // just use the parent MovePath
328                MoveSubPathResult::Skip => continue,
329                MoveSubPathResult::Stop => None,
330            };
331
332            let Some(&subpath) = subpath else {
333                return LookupResult::Parent(Some(result));
334            };
335            result = subpath;
336        }
337
338        LookupResult::Exact(result)
339    }
340
341    #[inline]
342    pub fn find_local(&self, local: Local) -> Option<MovePathIndex> {
343        self.locals[local]
344    }
345
346    /// An enumerated iterator of `local`s and their associated
347    /// `MovePathIndex`es.
348    pub fn iter_locals_enumerated(
349        &self,
350    ) -> impl DoubleEndedIterator<Item = (Local, MovePathIndex)> {
351        self.locals.iter_enumerated().filter_map(|(l, &idx)| Some((l, idx?)))
352    }
353}
354
355impl<'tcx> MoveData<'tcx> {
356    pub fn gather_moves(
357        body: &Body<'tcx>,
358        tcx: TyCtxt<'tcx>,
359        filter: impl Fn(Ty<'tcx>) -> bool,
360    ) -> MoveData<'tcx> {
361        builder::gather_moves(body, tcx, filter)
362    }
363
364    /// For the move path `mpi`, returns the root local variable that starts the path.
365    /// (e.g., for a path like `a.b.c` returns `a`)
366    pub fn base_local(&self, mut mpi: MovePathIndex) -> Local {
367        loop {
368            let path = &self.move_paths[mpi];
369            if let Some(l) = path.place.as_local() {
370                return l;
371            }
372            mpi = path.parent.expect("root move paths should be locals");
373        }
374    }
375
376    pub fn find_in_move_path_or_its_descendants(
377        &self,
378        root: MovePathIndex,
379        pred: impl Fn(MovePathIndex) -> bool,
380    ) -> Option<MovePathIndex> {
381        if pred(root) {
382            return Some(root);
383        }
384
385        self.move_paths[root].find_descendant(&self.move_paths, pred)
386    }
387}
388
389/// A projection into a move path producing a child path
390#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
391pub enum MoveSubPath {
392    Deref,
393    Field(FieldIdx),
394    ConstantIndex(u64),
395    Downcast(VariantIdx),
396    UnwrapUnsafeBinder,
397}
398
399#[derive(Copy, Clone, Debug, PartialEq, Eq)]
400pub enum MoveSubPathResult {
401    One(MoveSubPath),
402    Subslice { from: u64, to: u64 },
403    Skip,
404    Stop,
405}
406
407impl MoveSubPath {
408    pub fn of(elem: ProjectionKind) -> MoveSubPathResult {
409        let subpath = match elem {
410            // correspond to a MoveSubPath
411            ProjectionKind::Deref => MoveSubPath::Deref,
412            ProjectionKind::Field(idx, _) => MoveSubPath::Field(idx),
413            ProjectionKind::ConstantIndex { offset, min_length: _, from_end: false } => {
414                MoveSubPath::ConstantIndex(offset)
415            }
416            ProjectionKind::Downcast(_, idx) => MoveSubPath::Downcast(idx),
417            ProjectionKind::UnwrapUnsafeBinder(_) => MoveSubPath::UnwrapUnsafeBinder,
418
419            // this should be the same move path as its parent
420            // its fine to skip because it cannot have sibling move paths
421            // and it is not a user visible path
422            ProjectionKind::OpaqueCast(_) => {
423                return MoveSubPathResult::Skip;
424            }
425
426            // these cannot be moved through
427            ProjectionKind::Index(_)
428            | ProjectionKind::ConstantIndex { offset: _, min_length: _, from_end: true }
429            | ProjectionKind::Subslice { from: _, to: _, from_end: true } => {
430                return MoveSubPathResult::Stop;
431            }
432
433            // subslice is special.
434            // it needs to be split into individual move paths
435            ProjectionKind::Subslice { from, to, from_end: false } => {
436                return MoveSubPathResult::Subslice { from, to };
437            }
438        };
439
440        MoveSubPathResult::One(subpath)
441    }
442}