]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/dataflow/impls/borrows.rs
Rollup merge of #62120 - GuillaumeGomez:add-missing-type-links, r=Centril
[rust.git] / src / librustc_mir / dataflow / impls / borrows.rs
1 use crate::borrow_check::borrow_set::{BorrowSet, BorrowData};
2 use crate::borrow_check::place_ext::PlaceExt;
3
4 use rustc::mir::{self, Location, Place, PlaceBase, Body};
5 use rustc::ty::TyCtxt;
6 use rustc::ty::RegionVid;
7
8 use rustc_data_structures::bit_set::BitSet;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
11
12 use crate::dataflow::{BitDenotation, BottomValue, GenKillSet};
13 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
14 use crate::borrow_check::nll::ToRegionVid;
15 use crate::borrow_check::places_conflict;
16
17 use std::rc::Rc;
18
19 newtype_index! {
20     pub struct BorrowIndex {
21         DEBUG_FORMAT = "bw{}"
22     }
23 }
24
25 /// `Borrows` stores the data used in the analyses that track the flow
26 /// of borrows.
27 ///
28 /// It uniquely identifies every borrow (`Rvalue::Ref`) by a
29 /// `BorrowIndex`, and maps each such index to a `BorrowData`
30 /// describing the borrow. These indexes are used for representing the
31 /// borrows in compact bitvectors.
32 pub struct Borrows<'a, 'tcx> {
33     tcx: TyCtxt<'tcx>,
34     body: &'a Body<'tcx>,
35
36     borrow_set: Rc<BorrowSet<'tcx>>,
37     borrows_out_of_scope_at_location: FxHashMap<Location, Vec<BorrowIndex>>,
38
39     /// NLL region inference context with which NLL queries should be resolved
40     _nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
41 }
42
43 struct StackEntry {
44     bb: mir::BasicBlock,
45     lo: usize,
46     hi: usize,
47     first_part_only: bool
48 }
49
50 fn precompute_borrows_out_of_scope<'tcx>(
51     body: &Body<'tcx>,
52     regioncx: &Rc<RegionInferenceContext<'tcx>>,
53     borrows_out_of_scope_at_location: &mut FxHashMap<Location, Vec<BorrowIndex>>,
54     borrow_index: BorrowIndex,
55     borrow_region: RegionVid,
56     location: Location,
57 ) {
58     // We visit one BB at a time. The complication is that we may start in the
59     // middle of the first BB visited (the one containing `location`), in which
60     // case we may have to later on process the first part of that BB if there
61     // is a path back to its start.
62
63     // For visited BBs, we record the index of the first statement processed.
64     // (In fully processed BBs this index is 0.) Note also that we add BBs to
65     // `visited` once they are added to `stack`, before they are actually
66     // processed, because this avoids the need to look them up again on
67     // completion.
68     let mut visited = FxHashMap::default();
69     visited.insert(location.block, location.statement_index);
70
71     let mut stack = vec![];
72     stack.push(StackEntry {
73         bb: location.block,
74         lo: location.statement_index,
75         hi: body[location.block].statements.len(),
76         first_part_only: false,
77     });
78
79     while let Some(StackEntry { bb, lo, hi, first_part_only }) = stack.pop() {
80         let mut finished_early = first_part_only;
81         for i in lo ..= hi {
82             let location = Location { block: bb, statement_index: i };
83             // If region does not contain a point at the location, then add to list and skip
84             // successor locations.
85             if !regioncx.region_contains(borrow_region, location) {
86                 debug!("borrow {:?} gets killed at {:?}", borrow_index, location);
87                 borrows_out_of_scope_at_location
88                     .entry(location)
89                     .or_default()
90                     .push(borrow_index);
91                 finished_early = true;
92                 break;
93             }
94         }
95
96         if !finished_early {
97             // Add successor BBs to the work list, if necessary.
98             let bb_data = &body[bb];
99             assert!(hi == bb_data.statements.len());
100             for &succ_bb in bb_data.terminator.as_ref().unwrap().successors() {
101                 visited.entry(succ_bb)
102                     .and_modify(|lo| {
103                         // `succ_bb` has been seen before. If it wasn't
104                         // fully processed, add its first part to `stack`
105                         // for processing.
106                         if *lo > 0 {
107                             stack.push(StackEntry {
108                                 bb: succ_bb,
109                                 lo: 0,
110                                 hi: *lo - 1,
111                                 first_part_only: true,
112                             });
113                         }
114                         // And update this entry with 0, to represent the
115                         // whole BB being processed.
116                         *lo = 0;
117                     })
118                     .or_insert_with(|| {
119                         // succ_bb hasn't been seen before. Add it to
120                         // `stack` for processing.
121                         stack.push(StackEntry {
122                             bb: succ_bb,
123                             lo: 0,
124                             hi: body[succ_bb].statements.len(),
125                             first_part_only: false,
126                         });
127                         // Insert 0 for this BB, to represent the whole BB
128                         // being processed.
129                         0
130                     });
131             }
132         }
133     }
134 }
135
136 impl<'a, 'tcx> Borrows<'a, 'tcx> {
137     crate fn new(
138         tcx: TyCtxt<'tcx>,
139         body: &'a Body<'tcx>,
140         nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
141         borrow_set: &Rc<BorrowSet<'tcx>>,
142     ) -> Self {
143         let mut borrows_out_of_scope_at_location = FxHashMap::default();
144         for (borrow_index, borrow_data) in borrow_set.borrows.iter_enumerated() {
145             let borrow_region = borrow_data.region.to_region_vid();
146             let location = borrow_set.borrows[borrow_index].reserve_location;
147
148             precompute_borrows_out_of_scope(body, &nonlexical_regioncx,
149                                             &mut borrows_out_of_scope_at_location,
150                                             borrow_index, borrow_region, location);
151         }
152
153         Borrows {
154             tcx: tcx,
155             body: body,
156             borrow_set: borrow_set.clone(),
157             borrows_out_of_scope_at_location,
158             _nonlexical_regioncx: nonlexical_regioncx,
159         }
160     }
161
162     crate fn borrows(&self) -> &IndexVec<BorrowIndex, BorrowData<'tcx>> { &self.borrow_set.borrows }
163
164     pub fn location(&self, idx: BorrowIndex) -> &Location {
165         &self.borrow_set.borrows[idx].reserve_location
166     }
167
168     /// Add all borrows to the kill set, if those borrows are out of scope at `location`.
169     /// That means they went out of a nonlexical scope
170     fn kill_loans_out_of_scope_at_location(&self,
171                                            trans: &mut GenKillSet<BorrowIndex>,
172                                            location: Location) {
173         // NOTE: The state associated with a given `location`
174         // reflects the dataflow on entry to the statement.
175         // Iterate over each of the borrows that we've precomputed
176         // to have went out of scope at this location and kill them.
177         //
178         // We are careful always to call this function *before* we
179         // set up the gen-bits for the statement or
180         // termanator. That way, if the effect of the statement or
181         // terminator *does* introduce a new loan of the same
182         // region, then setting that gen-bit will override any
183         // potential kill introduced here.
184         if let Some(indices) = self.borrows_out_of_scope_at_location.get(&location) {
185             trans.kill_all(indices);
186         }
187     }
188
189     /// Kill any borrows that conflict with `place`.
190     fn kill_borrows_on_place(
191         &self,
192         trans: &mut GenKillSet<BorrowIndex>,
193         place: &Place<'tcx>
194     ) {
195         debug!("kill_borrows_on_place: place={:?}", place);
196
197         if let PlaceBase::Local(local) = place.base {
198             let other_borrows_of_local = self
199                 .borrow_set
200                 .local_map
201                 .get(&local)
202                 .into_iter()
203                 .flat_map(|bs| bs.into_iter());
204
205             // If the borrowed place is a local with no projections, all other borrows of this
206             // local must conflict. This is purely an optimization so we don't have to call
207             // `places_conflict` for every borrow.
208             if place.projection.is_none() {
209                 trans.kill_all(other_borrows_of_local);
210                 return;
211             }
212
213             // By passing `PlaceConflictBias::NoOverlap`, we conservatively assume that any given
214             // pair of array indices are unequal, so that when `places_conflict` returns true, we
215             // will be assured that two places being compared definitely denotes the same sets of
216             // locations.
217             let definitely_conflicting_borrows = other_borrows_of_local
218                 .filter(|&&i| {
219                     places_conflict::places_conflict(
220                         self.tcx,
221                         self.body,
222                         &self.borrow_set.borrows[i].borrowed_place,
223                         place,
224                         places_conflict::PlaceConflictBias::NoOverlap)
225                 });
226
227             trans.kill_all(definitely_conflicting_borrows);
228         }
229     }
230 }
231
232 impl<'a, 'tcx> BitDenotation<'tcx> for Borrows<'a, 'tcx> {
233     type Idx = BorrowIndex;
234     fn name() -> &'static str { "borrows" }
235     fn bits_per_block(&self) -> usize {
236         self.borrow_set.borrows.len() * 2
237     }
238
239     fn start_block_effect(&self, _entry_set: &mut BitSet<Self::Idx>) {
240         // no borrows of code region_scopes have been taken prior to
241         // function execution, so this method has no effect.
242     }
243
244     fn before_statement_effect(&self,
245                                trans: &mut GenKillSet<Self::Idx>,
246                                location: Location) {
247         debug!("Borrows::before_statement_effect trans: {:?} location: {:?}",
248                trans, location);
249         self.kill_loans_out_of_scope_at_location(trans, location);
250     }
251
252     fn statement_effect(&self,
253                         trans: &mut GenKillSet<Self::Idx>,
254                         location: Location) {
255         debug!("Borrows::statement_effect: trans={:?} location={:?}",
256                trans, location);
257
258         let block = &self.body.basic_blocks().get(location.block).unwrap_or_else(|| {
259             panic!("could not find block at location {:?}", location);
260         });
261         let stmt = block.statements.get(location.statement_index).unwrap_or_else(|| {
262             panic!("could not find statement at location {:?}");
263         });
264
265         debug!("Borrows::statement_effect: stmt={:?}", stmt);
266         match stmt.kind {
267             mir::StatementKind::Assign(ref lhs, ref rhs) => {
268                 // Make sure there are no remaining borrows for variables
269                 // that are assigned over.
270                 self.kill_borrows_on_place(trans, lhs);
271
272                 if let mir::Rvalue::Ref(_, _, ref place) = **rhs {
273                     if place.ignore_borrow(
274                         self.tcx,
275                         self.body,
276                         &self.borrow_set.locals_state_at_exit,
277                     ) {
278                         return;
279                     }
280                     let index = self.borrow_set.location_map.get(&location).unwrap_or_else(|| {
281                         panic!("could not find BorrowIndex for location {:?}", location);
282                     });
283
284                     trans.gen(*index);
285                 }
286             }
287
288             mir::StatementKind::StorageDead(local) => {
289                 // Make sure there are no remaining borrows for locals that
290                 // are gone out of scope.
291                 self.kill_borrows_on_place(trans, &Place::from(local));
292             }
293
294             mir::StatementKind::InlineAsm(ref asm) => {
295                 for (output, kind) in asm.outputs.iter().zip(&asm.asm.outputs) {
296                     if !kind.is_indirect && !kind.is_rw {
297                         self.kill_borrows_on_place(trans, output);
298                     }
299                 }
300             }
301
302             mir::StatementKind::FakeRead(..) |
303             mir::StatementKind::SetDiscriminant { .. } |
304             mir::StatementKind::StorageLive(..) |
305             mir::StatementKind::Retag { .. } |
306             mir::StatementKind::AscribeUserType(..) |
307             mir::StatementKind::Nop => {}
308
309         }
310     }
311
312     fn before_terminator_effect(&self,
313                                 trans: &mut GenKillSet<Self::Idx>,
314                                 location: Location) {
315         debug!("Borrows::before_terminator_effect: trans={:?} location={:?}",
316                trans, location);
317         self.kill_loans_out_of_scope_at_location(trans, location);
318     }
319
320     fn terminator_effect(&self,
321                          _: &mut GenKillSet<Self::Idx>,
322                          _: Location) {}
323
324     fn propagate_call_return(
325         &self,
326         _in_out: &mut BitSet<BorrowIndex>,
327         _call_bb: mir::BasicBlock,
328         _dest_bb: mir::BasicBlock,
329         _dest_place: &mir::Place<'tcx>,
330     ) {
331     }
332 }
333
334 impl<'a, 'tcx> BottomValue for Borrows<'a, 'tcx> {
335     /// bottom = nothing is reserved or activated yet;
336     const BOTTOM_VALUE: bool = false;
337 }