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`.
181    pub init_loc_map: LocationMap<SmallVec<[InitIndex; 4]>>,
182    pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
183}
184
185pub trait HasMoveData<'tcx> {
186    fn move_data(&self) -> &MoveData<'tcx>;
187}
188
189#[derive(Debug)]
190pub struct LocationMap<T> {
191    /// Location-indexed (BasicBlock for outer index, index within BB
192    /// for inner index) map.
193    pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
194}
195
196impl<T> Index<Location> for LocationMap<T> {
197    type Output = T;
198    fn index(&self, index: Location) -> &Self::Output {
199        &self.map[index.block][index.statement_index]
200    }
201}
202
203impl<T> IndexMut<Location> for LocationMap<T> {
204    fn index_mut(&mut self, index: Location) -> &mut Self::Output {
205        &mut self.map[index.block][index.statement_index]
206    }
207}
208
209impl<T> LocationMap<T>
210where
211    T: Default + Clone,
212{
213    fn new(body: &Body<'_>) -> Self {
214        LocationMap {
215            map: body
216                .basic_blocks
217                .iter()
218                .map(|block| vec![T::default(); block.statements.len() + 1])
219                .collect(),
220        }
221    }
222}
223
224/// `MoveOut` represents a point in a program that moves out of some
225/// L-value; i.e., "creates" uninitialized memory.
226///
227/// With respect to dataflow analysis:
228/// - Generated by moves and declaration of uninitialized variables.
229/// - Killed by assignments to the memory.
230#[derive(Copy, Clone)]
231pub struct MoveOut {
232    /// path being moved
233    pub path: MovePathIndex,
234    /// location of move
235    pub source: Location,
236}
237
238impl fmt::Debug for MoveOut {
239    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
240        write!(fmt, "{:?}@{:?}", self.path, self.source)
241    }
242}
243
244/// `Init` represents a point in a program that initializes some L-value;
245#[derive(Copy, Clone)]
246pub struct Init {
247    /// path being initialized
248    pub path: MovePathIndex,
249    /// location of initialization
250    pub location: InitLocation,
251    /// Extra information about this initialization
252    pub kind: InitKind,
253}
254
255/// Initializations can be from an argument or from a statement. Arguments
256/// do not have locations, in those cases the `Local` is kept..
257#[derive(Copy, Clone, Debug, PartialEq, Eq)]
258pub enum InitLocation {
259    Argument(Local),
260    Statement(Location),
261}
262
263/// Additional information about the initialization.
264#[derive(Copy, Clone, Debug, PartialEq, Eq)]
265pub enum InitKind {
266    /// Deep init, even on panic
267    Deep,
268    /// Only does a shallow init
269    Shallow,
270    /// This doesn't initialize the variable on panic (and a panic is possible).
271    NonPanicPathOnly,
272}
273
274impl fmt::Debug for Init {
275    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
276        write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
277    }
278}
279
280impl Init {
281    pub fn span<'tcx>(&self, body: &Body<'tcx>) -> Span {
282        match self.location {
283            InitLocation::Argument(local) => body.local_decls[local].source_info.span,
284            InitLocation::Statement(location) => body.source_info(location).span,
285        }
286    }
287}
288
289/// Tables mapping from a place to its MovePathIndex.
290#[derive(Debug)]
291pub struct MovePathLookup<'tcx> {
292    locals: IndexVec<Local, Option<MovePathIndex>>,
293
294    /// projections are made from a base-place and a projection
295    /// elem. The base-place will have a unique MovePathIndex; we use
296    /// the latter as the index into the outer vector (narrowing
297    /// subsequent search so that it is solely relative to that
298    /// base-place). For the remaining lookup, we map the projection
299    /// elem to the associated MovePathIndex.
300    projections: FxHashMap<(MovePathIndex, MoveSubPath), MovePathIndex>,
301
302    un_derefer: UnDerefer<'tcx>,
303}
304
305mod builder;
306
307#[derive(Copy, Clone, Debug)]
308pub enum LookupResult {
309    Exact(MovePathIndex),
310    Parent(Option<MovePathIndex>),
311}
312
313impl<'tcx> MovePathLookup<'tcx> {
314    // Unlike the builder `fn move_path_for` below, this lookup
315    // alternative will *not* create a MovePath on the fly for an
316    // unknown place, but will rather return the nearest available
317    // parent.
318    pub fn find(&self, place: PlaceRef<'tcx>) -> LookupResult {
319        let Some(mut result) = self.find_local(place.local) else {
320            return LookupResult::Parent(None);
321        };
322
323        for (_, elem) in self.un_derefer.iter_projections(place) {
324            let subpath = match MoveSubPath::of(elem.kind()) {
325                MoveSubPathResult::One(kind) => self.projections.get(&(result, kind)),
326                MoveSubPathResult::Subslice { .. } => None, // just use the parent MovePath
327                MoveSubPathResult::Skip => continue,
328                MoveSubPathResult::Stop => None,
329            };
330
331            let Some(&subpath) = subpath else {
332                return LookupResult::Parent(Some(result));
333            };
334            result = subpath;
335        }
336
337        LookupResult::Exact(result)
338    }
339
340    #[inline]
341    pub fn find_local(&self, local: Local) -> Option<MovePathIndex> {
342        self.locals[local]
343    }
344
345    /// An enumerated iterator of `local`s and their associated
346    /// `MovePathIndex`es.
347    pub fn iter_locals_enumerated(
348        &self,
349    ) -> impl DoubleEndedIterator<Item = (Local, MovePathIndex)> {
350        self.locals.iter_enumerated().filter_map(|(l, &idx)| Some((l, idx?)))
351    }
352}
353
354impl<'tcx> MoveData<'tcx> {
355    pub fn gather_moves(
356        body: &Body<'tcx>,
357        tcx: TyCtxt<'tcx>,
358        filter: impl Fn(Ty<'tcx>) -> bool,
359    ) -> MoveData<'tcx> {
360        builder::gather_moves(body, tcx, filter)
361    }
362
363    /// For the move path `mpi`, returns the root local variable that starts the path.
364    /// (e.g., for a path like `a.b.c` returns `a`)
365    pub fn base_local(&self, mut mpi: MovePathIndex) -> Local {
366        loop {
367            let path = &self.move_paths[mpi];
368            if let Some(l) = path.place.as_local() {
369                return l;
370            }
371            mpi = path.parent.expect("root move paths should be locals");
372        }
373    }
374
375    pub fn find_in_move_path_or_its_descendants(
376        &self,
377        root: MovePathIndex,
378        pred: impl Fn(MovePathIndex) -> bool,
379    ) -> Option<MovePathIndex> {
380        if pred(root) {
381            return Some(root);
382        }
383
384        self.move_paths[root].find_descendant(&self.move_paths, pred)
385    }
386}
387
388/// A projection into a move path producing a child path
389#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
390pub enum MoveSubPath {
391    Deref,
392    Field(FieldIdx),
393    ConstantIndex(u64),
394    Downcast(VariantIdx),
395    UnwrapUnsafeBinder,
396}
397
398#[derive(Copy, Clone, Debug, PartialEq, Eq)]
399pub enum MoveSubPathResult {
400    One(MoveSubPath),
401    Subslice { from: u64, to: u64 },
402    Skip,
403    Stop,
404}
405
406impl MoveSubPath {
407    pub fn of(elem: ProjectionKind) -> MoveSubPathResult {
408        let subpath = match elem {
409            // correspond to a MoveSubPath
410            ProjectionKind::Deref => MoveSubPath::Deref,
411            ProjectionKind::Field(idx, _) => MoveSubPath::Field(idx),
412            ProjectionKind::ConstantIndex { offset, min_length: _, from_end: false } => {
413                MoveSubPath::ConstantIndex(offset)
414            }
415            ProjectionKind::Downcast(_, idx) => MoveSubPath::Downcast(idx),
416            ProjectionKind::UnwrapUnsafeBinder(_) => MoveSubPath::UnwrapUnsafeBinder,
417
418            // this should be the same move path as its parent
419            // its fine to skip because it cannot have sibling move paths
420            // and it is not a user visible path
421            ProjectionKind::OpaqueCast(_) => {
422                return MoveSubPathResult::Skip;
423            }
424
425            // these cannot be moved through
426            ProjectionKind::Index(_)
427            | ProjectionKind::ConstantIndex { offset: _, min_length: _, from_end: true }
428            | ProjectionKind::Subslice { from: _, to: _, from_end: true } => {
429                return MoveSubPathResult::Stop;
430            }
431
432            // subslice is special.
433            // it needs to be split into individual move paths
434            ProjectionKind::Subslice { from, to, from_end: false } => {
435                return MoveSubPathResult::Subslice { from, to };
436            }
437        };
438
439        MoveSubPathResult::One(subpath)
440    }
441}