1 use borrow_check::place_ext::PlaceExt;
2 use borrow_check::nll::ToRegionVid;
3 use dataflow::indexes::BorrowIndex;
4 use dataflow::move_paths::MoveData;
5 use rustc::mir::traversal;
6 use rustc::mir::visit::{
7 PlaceContext, Visitor, NonUseContext, MutatingUseContext, NonMutatingUseContext
9 use rustc::mir::{self, Location, Mir, Local};
10 use rustc::ty::{RegionVid, TyCtxt};
11 use rustc::util::nodemap::{FxHashMap, FxHashSet};
12 use rustc_data_structures::indexed_vec::IndexVec;
13 use rustc_data_structures::bit_set::BitSet;
17 crate struct BorrowSet<'tcx> {
18 /// The fundamental map relating bitvector indexes to the borrows
20 crate borrows: IndexVec<BorrowIndex, BorrowData<'tcx>>,
22 /// Each borrow is also uniquely identified in the MIR by the
23 /// `Location` of the assignment statement in which it appears on
24 /// the right hand side; we map each such location to the
25 /// corresponding `BorrowIndex`.
26 crate location_map: FxHashMap<Location, BorrowIndex>,
28 /// Locations which activate borrows.
29 /// NOTE: A given location may activate more than one borrow in the future
30 /// when more general two-phase borrow support is introduced, but for now we
31 /// only need to store one borrow index
32 crate activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
34 /// Map from local to all the borrows on that local
35 crate local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
37 crate locals_state_at_exit: LocalsStateAtExit,
40 impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
41 type Output = BorrowData<'tcx>;
43 fn index(&self, index: BorrowIndex) -> &BorrowData<'tcx> {
48 /// Location where a two phase borrow is activated, if a borrow
49 /// is in fact a two phase borrow.
50 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
51 crate enum TwoPhaseActivation {
54 ActivatedAt(Location),
58 crate struct BorrowData<'tcx> {
59 /// Location where the borrow reservation starts.
60 /// In many cases, this will be equal to the activation location but not always.
61 crate reserve_location: Location,
62 /// Location where the borrow is activated.
63 crate activation_location: TwoPhaseActivation,
64 /// What kind of borrow this is
65 crate kind: mir::BorrowKind,
66 /// The region for which this borrow is live
67 crate region: RegionVid,
68 /// Place from which we are borrowing
69 crate borrowed_place: mir::Place<'tcx>,
70 /// Place to which the borrow was stored
71 crate assigned_place: mir::Place<'tcx>,
74 impl<'tcx> fmt::Display for BorrowData<'tcx> {
75 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
76 let kind = match self.kind {
77 mir::BorrowKind::Shared => "",
78 mir::BorrowKind::Shallow => "shallow ",
79 mir::BorrowKind::Unique => "uniq ",
80 mir::BorrowKind::Mut { .. } => "mut ",
82 write!(w, "&{:?} {}{:?}", self.region, kind, self.borrowed_place)
86 crate enum LocalsStateAtExit {
88 SomeAreInvalidated { has_storage_dead_or_moved: BitSet<Local> }
91 impl LocalsStateAtExit {
93 locals_are_invalidated_at_exit: bool,
95 move_data: &MoveData<'tcx>
97 struct HasStorageDead(BitSet<Local>);
99 impl<'tcx> Visitor<'tcx> for HasStorageDead {
100 fn visit_local(&mut self, local: &Local, ctx: PlaceContext<'tcx>, _: Location) {
101 if ctx == PlaceContext::NonUse(NonUseContext::StorageDead) {
102 self.0.insert(*local);
107 if locals_are_invalidated_at_exit {
108 LocalsStateAtExit::AllAreInvalidated
110 let mut has_storage_dead = HasStorageDead(BitSet::new_empty(mir.local_decls.len()));
111 has_storage_dead.visit_mir(mir);
112 let mut has_storage_dead_or_moved = has_storage_dead.0;
113 for move_out in &move_data.moves {
114 if let Some(index) = move_data.base_local(move_out.path) {
115 has_storage_dead_or_moved.insert(index);
119 LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved }
124 impl<'tcx> BorrowSet<'tcx> {
126 tcx: TyCtxt<'_, '_, 'tcx>,
128 locals_are_invalidated_at_exit: bool,
129 move_data: &MoveData<'tcx>
132 let mut visitor = GatherBorrows {
135 idx_vec: IndexVec::new(),
136 location_map: Default::default(),
137 activation_map: Default::default(),
138 local_map: Default::default(),
139 pending_activations: Default::default(),
140 locals_state_at_exit:
141 LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data),
144 for (block, block_data) in traversal::preorder(mir) {
145 visitor.visit_basic_block_data(block, block_data);
149 borrows: visitor.idx_vec,
150 location_map: visitor.location_map,
151 activation_map: visitor.activation_map,
152 local_map: visitor.local_map,
153 locals_state_at_exit: visitor.locals_state_at_exit,
157 crate fn activations_at_location(&self, location: Location) -> &[BorrowIndex] {
160 .map(|activations| &activations[..])
165 struct GatherBorrows<'a, 'gcx: 'tcx, 'tcx: 'a> {
166 tcx: TyCtxt<'a, 'gcx, 'tcx>,
168 idx_vec: IndexVec<BorrowIndex, BorrowData<'tcx>>,
169 location_map: FxHashMap<Location, BorrowIndex>,
170 activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
171 local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
173 /// When we encounter a 2-phase borrow statement, it will always
174 /// be assigning into a temporary TEMP:
178 /// We add TEMP into this map with `b`, where `b` is the index of
179 /// the borrow. When we find a later use of this activation, we
180 /// remove from the map (and add to the "tombstone" set below).
181 pending_activations: FxHashMap<mir::Local, BorrowIndex>,
183 locals_state_at_exit: LocalsStateAtExit,
186 impl<'a, 'gcx, 'tcx> Visitor<'tcx> for GatherBorrows<'a, 'gcx, 'tcx> {
189 block: mir::BasicBlock,
190 assigned_place: &mir::Place<'tcx>,
191 rvalue: &mir::Rvalue<'tcx>,
192 location: mir::Location,
194 if let mir::Rvalue::Ref(region, kind, ref borrowed_place) = *rvalue {
195 if borrowed_place.ignore_borrow(
196 self.tcx, self.mir, &self.locals_state_at_exit) {
200 let region = region.to_region_vid();
202 let borrow = BorrowData {
205 reserve_location: location,
206 activation_location: TwoPhaseActivation::NotTwoPhase,
207 borrowed_place: borrowed_place.clone(),
208 assigned_place: assigned_place.clone(),
210 let idx = self.idx_vec.push(borrow);
211 self.location_map.insert(location, idx);
213 self.insert_as_pending_if_two_phase(location, &assigned_place, kind, idx);
215 if let Some(local) = borrowed_place.root_local() {
216 self.local_map.entry(local).or_default().insert(idx);
220 self.super_assign(block, assigned_place, rvalue, location)
226 context: PlaceContext<'tcx>,
229 if !context.is_use() {
233 // We found a use of some temporary TMP
234 // check whether we (earlier) saw a 2-phase borrow like
237 if let Some(&borrow_index) = self.pending_activations.get(temp) {
238 let borrow_data = &mut self.idx_vec[borrow_index];
240 // Watch out: the use of TMP in the borrow itself
241 // doesn't count as an activation. =)
242 if borrow_data.reserve_location == location &&
243 context == PlaceContext::MutatingUse(MutatingUseContext::Store)
248 if let TwoPhaseActivation::ActivatedAt(other_location) =
249 borrow_data.activation_location {
251 self.mir.source_info(location).span,
252 "found two uses for 2-phase borrow temporary {:?}: \
260 // Otherwise, this is the unique later use
262 borrow_data.activation_location = match context {
263 // The use of TMP in a shared borrow does not
264 // count as an actual activation.
265 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow(..)) |
266 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow(..)) =>
267 TwoPhaseActivation::NotActivated,
269 // Double check: This borrow is indeed a two-phase borrow (that is,
270 // we are 'transitioning' from `NotActivated` to `ActivatedAt`) and
271 // we've not found any other activations (checked above).
273 borrow_data.activation_location,
274 TwoPhaseActivation::NotActivated,
275 "never found an activation for this borrow!",
282 TwoPhaseActivation::ActivatedAt(location)
288 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
289 if let mir::Rvalue::Ref(region, kind, ref place) = *rvalue {
290 // double-check that we already registered a BorrowData for this
292 let borrow_index = self.location_map[&location];
293 let borrow_data = &self.idx_vec[borrow_index];
294 assert_eq!(borrow_data.reserve_location, location);
295 assert_eq!(borrow_data.kind, kind);
296 assert_eq!(borrow_data.region, region.to_region_vid());
297 assert_eq!(borrow_data.borrowed_place, *place);
300 return self.super_rvalue(rvalue, location);
305 block: mir::BasicBlock,
306 statement: &mir::Statement<'tcx>,
309 return self.super_statement(block, statement, location);
313 impl<'a, 'gcx, 'tcx> GatherBorrows<'a, 'gcx, 'tcx> {
314 /// Returns true if the borrow represented by `kind` is
315 /// allowed to be split into separate Reservation and
316 /// Activation phases.
317 fn allow_two_phase_borrow(&self, kind: mir::BorrowKind) -> bool {
318 self.tcx.two_phase_borrows()
319 && (kind.allows_two_phase_borrow()
320 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
323 /// If this is a two-phase borrow, then we will record it
324 /// as "pending" until we find the activating use.
325 fn insert_as_pending_if_two_phase(
327 start_location: Location,
328 assigned_place: &mir::Place<'tcx>,
329 kind: mir::BorrowKind,
330 borrow_index: BorrowIndex,
333 "Borrows::insert_as_pending_if_two_phase({:?}, {:?}, {:?})",
334 start_location, assigned_place, borrow_index,
337 if !self.allow_two_phase_borrow(kind) {
338 debug!(" -> {:?}", start_location);
342 // When we encounter a 2-phase borrow statement, it will always
343 // be assigning into a temporary TEMP:
347 // so extract `temp`.
348 let temp = if let &mir::Place::Local(temp) = assigned_place {
352 self.mir.source_info(start_location).span,
353 "expected 2-phase borrow to assign to a local, not `{:?}`",
358 // Consider the borrow not activated to start. When we find an activation, we'll update
361 let borrow_data = &mut self.idx_vec[borrow_index];
362 borrow_data.activation_location = TwoPhaseActivation::NotActivated;
365 // Insert `temp` into the list of pending activations. From
366 // now on, we'll be on the lookout for a use of it. Note that
367 // we are guaranteed that this use will come after the
369 let old_value = self.pending_activations.insert(temp, borrow_index);
370 if let Some(old_index) = old_value {
371 span_bug!(self.mir.source_info(start_location).span,
372 "found already pending activation for temp: {:?} \
373 at borrow_index: {:?} with associated data {:?}",
374 temp, old_index, self.idx_vec[old_index]);