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::Unique => "uniq ",
91 mir::BorrowKind::Mut { .. } => "mut ",
93 let region = self.region.to_string();
94 let region = if region.len() > 0 {
95 format!("{} ", region)
99 write!(w, "&{}{}{:?}", region, kind, self.borrowed_place)
103 crate enum LocalsStateAtExit {
105 SomeAreInvalidated { has_storage_dead_or_moved: BitSet<Local> }
108 impl LocalsStateAtExit {
110 locals_are_invalidated_at_exit: bool,
112 move_data: &MoveData<'tcx>
114 struct HasStorageDead(BitSet<Local>);
116 impl<'tcx> Visitor<'tcx> for HasStorageDead {
117 fn visit_local(&mut self, local: &Local, ctx: PlaceContext<'tcx>, _: Location) {
118 if ctx == PlaceContext::StorageDead {
119 self.0.insert(*local);
124 if locals_are_invalidated_at_exit {
125 LocalsStateAtExit::AllAreInvalidated
127 let mut has_storage_dead = HasStorageDead(BitSet::new_empty(mir.local_decls.len()));
128 has_storage_dead.visit_mir(mir);
129 let mut has_storage_dead_or_moved = has_storage_dead.0;
130 for move_out in &move_data.moves {
131 if let Some(index) = move_data.base_local(move_out.path) {
132 has_storage_dead_or_moved.insert(index);
136 LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved }
141 impl<'tcx> BorrowSet<'tcx> {
143 tcx: TyCtxt<'_, '_, 'tcx>,
145 locals_are_invalidated_at_exit: bool,
146 move_data: &MoveData<'tcx>
149 let mut visitor = GatherBorrows {
152 idx_vec: IndexVec::new(),
153 location_map: FxHashMap(),
154 activation_map: FxHashMap(),
155 region_map: FxHashMap(),
156 local_map: FxHashMap(),
157 pending_activations: FxHashMap(),
158 locals_state_at_exit:
159 LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data),
162 for (block, block_data) in traversal::preorder(mir) {
163 visitor.visit_basic_block_data(block, block_data);
167 borrows: visitor.idx_vec,
168 location_map: visitor.location_map,
169 activation_map: visitor.activation_map,
170 region_map: visitor.region_map,
171 local_map: visitor.local_map,
172 locals_state_at_exit: visitor.locals_state_at_exit,
176 crate fn activations_at_location(&self, location: Location) -> &[BorrowIndex] {
179 .map(|activations| &activations[..])
184 struct GatherBorrows<'a, 'gcx: 'tcx, 'tcx: 'a> {
185 tcx: TyCtxt<'a, 'gcx, 'tcx>,
187 idx_vec: IndexVec<BorrowIndex, BorrowData<'tcx>>,
188 location_map: FxHashMap<Location, BorrowIndex>,
189 activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
190 region_map: FxHashMap<Region<'tcx>, FxHashSet<BorrowIndex>>,
191 local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
193 /// When we encounter a 2-phase borrow statement, it will always
194 /// be assigning into a temporary TEMP:
198 /// We add TEMP into this map with `b`, where `b` is the index of
199 /// the borrow. When we find a later use of this activation, we
200 /// remove from the map (and add to the "tombstone" set below).
201 pending_activations: FxHashMap<mir::Local, BorrowIndex>,
203 locals_state_at_exit: LocalsStateAtExit,
206 impl<'a, 'gcx, 'tcx> Visitor<'tcx> for GatherBorrows<'a, 'gcx, 'tcx> {
209 block: mir::BasicBlock,
210 assigned_place: &mir::Place<'tcx>,
211 rvalue: &mir::Rvalue<'tcx>,
212 location: mir::Location,
214 if let mir::Rvalue::Ref(region, kind, ref borrowed_place) = *rvalue {
215 if borrowed_place.ignore_borrow(
216 self.tcx, self.mir, &self.locals_state_at_exit) {
220 let borrow = BorrowData {
223 reserve_location: location,
224 activation_location: TwoPhaseActivation::NotTwoPhase,
225 borrowed_place: borrowed_place.clone(),
226 assigned_place: assigned_place.clone(),
228 let idx = self.idx_vec.push(borrow);
229 self.location_map.insert(location, idx);
231 self.insert_as_pending_if_two_phase(location, &assigned_place, region, kind, idx);
233 insert(&mut self.region_map, ®ion, idx);
234 if let Some(local) = borrowed_place.root_local() {
235 insert(&mut self.local_map, &local, idx);
239 return self.super_assign(block, assigned_place, rvalue, location);
241 fn insert<'a, K, V>(map: &'a mut FxHashMap<K, FxHashSet<V>>, k: &K, v: V)
243 K: Clone + Eq + Hash,
246 map.entry(k.clone()).or_insert(FxHashSet()).insert(v);
252 place: &mir::Place<'tcx>,
253 context: PlaceContext<'tcx>,
256 self.super_place(place, context, location);
258 // We found a use of some temporary TEMP...
259 if let Place::Local(temp) = place {
260 // ... check whether we (earlier) saw a 2-phase borrow like
263 match self.pending_activations.get(temp) {
264 Some(&borrow_index) => {
265 let borrow_data = &mut self.idx_vec[borrow_index];
267 // Watch out: the use of TMP in the borrow itself
268 // doesn't count as an activation. =)
269 if borrow_data.reserve_location == location && context == PlaceContext::Store {
273 if let TwoPhaseActivation::ActivatedAt(other_location) =
274 borrow_data.activation_location {
276 self.mir.source_info(location).span,
277 "found two uses for 2-phase borrow temporary {:?}: \
285 // Otherwise, this is the unique later use
287 borrow_data.activation_location = match context {
288 // The use of TMP in a shared borrow does not
289 // count as an actual activation.
290 PlaceContext::Borrow { kind: mir::BorrowKind::Shared, .. } => {
291 TwoPhaseActivation::NotActivated
294 // Double check: This borrow is indeed a two-phase borrow (that is,
295 // we are 'transitioning' from `NotActivated` to `ActivatedAt`) and
296 // we've not found any other activations (checked above).
298 borrow_data.activation_location,
299 TwoPhaseActivation::NotActivated,
300 "never found an activation for this borrow!",
307 TwoPhaseActivation::ActivatedAt(location)
317 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
318 if let mir::Rvalue::Ref(region, kind, ref place) = *rvalue {
319 // double-check that we already registered a BorrowData for this
321 let borrow_index = self.location_map[&location];
322 let borrow_data = &self.idx_vec[borrow_index];
323 assert_eq!(borrow_data.reserve_location, location);
324 assert_eq!(borrow_data.kind, kind);
325 assert_eq!(borrow_data.region, region);
326 assert_eq!(borrow_data.borrowed_place, *place);
329 return self.super_rvalue(rvalue, location);
334 block: mir::BasicBlock,
335 statement: &mir::Statement<'tcx>,
338 return self.super_statement(block, statement, location);
342 impl<'a, 'gcx, 'tcx> GatherBorrows<'a, 'gcx, 'tcx> {
343 /// Returns true if the borrow represented by `kind` is
344 /// allowed to be split into separate Reservation and
345 /// Activation phases.
346 fn allow_two_phase_borrow(&self, kind: mir::BorrowKind) -> bool {
347 self.tcx.two_phase_borrows()
348 && (kind.allows_two_phase_borrow()
349 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
352 /// If this is a two-phase borrow, then we will record it
353 /// as "pending" until we find the activating use.
354 fn insert_as_pending_if_two_phase(
356 start_location: Location,
357 assigned_place: &mir::Place<'tcx>,
358 region: Region<'tcx>,
359 kind: mir::BorrowKind,
360 borrow_index: BorrowIndex,
363 "Borrows::insert_as_pending_if_two_phase({:?}, {:?}, {:?}, {:?})",
364 start_location, assigned_place, region, borrow_index,
367 if !self.allow_two_phase_borrow(kind) {
368 debug!(" -> {:?}", start_location);
372 // When we encounter a 2-phase borrow statement, it will always
373 // be assigning into a temporary TEMP:
377 // so extract `temp`.
378 let temp = if let &mir::Place::Local(temp) = assigned_place {
382 self.mir.source_info(start_location).span,
383 "expected 2-phase borrow to assign to a local, not `{:?}`",
388 // Consider the borrow not activated to start. When we find an activation, we'll update
391 let borrow_data = &mut self.idx_vec[borrow_index];
392 borrow_data.activation_location = TwoPhaseActivation::NotActivated;
395 // Insert `temp` into the list of pending activations. From
396 // now on, we'll be on the lookout for a use of it. Note that
397 // we are guaranteed that this use will come after the
399 let old_value = self.pending_activations.insert(temp, borrow_index);
400 if let Some(old_index) = old_value {
401 span_bug!(self.mir.source_info(start_location).span,
402 "found already pending activation for temp: {:?} \
403 at borrow_index: {:?} with associated data {:?}",
404 temp, old_index, self.idx_vec[old_index]);