2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_index::vec::{Enumerated, IndexVec};
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
7 use smallvec::SmallVec;
10 use std::ops::{Index, IndexMut};
12 use self::abs_domain::{AbstractElem, Lift};
16 rustc_index::newtype_index! {
17 pub struct MovePathIndex {
22 rustc_index::newtype_index! {
23 pub struct MoveOutIndex {
28 rustc_index::newtype_index! {
29 pub struct InitIndex {
35 pub fn move_path_index(&self, move_data: &MoveData<'_>) -> MovePathIndex {
36 move_data.moves[*self].path
40 /// `MovePath` is a canonicalized representation of a path that is
41 /// moved or assigned to.
43 /// It follows a tree structure.
45 /// Given `struct X { m: M, n: N }` and `x: X`, moves like `drop x.m;`
46 /// move *out* of the place `x.m`.
48 /// The MovePaths representing `x.m` and `x.n` are siblings (that is,
49 /// one of them will link to the other via the `next_sibling` field,
50 /// and the other will have no entry in its `next_sibling` field), and
51 /// they both have the MovePath representing `x` as their parent.
53 pub struct MovePath<'tcx> {
54 pub next_sibling: Option<MovePathIndex>,
55 pub first_child: Option<MovePathIndex>,
56 pub parent: Option<MovePathIndex>,
57 pub place: Place<'tcx>,
60 impl<'tcx> MovePath<'tcx> {
61 /// Returns an iterator over the parents of `self`.
64 move_paths: &'a IndexVec<MovePathIndex, MovePath<'tcx>>,
65 ) -> impl 'a + Iterator<Item = (MovePathIndex, &'a MovePath<'tcx>)> {
66 let first = self.parent.map(|mpi| (mpi, &move_paths[mpi]));
69 fetch_next: move |_, parent: &MovePath<'_>| {
70 parent.parent.map(|mpi| (mpi, &move_paths[mpi]))
75 /// Returns an iterator over the immediate children of `self`.
78 move_paths: &'a IndexVec<MovePathIndex, MovePath<'tcx>>,
79 ) -> impl 'a + Iterator<Item = (MovePathIndex, &'a MovePath<'tcx>)> {
80 let first = self.first_child.map(|mpi| (mpi, &move_paths[mpi]));
83 fetch_next: move |_, child: &MovePath<'_>| {
84 child.next_sibling.map(|mpi| (mpi, &move_paths[mpi]))
89 /// Finds the closest descendant of `self` for which `f` returns `true` using a breadth-first
92 /// `f` will **not** be called on `self`.
93 pub fn find_descendant(
95 move_paths: &IndexVec<MovePathIndex, MovePath<'_>>,
96 f: impl Fn(MovePathIndex) -> bool,
97 ) -> Option<MovePathIndex> {
98 let mut todo = if let Some(child) = self.first_child {
104 while let Some(mpi) = todo.pop() {
109 let move_path = &move_paths[mpi];
110 if let Some(child) = move_path.first_child {
114 // After we've processed the original `mpi`, we should always
115 // traverse the siblings of any of its children.
116 if let Some(sibling) = move_path.next_sibling {
125 impl<'tcx> fmt::Debug for MovePath<'tcx> {
126 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
127 write!(w, "MovePath {{")?;
128 if let Some(parent) = self.parent {
129 write!(w, " parent: {:?},", parent)?;
131 if let Some(first_child) = self.first_child {
132 write!(w, " first_child: {:?},", first_child)?;
134 if let Some(next_sibling) = self.next_sibling {
135 write!(w, " next_sibling: {:?}", next_sibling)?;
137 write!(w, " place: {:?} }}", self.place)
141 impl<'tcx> fmt::Display for MovePath<'tcx> {
142 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
143 write!(w, "{:?}", self.place)
147 struct MovePathLinearIter<'a, 'tcx, F> {
148 next: Option<(MovePathIndex, &'a MovePath<'tcx>)>,
152 impl<'a, 'tcx, F> Iterator for MovePathLinearIter<'a, 'tcx, F>
154 F: FnMut(MovePathIndex, &'a MovePath<'tcx>) -> Option<(MovePathIndex, &'a MovePath<'tcx>)>,
156 type Item = (MovePathIndex, &'a MovePath<'tcx>);
158 fn next(&mut self) -> Option<Self::Item> {
159 let ret = self.next.take()?;
160 self.next = (self.fetch_next)(ret.0, ret.1);
166 pub struct MoveData<'tcx> {
167 pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
168 pub moves: IndexVec<MoveOutIndex, MoveOut>,
169 /// Each Location `l` is mapped to the MoveOut's that are effects
170 /// of executing the code at `l`. (There can be multiple MoveOut's
171 /// for a given `l` because each MoveOut is associated with one
172 /// particular path being moved.)
173 pub loc_map: LocationMap<SmallVec<[MoveOutIndex; 4]>>,
174 pub path_map: IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
175 pub rev_lookup: MovePathLookup,
176 pub inits: IndexVec<InitIndex, Init>,
177 /// Each Location `l` is mapped to the Inits that are effects
178 /// of executing the code at `l`.
179 pub init_loc_map: LocationMap<SmallVec<[InitIndex; 4]>>,
180 pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
183 pub trait HasMoveData<'tcx> {
184 fn move_data(&self) -> &MoveData<'tcx>;
188 pub struct LocationMap<T> {
189 /// Location-indexed (BasicBlock for outer index, index within BB
190 /// for inner index) map.
191 pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
194 impl<T> Index<Location> for LocationMap<T> {
196 fn index(&self, index: Location) -> &Self::Output {
197 &self.map[index.block][index.statement_index]
201 impl<T> IndexMut<Location> for LocationMap<T> {
202 fn index_mut(&mut self, index: Location) -> &mut Self::Output {
203 &mut self.map[index.block][index.statement_index]
207 impl<T> LocationMap<T>
211 fn new(body: &Body<'_>) -> Self {
216 .map(|block| vec![T::default(); block.statements.len() + 1])
222 /// `MoveOut` represents a point in a program that moves out of some
223 /// L-value; i.e., "creates" uninitialized memory.
225 /// With respect to dataflow analysis:
226 /// - Generated by moves and declaration of uninitialized variables.
227 /// - Killed by assignments to the memory.
228 #[derive(Copy, Clone)]
231 pub path: MovePathIndex,
233 pub source: Location,
236 impl fmt::Debug for MoveOut {
237 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
238 write!(fmt, "{:?}@{:?}", self.path, self.source)
242 /// `Init` represents a point in a program that initializes some L-value;
243 #[derive(Copy, Clone)]
245 /// path being initialized
246 pub path: MovePathIndex,
247 /// location of initialization
248 pub location: InitLocation,
249 /// Extra information about this initialization
253 /// Initializations can be from an argument or from a statement. Arguments
254 /// do not have locations, in those cases the `Local` is kept..
255 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
256 pub enum InitLocation {
261 /// Additional information about the initialization.
262 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
264 /// Deep init, even on panic
266 /// Only does a shallow init
268 /// This doesn't initialize the variable on panic (and a panic is possible).
272 impl fmt::Debug for Init {
273 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
274 write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
279 crate fn span<'tcx>(&self, body: &Body<'tcx>) -> Span {
280 match self.location {
281 InitLocation::Argument(local) => body.local_decls[local].source_info.span,
282 InitLocation::Statement(location) => body.source_info(location).span,
287 /// Tables mapping from a place to its MovePathIndex.
289 pub struct MovePathLookup {
290 locals: IndexVec<Local, MovePathIndex>,
292 /// projections are made from a base-place and a projection
293 /// elem. The base-place will have a unique MovePathIndex; we use
294 /// the latter as the index into the outer vector (narrowing
295 /// subsequent search so that it is solely relative to that
296 /// base-place). For the remaining lookup, we map the projection
297 /// elem to the associated MovePathIndex.
298 projections: FxHashMap<(MovePathIndex, AbstractElem), MovePathIndex>,
303 #[derive(Copy, Clone, Debug)]
304 pub enum LookupResult {
305 Exact(MovePathIndex),
306 Parent(Option<MovePathIndex>),
309 impl MovePathLookup {
310 // Unlike the builder `fn move_path_for` below, this lookup
311 // alternative will *not* create a MovePath on the fly for an
312 // unknown place, but will rather return the nearest available
314 pub fn find(&self, place: PlaceRef<'_>) -> LookupResult {
315 let mut result = self.locals[place.local];
317 for elem in place.projection.iter() {
318 if let Some(&subpath) = self.projections.get(&(result, elem.lift())) {
321 return LookupResult::Parent(Some(result));
325 LookupResult::Exact(result)
328 pub fn find_local(&self, local: Local) -> MovePathIndex {
332 /// An enumerated iterator of `local`s and their associated
333 /// `MovePathIndex`es.
334 pub fn iter_locals_enumerated(&self) -> Enumerated<Local, Iter<'_, MovePathIndex>> {
335 self.locals.iter_enumerated()
340 pub struct IllegalMoveOrigin<'tcx> {
341 pub(crate) location: Location,
342 pub(crate) kind: IllegalMoveOriginKind<'tcx>,
346 pub(crate) enum IllegalMoveOriginKind<'tcx> {
347 /// Illegal move due to attempt to move from behind a reference.
349 /// The place the reference refers to: if erroneous code was trying to
350 /// move from `(*x).f` this will be `*x`.
351 target_place: Place<'tcx>,
354 /// Illegal move due to attempt to move from field of an ADT that
355 /// implements `Drop`. Rust maintains invariant that all `Drop`
356 /// ADT's remain fully-initialized so that user-defined destructor
357 /// can safely read from all of the ADT's fields.
358 InteriorOfTypeWithDestructor { container_ty: Ty<'tcx> },
360 /// Illegal move due to attempt to move out of a slice or array.
361 InteriorOfSliceOrArray { ty: Ty<'tcx>, is_index: bool },
365 pub enum MoveError<'tcx> {
366 IllegalMove { cannot_move_out_of: IllegalMoveOrigin<'tcx> },
367 UnionMove { path: MovePathIndex },
370 impl<'tcx> MoveError<'tcx> {
371 fn cannot_move_out_of(location: Location, kind: IllegalMoveOriginKind<'tcx>) -> Self {
372 let origin = IllegalMoveOrigin { location, kind };
373 MoveError::IllegalMove { cannot_move_out_of: origin }
377 impl<'tcx> MoveData<'tcx> {
381 param_env: ParamEnv<'tcx>,
382 ) -> Result<Self, (Self, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
383 builder::gather_moves(body, tcx, param_env)
386 /// For the move path `mpi`, returns the root local variable (if any) that starts the path.
387 /// (e.g., for a path like `a.b.c` returns `Some(a)`)
388 pub fn base_local(&self, mut mpi: MovePathIndex) -> Option<Local> {
390 let path = &self.move_paths[mpi];
391 if let Some(l) = path.place.as_local() {
394 if let Some(parent) = path.parent {
403 pub fn find_in_move_path_or_its_descendants(
406 pred: impl Fn(MovePathIndex) -> bool,
407 ) -> Option<MovePathIndex> {
412 self.move_paths[root].find_descendant(&self.move_paths, pred)