]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/dataflow/move_paths/mod.rs
Rollup merge of #54257 - alexcrichton:wasm-math-symbols, r=TimNN
[rust.git] / src / librustc_mir / dataflow / move_paths / mod.rs
1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 use rustc::ty::{self, TyCtxt};
13 use rustc::mir::*;
14 use rustc::util::nodemap::FxHashMap;
15 use rustc_data_structures::indexed_vec::{IndexVec};
16 use syntax_pos::{Span};
17
18 use std::fmt;
19 use std::ops::{Index, IndexMut};
20
21 use self::abs_domain::{AbstractElem, Lift};
22
23 mod abs_domain;
24
25 // This submodule holds some newtype'd Index wrappers that are using
26 // NonZero to ensure that Option<Index> occupies only a single word.
27 // They are in a submodule to impose privacy restrictions; namely, to
28 // ensure that other code does not accidentally access `index.0`
29 // (which is likely to yield a subtle off-by-one error).
30 pub(crate) mod indexes {
31     use std::fmt;
32     use std::num::NonZeroUsize;
33     use rustc_data_structures::indexed_vec::Idx;
34
35     macro_rules! new_index {
36         ($Index:ident, $debug_name:expr) => {
37             #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
38             pub struct $Index(NonZeroUsize);
39
40             impl Idx for $Index {
41                 fn new(idx: usize) -> Self {
42                     $Index(NonZeroUsize::new(idx + 1).unwrap())
43                 }
44                 fn index(self) -> usize {
45                     self.0.get() - 1
46                 }
47             }
48
49             impl fmt::Debug for $Index {
50                 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
51                     write!(fmt, "{}{}", $debug_name, self.index())
52                 }
53             }
54         }
55     }
56
57     /// Index into MovePathData.move_paths
58     new_index!(MovePathIndex, "mp");
59
60     /// Index into MoveData.moves.
61     new_index!(MoveOutIndex, "mo");
62
63     /// Index into MoveData.inits.
64     new_index!(InitIndex, "in");
65
66     /// Index into Borrows.locations
67     new_index!(BorrowIndex, "bw");
68 }
69
70 pub use self::indexes::MovePathIndex;
71 pub use self::indexes::MoveOutIndex;
72 pub use self::indexes::InitIndex;
73
74 impl MoveOutIndex {
75     pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex {
76         move_data.moves[*self].path
77     }
78 }
79
80 /// `MovePath` is a canonicalized representation of a path that is
81 /// moved or assigned to.
82 ///
83 /// It follows a tree structure.
84 ///
85 /// Given `struct X { m: M, n: N }` and `x: X`, moves like `drop x.m;`
86 /// move *out* of the place `x.m`.
87 ///
88 /// The MovePaths representing `x.m` and `x.n` are siblings (that is,
89 /// one of them will link to the other via the `next_sibling` field,
90 /// and the other will have no entry in its `next_sibling` field), and
91 /// they both have the MovePath representing `x` as their parent.
92 #[derive(Clone)]
93 pub struct MovePath<'tcx> {
94     pub next_sibling: Option<MovePathIndex>,
95     pub first_child: Option<MovePathIndex>,
96     pub parent: Option<MovePathIndex>,
97     pub place: Place<'tcx>,
98 }
99
100 impl<'tcx> MovePath<'tcx> {
101     pub fn parents(&self, move_paths: &IndexVec<MovePathIndex, MovePath>) -> Vec<MovePathIndex> {
102         let mut parents = Vec::new();
103
104         let mut curr_parent = self.parent;
105         while let Some(parent_mpi) = curr_parent {
106             parents.push(parent_mpi);
107             curr_parent = move_paths[parent_mpi].parent;
108         }
109
110         parents
111     }
112 }
113
114 impl<'tcx> fmt::Debug for MovePath<'tcx> {
115     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
116         write!(w, "MovePath {{")?;
117         if let Some(parent) = self.parent {
118             write!(w, " parent: {:?},", parent)?;
119         }
120         if let Some(first_child) = self.first_child {
121             write!(w, " first_child: {:?},", first_child)?;
122         }
123         if let Some(next_sibling) = self.next_sibling {
124             write!(w, " next_sibling: {:?}", next_sibling)?;
125         }
126         write!(w, " place: {:?} }}", self.place)
127     }
128 }
129
130 impl<'tcx> fmt::Display for MovePath<'tcx> {
131     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
132         write!(w, "{:?}", self.place)
133     }
134 }
135
136 #[derive(Debug)]
137 pub struct MoveData<'tcx> {
138     pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
139     pub moves: IndexVec<MoveOutIndex, MoveOut>,
140     /// Each Location `l` is mapped to the MoveOut's that are effects
141     /// of executing the code at `l`. (There can be multiple MoveOut's
142     /// for a given `l` because each MoveOut is associated with one
143     /// particular path being moved.)
144     pub loc_map: LocationMap<Vec<MoveOutIndex>>,
145     pub path_map: IndexVec<MovePathIndex, Vec<MoveOutIndex>>,
146     pub rev_lookup: MovePathLookup<'tcx>,
147     pub inits: IndexVec<InitIndex, Init>,
148     /// Each Location `l` is mapped to the Inits that are effects
149     /// of executing the code at `l`.
150     pub init_loc_map: LocationMap<Vec<InitIndex>>,
151     pub init_path_map: IndexVec<MovePathIndex, Vec<InitIndex>>,
152 }
153
154 pub trait HasMoveData<'tcx> {
155     fn move_data(&self) -> &MoveData<'tcx>;
156 }
157
158 #[derive(Debug)]
159 pub struct LocationMap<T> {
160     /// Location-indexed (BasicBlock for outer index, index within BB
161     /// for inner index) map.
162     pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
163 }
164
165 impl<T> Index<Location> for LocationMap<T> {
166     type Output = T;
167     fn index(&self, index: Location) -> &Self::Output {
168         &self.map[index.block][index.statement_index]
169     }
170 }
171
172 impl<T> IndexMut<Location> for LocationMap<T> {
173     fn index_mut(&mut self, index: Location) -> &mut Self::Output {
174         &mut self.map[index.block][index.statement_index]
175     }
176 }
177
178 impl<T> LocationMap<T> where T: Default + Clone {
179     fn new(mir: &Mir) -> Self {
180         LocationMap {
181             map: mir.basic_blocks().iter().map(|block| {
182                 vec![T::default(); block.statements.len()+1]
183             }).collect()
184         }
185     }
186 }
187
188 /// `MoveOut` represents a point in a program that moves out of some
189 /// L-value; i.e., "creates" uninitialized memory.
190 ///
191 /// With respect to dataflow analysis:
192 /// - Generated by moves and declaration of uninitialized variables.
193 /// - Killed by assignments to the memory.
194 #[derive(Copy, Clone)]
195 pub struct MoveOut {
196     /// path being moved
197     pub path: MovePathIndex,
198     /// location of move
199     pub source: Location,
200 }
201
202 impl fmt::Debug for MoveOut {
203     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
204         write!(fmt, "{:?}@{:?}", self.path, self.source)
205     }
206 }
207
208 /// `Init` represents a point in a program that initializes some L-value;
209 #[derive(Copy, Clone)]
210 pub struct Init {
211     /// path being initialized
212     pub path: MovePathIndex,
213     /// location of initialization
214     pub location: InitLocation,
215     /// Extra information about this initialization
216     pub kind: InitKind,
217 }
218
219
220 /// Initializations can be from an argument or from a statement. Arguments
221 /// do not have locations, in those cases the `Local` is kept..
222 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
223 pub enum InitLocation {
224     Argument(Local),
225     Statement(Location),
226 }
227
228 /// Additional information about the initialization.
229 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
230 pub enum InitKind {
231     /// Deep init, even on panic
232     Deep,
233     /// Only does a shallow init
234     Shallow,
235     /// This doesn't initialize the variable on panic (and a panic is possible).
236     NonPanicPathOnly,
237 }
238
239 impl fmt::Debug for Init {
240     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
241         write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
242     }
243 }
244
245 impl Init {
246     crate fn span<'gcx>(&self, mir: &Mir<'gcx>) -> Span {
247         match self.location {
248             InitLocation::Argument(local) => mir.local_decls[local].source_info.span,
249             InitLocation::Statement(location) => mir.source_info(location).span,
250         }
251     }
252 }
253
254 /// Tables mapping from a place to its MovePathIndex.
255 #[derive(Debug)]
256 pub struct MovePathLookup<'tcx> {
257     locals: IndexVec<Local, MovePathIndex>,
258
259     /// projections are made from a base-place and a projection
260     /// elem. The base-place will have a unique MovePathIndex; we use
261     /// the latter as the index into the outer vector (narrowing
262     /// subsequent search so that it is solely relative to that
263     /// base-place). For the remaining lookup, we map the projection
264     /// elem to the associated MovePathIndex.
265     projections: FxHashMap<(MovePathIndex, AbstractElem<'tcx>), MovePathIndex>
266 }
267
268 mod builder;
269
270 #[derive(Copy, Clone, Debug)]
271 pub enum LookupResult {
272     Exact(MovePathIndex),
273     Parent(Option<MovePathIndex>)
274 }
275
276 impl<'tcx> MovePathLookup<'tcx> {
277     // Unlike the builder `fn move_path_for` below, this lookup
278     // alternative will *not* create a MovePath on the fly for an
279     // unknown place, but will rather return the nearest available
280     // parent.
281     pub fn find(&self, place: &Place<'tcx>) -> LookupResult {
282         match *place {
283             Place::Local(local) => LookupResult::Exact(self.locals[local]),
284             Place::Promoted(_) |
285             Place::Static(..) => LookupResult::Parent(None),
286             Place::Projection(ref proj) => {
287                 match self.find(&proj.base) {
288                     LookupResult::Exact(base_path) => {
289                         match self.projections.get(&(base_path, proj.elem.lift())) {
290                             Some(&subpath) => LookupResult::Exact(subpath),
291                             None => LookupResult::Parent(Some(base_path))
292                         }
293                     }
294                     inexact => inexact
295                 }
296             }
297         }
298     }
299
300     pub fn find_local(&self, local: Local) -> MovePathIndex {
301         self.locals[local]
302     }
303 }
304
305 #[derive(Debug)]
306 pub struct IllegalMoveOrigin<'tcx> {
307     pub(crate) location: Location,
308     pub(crate) kind: IllegalMoveOriginKind<'tcx>,
309 }
310
311 #[derive(Debug)]
312 pub(crate) enum IllegalMoveOriginKind<'tcx> {
313     /// Illegal move due to attempt to move from `static` variable.
314     Static,
315
316     /// Illegal move due to attempt to move from behind a reference.
317     BorrowedContent {
318         /// The place the reference refers to: if erroneous code was trying to
319         /// move from `(*x).f` this will be `*x`.
320         target_place: Place<'tcx>,
321     },
322
323     /// Illegal move due to attempt to move from field of an ADT that
324     /// implements `Drop`. Rust maintains invariant that all `Drop`
325     /// ADT's remain fully-initialized so that user-defined destructor
326     /// can safely read from all of the ADT's fields.
327     InteriorOfTypeWithDestructor { container_ty: ty::Ty<'tcx> },
328
329     /// Illegal move due to attempt to move out of a slice or array.
330     InteriorOfSliceOrArray { ty: ty::Ty<'tcx>, is_index: bool, },
331 }
332
333 #[derive(Debug)]
334 pub enum MoveError<'tcx> {
335     IllegalMove { cannot_move_out_of: IllegalMoveOrigin<'tcx> },
336     UnionMove { path: MovePathIndex },
337 }
338
339 impl<'tcx> MoveError<'tcx> {
340     fn cannot_move_out_of(location: Location, kind: IllegalMoveOriginKind<'tcx>) -> Self {
341         let origin = IllegalMoveOrigin { location, kind };
342         MoveError::IllegalMove { cannot_move_out_of: origin }
343     }
344 }
345
346 impl<'a, 'gcx, 'tcx> MoveData<'tcx> {
347     pub fn gather_moves(mir: &Mir<'tcx>, tcx: TyCtxt<'a, 'gcx, 'tcx>)
348                         -> Result<Self, (Self, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
349         builder::gather_moves(mir, tcx)
350     }
351
352     /// For the move path `mpi`, returns the root local variable (if any) that starts the path.
353     /// (e.g., for a path like `a.b.c` returns `Some(a)`)
354     pub fn base_local(&self, mut mpi: MovePathIndex) -> Option<Local> {
355         loop {
356             let path = &self.move_paths[mpi];
357             if let Place::Local(l) = path.place { return Some(l); }
358             if let Some(parent) = path.parent { mpi = parent; continue } else { return None }
359         }
360     }
361 }