1 // Copyright 2012-2017 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.
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.
11 use borrow_check::place_ext::PlaceExt;
12 use dataflow::indexes::BorrowIndex;
13 use dataflow::move_paths::MoveData;
14 use rustc::mir::traversal;
15 use rustc::mir::visit::{PlaceContext, Visitor};
16 use rustc::mir::{self, Location, Mir, Place, Local};
17 use rustc::ty::{Region, TyCtxt};
18 use rustc::util::nodemap::{FxHashMap, FxHashSet};
19 use rustc_data_structures::indexed_vec::IndexVec;
20 use rustc_data_structures::bit_set::BitSet;
25 crate struct BorrowSet<'tcx> {
26 /// The fundamental map relating bitvector indexes to the borrows
28 crate borrows: IndexVec<BorrowIndex, BorrowData<'tcx>>,
30 /// Each borrow is also uniquely identified in the MIR by the
31 /// `Location` of the assignment statement in which it appears on
32 /// the right hand side; we map each such location to the
33 /// corresponding `BorrowIndex`.
34 crate location_map: FxHashMap<Location, BorrowIndex>,
36 /// Locations which activate borrows.
37 /// NOTE: A given location may activate more than one borrow in the future
38 /// when more general two-phase borrow support is introduced, but for now we
39 /// only need to store one borrow index
40 crate activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
42 /// Every borrow has a region; this maps each such regions back to
43 /// its borrow-indexes.
44 crate region_map: FxHashMap<Region<'tcx>, FxHashSet<BorrowIndex>>,
46 /// Map from local to all the borrows on that local
47 crate local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
49 crate locals_state_at_exit: LocalsStateAtExit,
52 impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
53 type Output = BorrowData<'tcx>;
55 fn index(&self, index: BorrowIndex) -> &BorrowData<'tcx> {
60 /// Location where a two phase borrow is activated, if a borrow
61 /// is in fact a two phase borrow.
62 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
63 crate enum TwoPhaseActivation {
66 ActivatedAt(Location),
70 crate struct BorrowData<'tcx> {
71 /// Location where the borrow reservation starts.
72 /// In many cases, this will be equal to the activation location but not always.
73 crate reserve_location: Location,
74 /// Location where the borrow is activated.
75 crate activation_location: TwoPhaseActivation,
76 /// What kind of borrow this is
77 crate kind: mir::BorrowKind,
78 /// The region for which this borrow is live
79 crate region: Region<'tcx>,
80 /// Place from which we are borrowing
81 crate borrowed_place: mir::Place<'tcx>,
82 /// Place to which the borrow was stored
83 crate assigned_place: mir::Place<'tcx>,
86 impl<'tcx> fmt::Display for BorrowData<'tcx> {
87 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
88 let kind = match self.kind {
89 mir::BorrowKind::Shared => "",
90 mir::BorrowKind::Shallow => "shallow ",
91 mir::BorrowKind::Unique => "uniq ",
92 mir::BorrowKind::Mut { .. } => "mut ",
94 let region = self.region.to_string();
95 let region = if region.len() > 0 {
96 format!("{} ", region)
100 write!(w, "&{}{}{:?}", region, kind, self.borrowed_place)
104 crate enum LocalsStateAtExit {
106 SomeAreInvalidated { has_storage_dead_or_moved: BitSet<Local> }
109 impl LocalsStateAtExit {
111 locals_are_invalidated_at_exit: bool,
113 move_data: &MoveData<'tcx>
115 struct HasStorageDead(BitSet<Local>);
117 impl<'tcx> Visitor<'tcx> for HasStorageDead {
118 fn visit_local(&mut self, local: &Local, ctx: PlaceContext<'tcx>, _: Location) {
119 if ctx == PlaceContext::StorageDead {
120 self.0.insert(*local);
125 if locals_are_invalidated_at_exit {
126 LocalsStateAtExit::AllAreInvalidated
128 let mut has_storage_dead = HasStorageDead(BitSet::new_empty(mir.local_decls.len()));
129 has_storage_dead.visit_mir(mir);
130 let mut has_storage_dead_or_moved = has_storage_dead.0;
131 for move_out in &move_data.moves {
132 if let Some(index) = move_data.base_local(move_out.path) {
133 has_storage_dead_or_moved.insert(index);
137 LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved }
142 impl<'tcx> BorrowSet<'tcx> {
144 tcx: TyCtxt<'_, '_, 'tcx>,
146 locals_are_invalidated_at_exit: bool,
147 move_data: &MoveData<'tcx>
150 let mut visitor = GatherBorrows {
153 idx_vec: IndexVec::new(),
154 location_map: FxHashMap(),
155 activation_map: FxHashMap(),
156 region_map: FxHashMap(),
157 local_map: FxHashMap(),
158 pending_activations: FxHashMap(),
159 locals_state_at_exit:
160 LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data),
163 for (block, block_data) in traversal::preorder(mir) {
164 visitor.visit_basic_block_data(block, block_data);
168 borrows: visitor.idx_vec,
169 location_map: visitor.location_map,
170 activation_map: visitor.activation_map,
171 region_map: visitor.region_map,
172 local_map: visitor.local_map,
173 locals_state_at_exit: visitor.locals_state_at_exit,
177 crate fn activations_at_location(&self, location: Location) -> &[BorrowIndex] {
180 .map(|activations| &activations[..])
185 struct GatherBorrows<'a, 'gcx: 'tcx, 'tcx: 'a> {
186 tcx: TyCtxt<'a, 'gcx, 'tcx>,
188 idx_vec: IndexVec<BorrowIndex, BorrowData<'tcx>>,
189 location_map: FxHashMap<Location, BorrowIndex>,
190 activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
191 region_map: FxHashMap<Region<'tcx>, FxHashSet<BorrowIndex>>,
192 local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
194 /// When we encounter a 2-phase borrow statement, it will always
195 /// be assigning into a temporary TEMP:
199 /// We add TEMP into this map with `b`, where `b` is the index of
200 /// the borrow. When we find a later use of this activation, we
201 /// remove from the map (and add to the "tombstone" set below).
202 pending_activations: FxHashMap<mir::Local, BorrowIndex>,
204 locals_state_at_exit: LocalsStateAtExit,
207 impl<'a, 'gcx, 'tcx> Visitor<'tcx> for GatherBorrows<'a, 'gcx, 'tcx> {
210 block: mir::BasicBlock,
211 assigned_place: &mir::Place<'tcx>,
212 rvalue: &mir::Rvalue<'tcx>,
213 location: mir::Location,
215 if let mir::Rvalue::Ref(region, kind, ref borrowed_place) = *rvalue {
216 if borrowed_place.ignore_borrow(
217 self.tcx, self.mir, &self.locals_state_at_exit) {
221 let borrow = BorrowData {
224 reserve_location: location,
225 activation_location: TwoPhaseActivation::NotTwoPhase,
226 borrowed_place: borrowed_place.clone(),
227 assigned_place: assigned_place.clone(),
229 let idx = self.idx_vec.push(borrow);
230 self.location_map.insert(location, idx);
232 self.insert_as_pending_if_two_phase(location, &assigned_place, region, kind, idx);
234 insert(&mut self.region_map, ®ion, idx);
235 if let Some(local) = borrowed_place.root_local() {
236 insert(&mut self.local_map, &local, idx);
240 return self.super_assign(block, assigned_place, rvalue, location);
242 fn insert<'a, K, V>(map: &'a mut FxHashMap<K, FxHashSet<V>>, k: &K, v: V)
244 K: Clone + Eq + Hash,
247 map.entry(k.clone()).or_insert(FxHashSet()).insert(v);
253 place: &mir::Place<'tcx>,
254 context: PlaceContext<'tcx>,
257 self.super_place(place, context, location);
259 // We found a use of some temporary TEMP...
260 if let Place::Local(temp) = place {
261 // ... check whether we (earlier) saw a 2-phase borrow like
264 match self.pending_activations.get(temp) {
265 Some(&borrow_index) => {
266 let borrow_data = &mut self.idx_vec[borrow_index];
268 // Watch out: the use of TMP in the borrow itself
269 // doesn't count as an activation. =)
270 if borrow_data.reserve_location == location && context == PlaceContext::Store {
274 if let TwoPhaseActivation::ActivatedAt(other_location) =
275 borrow_data.activation_location {
277 self.mir.source_info(location).span,
278 "found two uses for 2-phase borrow temporary {:?}: \
286 // Otherwise, this is the unique later use
288 borrow_data.activation_location = match context {
289 // The use of TMP in a shared borrow does not
290 // count as an actual activation.
291 PlaceContext::Borrow { kind: mir::BorrowKind::Shared, .. }
292 | PlaceContext::Borrow { kind: mir::BorrowKind::Shallow, .. } => {
293 TwoPhaseActivation::NotActivated
296 // Double check: This borrow is indeed a two-phase borrow (that is,
297 // we are 'transitioning' from `NotActivated` to `ActivatedAt`) and
298 // we've not found any other activations (checked above).
300 borrow_data.activation_location,
301 TwoPhaseActivation::NotActivated,
302 "never found an activation for this borrow!",
309 TwoPhaseActivation::ActivatedAt(location)
319 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
320 if let mir::Rvalue::Ref(region, kind, ref place) = *rvalue {
321 // double-check that we already registered a BorrowData for this
323 let borrow_index = self.location_map[&location];
324 let borrow_data = &self.idx_vec[borrow_index];
325 assert_eq!(borrow_data.reserve_location, location);
326 assert_eq!(borrow_data.kind, kind);
327 assert_eq!(borrow_data.region, region);
328 assert_eq!(borrow_data.borrowed_place, *place);
331 return self.super_rvalue(rvalue, location);
336 block: mir::BasicBlock,
337 statement: &mir::Statement<'tcx>,
340 return self.super_statement(block, statement, location);
344 impl<'a, 'gcx, 'tcx> GatherBorrows<'a, 'gcx, 'tcx> {
345 /// Returns true if the borrow represented by `kind` is
346 /// allowed to be split into separate Reservation and
347 /// Activation phases.
348 fn allow_two_phase_borrow(&self, kind: mir::BorrowKind) -> bool {
349 self.tcx.two_phase_borrows()
350 && (kind.allows_two_phase_borrow()
351 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
354 /// If this is a two-phase borrow, then we will record it
355 /// as "pending" until we find the activating use.
356 fn insert_as_pending_if_two_phase(
358 start_location: Location,
359 assigned_place: &mir::Place<'tcx>,
360 region: Region<'tcx>,
361 kind: mir::BorrowKind,
362 borrow_index: BorrowIndex,
365 "Borrows::insert_as_pending_if_two_phase({:?}, {:?}, {:?}, {:?})",
366 start_location, assigned_place, region, borrow_index,
369 if !self.allow_two_phase_borrow(kind) {
370 debug!(" -> {:?}", start_location);
374 // When we encounter a 2-phase borrow statement, it will always
375 // be assigning into a temporary TEMP:
379 // so extract `temp`.
380 let temp = if let &mir::Place::Local(temp) = assigned_place {
384 self.mir.source_info(start_location).span,
385 "expected 2-phase borrow to assign to a local, not `{:?}`",
390 // Consider the borrow not activated to start. When we find an activation, we'll update
393 let borrow_data = &mut self.idx_vec[borrow_index];
394 borrow_data.activation_location = TwoPhaseActivation::NotActivated;
397 // Insert `temp` into the list of pending activations. From
398 // now on, we'll be on the lookout for a use of it. Note that
399 // we are guaranteed that this use will come after the
401 let old_value = self.pending_activations.insert(temp, borrow_index);
402 if let Some(old_index) = old_value {
403 span_bug!(self.mir.source_info(start_location).span,
404 "found already pending activation for temp: {:?} \
405 at borrow_index: {:?} with associated data {:?}",
406 temp, old_index, self.idx_vec[old_index]);