]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/dataflow/move_paths/builder.rs
Reorder yield visitation order to match call
[rust.git] / src / librustc_mir / dataflow / move_paths / builder.rs
1 use rustc::mir::tcx::RvalueInitializationState;
2 use rustc::mir::*;
3 use rustc::ty::{self, TyCtxt};
4 use rustc_index::vec::IndexVec;
5 use smallvec::{smallvec, SmallVec};
6
7 use std::convert::TryInto;
8 use std::mem;
9
10 use super::abs_domain::Lift;
11 use super::IllegalMoveOriginKind::*;
12 use super::{Init, InitIndex, InitKind, InitLocation, LookupResult, MoveError};
13 use super::{
14     LocationMap, MoveData, MoveOut, MoveOutIndex, MovePath, MovePathIndex, MovePathLookup,
15 };
16
17 struct MoveDataBuilder<'a, 'tcx> {
18     body: &'a Body<'tcx>,
19     tcx: TyCtxt<'tcx>,
20     param_env: ty::ParamEnv<'tcx>,
21     data: MoveData<'tcx>,
22     errors: Vec<(Place<'tcx>, MoveError<'tcx>)>,
23 }
24
25 impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> {
26     fn new(body: &'a Body<'tcx>, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
27         let mut move_paths = IndexVec::new();
28         let mut path_map = IndexVec::new();
29         let mut init_path_map = IndexVec::new();
30
31         MoveDataBuilder {
32             body,
33             tcx,
34             param_env,
35             errors: Vec::new(),
36             data: MoveData {
37                 moves: IndexVec::new(),
38                 loc_map: LocationMap::new(body),
39                 rev_lookup: MovePathLookup {
40                     locals: body
41                         .local_decls
42                         .indices()
43                         .map(|i| {
44                             Self::new_move_path(
45                                 &mut move_paths,
46                                 &mut path_map,
47                                 &mut init_path_map,
48                                 None,
49                                 Place::from(i),
50                             )
51                         })
52                         .collect(),
53                     projections: Default::default(),
54                 },
55                 move_paths,
56                 path_map,
57                 inits: IndexVec::new(),
58                 init_loc_map: LocationMap::new(body),
59                 init_path_map,
60             },
61         }
62     }
63
64     fn new_move_path(
65         move_paths: &mut IndexVec<MovePathIndex, MovePath<'tcx>>,
66         path_map: &mut IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
67         init_path_map: &mut IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
68         parent: Option<MovePathIndex>,
69         place: Place<'tcx>,
70     ) -> MovePathIndex {
71         let move_path =
72             move_paths.push(MovePath { next_sibling: None, first_child: None, parent, place });
73
74         if let Some(parent) = parent {
75             let next_sibling = mem::replace(&mut move_paths[parent].first_child, Some(move_path));
76             move_paths[move_path].next_sibling = next_sibling;
77         }
78
79         let path_map_ent = path_map.push(smallvec![]);
80         assert_eq!(path_map_ent, move_path);
81
82         let init_path_map_ent = init_path_map.push(smallvec![]);
83         assert_eq!(init_path_map_ent, move_path);
84
85         move_path
86     }
87 }
88
89 impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> {
90     /// This creates a MovePath for a given place, returning an `MovePathError`
91     /// if that place can't be moved from.
92     ///
93     /// NOTE: places behind references *do not* get a move path, which is
94     /// problematic for borrowck.
95     ///
96     /// Maybe we should have separate "borrowck" and "moveck" modes.
97     fn move_path_for(&mut self, place: &Place<'tcx>) -> Result<MovePathIndex, MoveError<'tcx>> {
98         debug!("lookup({:?})", place);
99         let mut base = self.builder.data.rev_lookup.locals[place.local];
100
101         // The move path index of the first union that we find. Once this is
102         // some we stop creating child move paths, since moves from unions
103         // move the whole thing.
104         // We continue looking for other move errors though so that moving
105         // from `*(u.f: &_)` isn't allowed.
106         let mut union_path = None;
107
108         for (i, elem) in place.projection.iter().enumerate() {
109             let proj_base = &place.projection[..i];
110             let body = self.builder.body;
111             let tcx = self.builder.tcx;
112             let place_ty = Place::ty_from(place.local, proj_base, body, tcx).ty;
113             match place_ty.kind {
114                 ty::Ref(..) | ty::RawPtr(..) => {
115                     let proj = &place.projection[..i + 1];
116                     return Err(MoveError::cannot_move_out_of(
117                         self.loc,
118                         BorrowedContent {
119                             target_place: Place {
120                                 local: place.local,
121                                 projection: tcx.intern_place_elems(proj),
122                             },
123                         },
124                     ));
125                 }
126                 ty::Adt(adt, _) if adt.has_dtor(tcx) && !adt.is_box() => {
127                     return Err(MoveError::cannot_move_out_of(
128                         self.loc,
129                         InteriorOfTypeWithDestructor { container_ty: place_ty },
130                     ));
131                 }
132                 ty::Adt(adt, _) if adt.is_union() => {
133                     union_path.get_or_insert(base);
134                 }
135                 ty::Slice(_) => {
136                     return Err(MoveError::cannot_move_out_of(
137                         self.loc,
138                         InteriorOfSliceOrArray {
139                             ty: place_ty,
140                             is_index: match elem {
141                                 ProjectionElem::Index(..) => true,
142                                 _ => false,
143                             },
144                         },
145                     ));
146                 }
147                 ty::Array(..) => match elem {
148                     ProjectionElem::Index(..) => {
149                         return Err(MoveError::cannot_move_out_of(
150                             self.loc,
151                             InteriorOfSliceOrArray { ty: place_ty, is_index: true },
152                         ));
153                     }
154                     _ => {}
155                 },
156                 _ => {}
157             };
158
159             if union_path.is_none() {
160                 base = self.add_move_path(base, elem, |tcx| Place {
161                     local: place.local,
162                     projection: tcx.intern_place_elems(&place.projection[..i + 1]),
163                 });
164             }
165         }
166
167         if let Some(base) = union_path {
168             // Move out of union - always move the entire union.
169             Err(MoveError::UnionMove { path: base })
170         } else {
171             Ok(base)
172         }
173     }
174
175     fn add_move_path(
176         &mut self,
177         base: MovePathIndex,
178         elem: &PlaceElem<'tcx>,
179         mk_place: impl FnOnce(TyCtxt<'tcx>) -> Place<'tcx>,
180     ) -> MovePathIndex {
181         let MoveDataBuilder {
182             data: MoveData { rev_lookup, move_paths, path_map, init_path_map, .. },
183             tcx,
184             ..
185         } = self.builder;
186         *rev_lookup.projections.entry((base, elem.lift())).or_insert_with(move || {
187             let path = MoveDataBuilder::new_move_path(
188                 move_paths,
189                 path_map,
190                 init_path_map,
191                 Some(base),
192                 mk_place(*tcx),
193             );
194             path
195         })
196     }
197
198     fn create_move_path(&mut self, place: &Place<'tcx>) {
199         // This is an non-moving access (such as an overwrite or
200         // drop), so this not being a valid move path is OK.
201         let _ = self.move_path_for(place);
202     }
203 }
204
205 impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> {
206     fn finalize(
207         self,
208     ) -> Result<MoveData<'tcx>, (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
209         debug!("{}", {
210             debug!("moves for {:?}:", self.body.span);
211             for (j, mo) in self.data.moves.iter_enumerated() {
212                 debug!("    {:?} = {:?}", j, mo);
213             }
214             debug!("move paths for {:?}:", self.body.span);
215             for (j, path) in self.data.move_paths.iter_enumerated() {
216                 debug!("    {:?} = {:?}", j, path);
217             }
218             "done dumping moves"
219         });
220
221         if !self.errors.is_empty() { Err((self.data, self.errors)) } else { Ok(self.data) }
222     }
223 }
224
225 pub(super) fn gather_moves<'tcx>(
226     body: &Body<'tcx>,
227     tcx: TyCtxt<'tcx>,
228     param_env: ty::ParamEnv<'tcx>,
229 ) -> Result<MoveData<'tcx>, (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
230     let mut builder = MoveDataBuilder::new(body, tcx, param_env);
231
232     builder.gather_args();
233
234     for (bb, block) in body.basic_blocks().iter_enumerated() {
235         for (i, stmt) in block.statements.iter().enumerate() {
236             let source = Location { block: bb, statement_index: i };
237             builder.gather_statement(source, stmt);
238         }
239
240         let terminator_loc = Location { block: bb, statement_index: block.statements.len() };
241         builder.gather_terminator(terminator_loc, block.terminator());
242     }
243
244     builder.finalize()
245 }
246
247 impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> {
248     fn gather_args(&mut self) {
249         for arg in self.body.args_iter() {
250             let path = self.data.rev_lookup.locals[arg];
251
252             let init = self.data.inits.push(Init {
253                 path,
254                 kind: InitKind::Deep,
255                 location: InitLocation::Argument(arg),
256             });
257
258             debug!("gather_args: adding init {:?} of {:?} for argument {:?}", init, path, arg);
259
260             self.data.init_path_map[path].push(init);
261         }
262     }
263
264     fn gather_statement(&mut self, loc: Location, stmt: &Statement<'tcx>) {
265         debug!("gather_statement({:?}, {:?})", loc, stmt);
266         (Gatherer { builder: self, loc }).gather_statement(stmt);
267     }
268
269     fn gather_terminator(&mut self, loc: Location, term: &Terminator<'tcx>) {
270         debug!("gather_terminator({:?}, {:?})", loc, term);
271         (Gatherer { builder: self, loc }).gather_terminator(term);
272     }
273 }
274
275 struct Gatherer<'b, 'a, 'tcx> {
276     builder: &'b mut MoveDataBuilder<'a, 'tcx>,
277     loc: Location,
278 }
279
280 impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> {
281     fn gather_statement(&mut self, stmt: &Statement<'tcx>) {
282         match stmt.kind {
283             StatementKind::Assign(box (ref place, ref rval)) => {
284                 self.create_move_path(place);
285                 if let RvalueInitializationState::Shallow = rval.initialization_state() {
286                     // Box starts out uninitialized - need to create a separate
287                     // move-path for the interior so it will be separate from
288                     // the exterior.
289                     self.create_move_path(&self.builder.tcx.mk_place_deref(place.clone()));
290                     self.gather_init(place.as_ref(), InitKind::Shallow);
291                 } else {
292                     self.gather_init(place.as_ref(), InitKind::Deep);
293                 }
294                 self.gather_rvalue(rval);
295             }
296             StatementKind::FakeRead(_, ref place) => {
297                 self.create_move_path(place);
298             }
299             StatementKind::InlineAsm(ref asm) => {
300                 for (output, kind) in asm.outputs.iter().zip(&asm.asm.outputs) {
301                     if !kind.is_indirect {
302                         self.gather_init(output.as_ref(), InitKind::Deep);
303                     }
304                 }
305                 for (_, input) in asm.inputs.iter() {
306                     self.gather_operand(input);
307                 }
308             }
309             StatementKind::StorageLive(_) => {}
310             StatementKind::StorageDead(local) => {
311                 self.gather_move(&Place::from(local));
312             }
313             StatementKind::SetDiscriminant { .. } => {
314                 span_bug!(
315                     stmt.source_info.span,
316                     "SetDiscriminant should not exist during borrowck"
317                 );
318             }
319             StatementKind::Retag { .. }
320             | StatementKind::AscribeUserType(..)
321             | StatementKind::Nop => {}
322         }
323     }
324
325     fn gather_rvalue(&mut self, rvalue: &Rvalue<'tcx>) {
326         match *rvalue {
327             Rvalue::Use(ref operand)
328             | Rvalue::Repeat(ref operand, _)
329             | Rvalue::Cast(_, ref operand, _)
330             | Rvalue::UnaryOp(_, ref operand) => self.gather_operand(operand),
331             Rvalue::BinaryOp(ref _binop, ref lhs, ref rhs)
332             | Rvalue::CheckedBinaryOp(ref _binop, ref lhs, ref rhs) => {
333                 self.gather_operand(lhs);
334                 self.gather_operand(rhs);
335             }
336             Rvalue::Aggregate(ref _kind, ref operands) => {
337                 for operand in operands {
338                     self.gather_operand(operand);
339                 }
340             }
341             Rvalue::Ref(..)
342             | Rvalue::AddressOf(..)
343             | Rvalue::Discriminant(..)
344             | Rvalue::Len(..)
345             | Rvalue::NullaryOp(NullOp::SizeOf, _)
346             | Rvalue::NullaryOp(NullOp::Box, _) => {
347                 // This returns an rvalue with uninitialized contents. We can't
348                 // move out of it here because it is an rvalue - assignments always
349                 // completely initialize their place.
350                 //
351                 // However, this does not matter - MIR building is careful to
352                 // only emit a shallow free for the partially-initialized
353                 // temporary.
354                 //
355                 // In any case, if we want to fix this, we have to register a
356                 // special move and change the `statement_effect` functions.
357             }
358         }
359     }
360
361     fn gather_terminator(&mut self, term: &Terminator<'tcx>) {
362         match term.kind {
363             TerminatorKind::Goto { target: _ }
364             | TerminatorKind::Resume
365             | TerminatorKind::Abort
366             | TerminatorKind::GeneratorDrop
367             | TerminatorKind::FalseEdges { .. }
368             | TerminatorKind::FalseUnwind { .. }
369             | TerminatorKind::Unreachable => {}
370
371             TerminatorKind::Return => {
372                 self.gather_move(&Place::return_place());
373             }
374
375             TerminatorKind::Assert { ref cond, .. } => {
376                 self.gather_operand(cond);
377             }
378
379             TerminatorKind::SwitchInt { ref discr, .. } => {
380                 self.gather_operand(discr);
381             }
382
383             TerminatorKind::Yield { ref value, resume_arg: ref place, .. } => {
384                 self.gather_operand(value);
385                 self.create_move_path(place);
386                 self.gather_init(place.as_ref(), InitKind::Deep);
387             }
388
389             TerminatorKind::Drop { ref location, target: _, unwind: _ } => {
390                 self.gather_move(location);
391             }
392             TerminatorKind::DropAndReplace { ref location, ref value, .. } => {
393                 self.create_move_path(location);
394                 self.gather_operand(value);
395                 self.gather_init(location.as_ref(), InitKind::Deep);
396             }
397             TerminatorKind::Call {
398                 ref func,
399                 ref args,
400                 ref destination,
401                 cleanup: _,
402                 from_hir_call: _,
403             } => {
404                 self.gather_operand(func);
405                 for arg in args {
406                     self.gather_operand(arg);
407                 }
408                 if let Some((ref destination, _bb)) = *destination {
409                     self.create_move_path(destination);
410                     self.gather_init(destination.as_ref(), InitKind::NonPanicPathOnly);
411                 }
412             }
413         }
414     }
415
416     fn gather_operand(&mut self, operand: &Operand<'tcx>) {
417         match *operand {
418             Operand::Constant(..) | Operand::Copy(..) => {} // not-a-move
419             Operand::Move(ref place) => {
420                 // a move
421                 self.gather_move(place);
422             }
423         }
424     }
425
426     fn gather_move(&mut self, place: &Place<'tcx>) {
427         debug!("gather_move({:?}, {:?})", self.loc, place);
428
429         if let [ref base @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
430             **place.projection
431         {
432             // Split `Subslice` patterns into the corresponding list of
433             // `ConstIndex` patterns. This is done to ensure that all move paths
434             // are disjoint, which is expected by drop elaboration.
435             let base_place =
436                 Place { local: place.local, projection: self.builder.tcx.intern_place_elems(base) };
437             let base_path = match self.move_path_for(&base_place) {
438                 Ok(path) => path,
439                 Err(MoveError::UnionMove { path }) => {
440                     self.record_move(place, path);
441                     return;
442                 }
443                 Err(error @ MoveError::IllegalMove { .. }) => {
444                     self.builder.errors.push((base_place, error));
445                     return;
446                 }
447             };
448             let base_ty = base_place.ty(self.builder.body, self.builder.tcx).ty;
449             let len: u32 = match base_ty.kind {
450                 ty::Array(_, size) => {
451                     let length = size.eval_usize(self.builder.tcx, self.builder.param_env);
452                     length
453                         .try_into()
454                         .expect("slice pattern of array with more than u32::MAX elements")
455                 }
456                 _ => bug!("from_end: false slice pattern of non-array type"),
457             };
458             for offset in from..to {
459                 let elem =
460                     ProjectionElem::ConstantIndex { offset, min_length: len, from_end: false };
461                 let path = self.add_move_path(base_path, &elem, |tcx| {
462                     tcx.mk_place_elem(base_place.clone(), elem)
463                 });
464                 self.record_move(place, path);
465             }
466         } else {
467             match self.move_path_for(place) {
468                 Ok(path) | Err(MoveError::UnionMove { path }) => self.record_move(place, path),
469                 Err(error @ MoveError::IllegalMove { .. }) => {
470                     self.builder.errors.push((*place, error));
471                 }
472             };
473         }
474     }
475
476     fn record_move(&mut self, place: &Place<'tcx>, path: MovePathIndex) {
477         let move_out = self.builder.data.moves.push(MoveOut { path: path, source: self.loc });
478         debug!(
479             "gather_move({:?}, {:?}): adding move {:?} of {:?}",
480             self.loc, place, move_out, path
481         );
482         self.builder.data.path_map[path].push(move_out);
483         self.builder.data.loc_map[self.loc].push(move_out);
484     }
485
486     fn gather_init(&mut self, place: PlaceRef<'cx, 'tcx>, kind: InitKind) {
487         debug!("gather_init({:?}, {:?})", self.loc, place);
488
489         let mut place = place;
490
491         // Check if we are assigning into a field of a union, if so, lookup the place
492         // of the union so it is marked as initialized again.
493         if let [proj_base @ .., ProjectionElem::Field(_, _)] = place.projection {
494             if let ty::Adt(def, _) =
495                 Place::ty_from(place.local, proj_base, self.builder.body, self.builder.tcx).ty.kind
496             {
497                 if def.is_union() {
498                     place = PlaceRef { local: place.local, projection: proj_base }
499                 }
500             }
501         }
502
503         if let LookupResult::Exact(path) = self.builder.data.rev_lookup.find(place) {
504             let init = self.builder.data.inits.push(Init {
505                 location: InitLocation::Statement(self.loc),
506                 path,
507                 kind,
508             });
509
510             debug!(
511                 "gather_init({:?}, {:?}): adding init {:?} of {:?}",
512                 self.loc, place, init, path
513             );
514
515             self.builder.data.init_path_map[path].push(init);
516             self.builder.data.init_loc_map[self.loc].push(init);
517         }
518     }
519 }