1 use rustc_data_structures::graph::dominators::Dominators;
2 use rustc_middle::mir::visit::Visitor;
3 use rustc_middle::mir::{BasicBlock, Body, Location, Place, Rvalue};
4 use rustc_middle::mir::{BorrowKind, Mutability, Operand};
5 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
6 use rustc_middle::mir::{Statement, StatementKind};
7 use rustc_middle::ty::TyCtxt;
10 borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth,
11 Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read, ReadKind,
12 ReadOrWrite, Reservation, Shallow, Write, WriteKind,
15 pub(super) fn generate_invalidates<'tcx>(
17 all_facts: &mut Option<AllFacts>,
18 location_table: &LocationTable,
20 borrow_set: &BorrowSet<'tcx>,
22 if all_facts.is_none() {
23 // Nothing to do if we don't have any facts
27 if let Some(all_facts) = all_facts {
28 let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation");
29 let dominators = body.basic_blocks.dominators();
30 let mut ig = InvalidationGenerator {
42 struct InvalidationGenerator<'cx, 'tcx> {
44 all_facts: &'cx mut AllFacts,
45 location_table: &'cx LocationTable,
46 body: &'cx Body<'tcx>,
47 dominators: Dominators<BasicBlock>,
48 borrow_set: &'cx BorrowSet<'tcx>,
51 /// Visits the whole MIR and generates `invalidates()` facts.
52 /// Most of the code implementing this was stolen from `borrow_check/mod.rs`.
53 impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> {
54 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
55 self.check_activations(location);
57 match &statement.kind {
58 StatementKind::Assign(box (lhs, rhs)) => {
59 self.consume_rvalue(location, rhs);
61 self.mutate_place(location, *lhs, Shallow(None));
63 StatementKind::FakeRead(box (_, _)) => {
64 // Only relevant for initialized/liveness/safety checks.
66 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
71 self.consume_operand(location, src);
72 self.consume_operand(location, dst);
73 self.consume_operand(location, count);
75 // Only relevant for mir typeck
76 StatementKind::AscribeUserType(..)
77 // Doesn't have any language semantics
78 | StatementKind::Coverage(..)
79 // Takes a `bool` argument, and has no return value, thus being irrelevant for borrowck
80 | StatementKind::Assume(..)
81 // Does not actually affect borrowck
82 | StatementKind::StorageLive(..) => {}
83 StatementKind::StorageDead(local) => {
87 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
88 LocalMutationIsAllowed::Yes,
92 | StatementKind::Retag { .. }
93 | StatementKind::Deinit(..)
94 | StatementKind::SetDiscriminant { .. } => {
95 bug!("Statement not allowed in this MIR phase")
99 self.super_statement(statement, location);
102 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
103 self.check_activations(location);
105 match &terminator.kind {
106 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
107 self.consume_operand(location, discr);
109 TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
113 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
114 LocalMutationIsAllowed::Yes,
117 TerminatorKind::DropAndReplace {
119 value: ref new_value,
123 self.mutate_place(location, *drop_place, Deep);
124 self.consume_operand(location, new_value);
126 TerminatorKind::Call {
135 self.consume_operand(location, func);
137 self.consume_operand(location, arg);
139 self.mutate_place(location, *destination, Deep);
141 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
142 self.consume_operand(location, cond);
143 use rustc_middle::mir::AssertKind;
144 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
145 self.consume_operand(location, len);
146 self.consume_operand(location, index);
149 TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
150 self.consume_operand(location, value);
152 // Invalidate all borrows of local places
153 let borrow_set = self.borrow_set;
154 let resume = self.location_table.start_index(resume.start_location());
155 for (i, data) in borrow_set.iter_enumerated() {
156 if borrow_of_local_data(data.borrowed_place) {
157 self.all_facts.loan_invalidated_at.push((resume, i));
161 self.mutate_place(location, *resume_arg, Deep);
163 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
164 // Invalidate all borrows of local places
165 let borrow_set = self.borrow_set;
166 let start = self.location_table.start_index(location);
167 for (i, data) in borrow_set.iter_enumerated() {
168 if borrow_of_local_data(data.borrowed_place) {
169 self.all_facts.loan_invalidated_at.push((start, i));
173 TerminatorKind::InlineAsm {
183 InlineAsmOperand::In { reg: _, ref value } => {
184 self.consume_operand(location, value);
186 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
187 if let Some(place) = place {
188 self.mutate_place(location, place, Shallow(None));
191 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
192 self.consume_operand(location, in_value);
193 if let Some(out_place) = out_place {
194 self.mutate_place(location, out_place, Shallow(None));
197 InlineAsmOperand::Const { value: _ }
198 | InlineAsmOperand::SymFn { value: _ }
199 | InlineAsmOperand::SymStatic { def_id: _ } => {}
203 TerminatorKind::Goto { target: _ }
204 | TerminatorKind::Abort
205 | TerminatorKind::Unreachable
206 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
207 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
208 // no data used, thus irrelevant to borrowck
212 self.super_terminator(terminator, location);
216 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
217 /// Simulates mutation of a place.
218 fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
222 (kind, Write(WriteKind::Mutate)),
223 LocalMutationIsAllowed::ExceptUpvars,
227 /// Simulates consumption of an operand.
228 fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
230 Operand::Copy(place) => {
234 (Deep, Read(ReadKind::Copy)),
235 LocalMutationIsAllowed::No,
238 Operand::Move(place) => {
242 (Deep, Write(WriteKind::Move)),
243 LocalMutationIsAllowed::Yes,
246 Operand::Constant(_) => {}
250 // Simulates consumption of an rvalue
251 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
253 Rvalue::Ref(_ /*rgn*/, bk, place) => {
254 let access_kind = match bk {
255 BorrowKind::Shallow => {
256 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
258 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
259 BorrowKind::Unique | BorrowKind::Mut { .. } => {
260 let wk = WriteKind::MutableBorrow(bk);
261 if allow_two_phase_borrow(bk) {
262 (Deep, Reservation(wk))
269 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
272 Rvalue::AddressOf(mutability, place) => {
273 let access_kind = match mutability {
276 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
277 allow_two_phase_borrow: false,
280 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
283 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
286 Rvalue::ThreadLocalRef(_) => {}
288 Rvalue::Use(ref operand)
289 | Rvalue::Repeat(ref operand, _)
290 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
291 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
292 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
293 self.consume_operand(location, operand)
295 Rvalue::CopyForDeref(ref place) => {
296 let op = &Operand::Copy(*place);
297 self.consume_operand(location, op);
300 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
301 let af = match *rvalue {
302 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
303 Rvalue::Discriminant(..) => None,
309 (Shallow(af), Read(ReadKind::Copy)),
310 LocalMutationIsAllowed::No,
314 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
315 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
316 self.consume_operand(location, operand1);
317 self.consume_operand(location, operand2);
320 Rvalue::NullaryOp(_op, _ty) => {}
322 Rvalue::Aggregate(_, ref operands) => {
323 for operand in operands {
324 self.consume_operand(location, operand);
330 /// Simulates an access to a place.
335 kind: (AccessDepth, ReadOrWrite),
336 _is_local_mutation_allowed: LocalMutationIsAllowed,
339 // note: not doing check_access_permissions checks because they don't generate invalidates
340 self.check_access_for_conflict(location, place, sd, rw);
343 fn check_access_for_conflict(
351 "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
353 location, place, sd, rw,
356 let body = self.body;
357 let borrow_set = self.borrow_set;
358 let indices = self.borrow_set.indices();
359 each_borrow_involving_path(
367 |this, borrow_index, borrow| {
368 match (rw, borrow.kind) {
369 // Obviously an activation is compatible with its own
370 // reservation (or even prior activating uses of same
371 // borrow); so don't check if they interfere.
373 // NOTE: *reservations* do conflict with themselves;
374 // thus aren't injecting unsoundness w/ this check.)
375 (Activation(_, activating), _) if activating == borrow_index => {
376 // Activating a borrow doesn't generate any invalidations, since we
377 // have already taken the reservation
380 (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
382 Read(ReadKind::Borrow(BorrowKind::Shallow)),
383 BorrowKind::Unique | BorrowKind::Mut { .. },
385 // Reads don't invalidate shared or shallow borrows
388 (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
389 // Reading from mere reservations of mutable-borrows is OK.
390 if !is_active(&this.dominators, borrow, location) {
391 // If the borrow isn't active yet, reads don't invalidate it
392 assert!(allow_two_phase_borrow(borrow.kind));
393 return Control::Continue;
396 // Unique and mutable borrows are invalidated by reads from any
398 this.emit_loan_invalidated_at(borrow_index, location);
401 (Reservation(_) | Activation(_, _) | Write(_), _) => {
402 // unique or mutable borrows are invalidated by writes.
403 // Reservations count as writes since we need to check
404 // that activating the borrow will be OK
405 // FIXME(bob_twinkles) is this actually the right thing to do?
406 this.emit_loan_invalidated_at(borrow_index, location);
414 /// Generates a new `loan_invalidated_at(L, B)` fact.
415 fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
416 let lidx = self.location_table.start_index(l);
417 self.all_facts.loan_invalidated_at.push((lidx, b));
420 fn check_activations(&mut self, location: Location) {
421 // Two-phase borrow support: For each activation that is newly
422 // generated at this statement, check if it interferes with
424 for &borrow_index in self.borrow_set.activations_at_location(location) {
425 let borrow = &self.borrow_set[borrow_index];
427 // only mutable borrows should be 2-phase
428 assert!(match borrow.kind {
429 BorrowKind::Shared | BorrowKind::Shallow => false,
430 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
435 borrow.borrowed_place,
436 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
437 LocalMutationIsAllowed::No,
440 // We do not need to call `check_if_path_or_subpath_is_moved`
441 // again, as we already called it when we made the
442 // initial reservation.