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.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::SetDiscriminant { place, variant_index: _ } => {
67 self.mutate_place(location, **place, Shallow(None));
69 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
74 self.consume_operand(location, src);
75 self.consume_operand(location, dst);
76 self.consume_operand(location, count);
79 | StatementKind::Coverage(..)
80 | StatementKind::AscribeUserType(..)
81 | StatementKind::Retag { .. }
82 | StatementKind::StorageLive(..) => {
83 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
86 StatementKind::StorageDead(local) => {
90 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
91 LocalMutationIsAllowed::Yes,
96 self.super_statement(statement, location);
99 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
100 self.check_activations(location);
102 match &terminator.kind {
103 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
104 self.consume_operand(location, discr);
106 TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
110 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
111 LocalMutationIsAllowed::Yes,
114 TerminatorKind::DropAndReplace {
116 value: ref new_value,
120 self.mutate_place(location, *drop_place, Deep);
121 self.consume_operand(location, new_value);
123 TerminatorKind::Call {
131 self.consume_operand(location, func);
133 self.consume_operand(location, arg);
135 if let Some((dest, _ /*bb*/)) = destination {
136 self.mutate_place(location, *dest, Deep);
139 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
140 self.consume_operand(location, cond);
141 use rustc_middle::mir::AssertKind;
142 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
143 self.consume_operand(location, len);
144 self.consume_operand(location, index);
147 TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
148 self.consume_operand(location, value);
150 // Invalidate all borrows of local places
151 let borrow_set = self.borrow_set;
152 let resume = self.location_table.start_index(resume.start_location());
153 for (i, data) in borrow_set.iter_enumerated() {
154 if borrow_of_local_data(data.borrowed_place) {
155 self.all_facts.loan_invalidated_at.push((resume, i));
159 self.mutate_place(location, *resume_arg, Deep);
161 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
162 // Invalidate all borrows of local places
163 let borrow_set = self.borrow_set;
164 let start = self.location_table.start_index(location);
165 for (i, data) in borrow_set.iter_enumerated() {
166 if borrow_of_local_data(data.borrowed_place) {
167 self.all_facts.loan_invalidated_at.push((start, i));
171 TerminatorKind::InlineAsm {
181 InlineAsmOperand::In { reg: _, ref value } => {
182 self.consume_operand(location, value);
184 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
185 if let Some(place) = place {
186 self.mutate_place(location, place, Shallow(None));
189 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
190 self.consume_operand(location, in_value);
191 if let Some(out_place) = out_place {
192 self.mutate_place(location, out_place, Shallow(None));
195 InlineAsmOperand::Const { value: _ }
196 | InlineAsmOperand::SymFn { value: _ }
197 | InlineAsmOperand::SymStatic { def_id: _ } => {}
201 TerminatorKind::Goto { target: _ }
202 | TerminatorKind::Abort
203 | TerminatorKind::Unreachable
204 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
205 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
206 // no data used, thus irrelevant to borrowck
210 self.super_terminator(terminator, location);
214 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
215 /// Simulates mutation of a place.
216 fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
220 (kind, Write(WriteKind::Mutate)),
221 LocalMutationIsAllowed::ExceptUpvars,
225 /// Simulates consumption of an operand.
226 fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
228 Operand::Copy(place) => {
232 (Deep, Read(ReadKind::Copy)),
233 LocalMutationIsAllowed::No,
236 Operand::Move(place) => {
240 (Deep, Write(WriteKind::Move)),
241 LocalMutationIsAllowed::Yes,
244 Operand::Constant(_) => {}
248 // Simulates consumption of an rvalue
249 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
251 Rvalue::Ref(_ /*rgn*/, bk, place) => {
252 let access_kind = match bk {
253 BorrowKind::Shallow => {
254 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
256 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
257 BorrowKind::Unique | BorrowKind::Mut { .. } => {
258 let wk = WriteKind::MutableBorrow(bk);
259 if allow_two_phase_borrow(bk) {
260 (Deep, Reservation(wk))
267 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
270 Rvalue::AddressOf(mutability, place) => {
271 let access_kind = match mutability {
274 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
275 allow_two_phase_borrow: false,
278 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
281 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
284 Rvalue::ThreadLocalRef(_) => {}
286 Rvalue::Use(ref operand)
287 | Rvalue::Repeat(ref operand, _)
288 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
289 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
290 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
291 self.consume_operand(location, operand)
294 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
295 let af = match *rvalue {
296 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
297 Rvalue::Discriminant(..) => None,
303 (Shallow(af), Read(ReadKind::Copy)),
304 LocalMutationIsAllowed::No,
308 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
309 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
310 self.consume_operand(location, operand1);
311 self.consume_operand(location, operand2);
314 Rvalue::NullaryOp(_op, _ty) => {}
316 Rvalue::Aggregate(_, ref operands) => {
317 for operand in operands {
318 self.consume_operand(location, operand);
324 /// Simulates an access to a place.
329 kind: (AccessDepth, ReadOrWrite),
330 _is_local_mutation_allowed: LocalMutationIsAllowed,
333 // note: not doing check_access_permissions checks because they don't generate invalidates
334 self.check_access_for_conflict(location, place, sd, rw);
337 fn check_access_for_conflict(
345 "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
347 location, place, sd, rw,
350 let body = self.body;
351 let borrow_set = self.borrow_set;
352 let indices = self.borrow_set.indices();
353 each_borrow_involving_path(
361 |this, borrow_index, borrow| {
362 match (rw, borrow.kind) {
363 // Obviously an activation is compatible with its own
364 // reservation (or even prior activating uses of same
365 // borrow); so don't check if they interfere.
367 // NOTE: *reservations* do conflict with themselves;
368 // thus aren't injecting unsoundenss w/ this check.)
369 (Activation(_, activating), _) if activating == borrow_index => {
370 // Activating a borrow doesn't generate any invalidations, since we
371 // have already taken the reservation
374 (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
376 Read(ReadKind::Borrow(BorrowKind::Shallow)),
377 BorrowKind::Unique | BorrowKind::Mut { .. },
379 // Reads don't invalidate shared or shallow borrows
382 (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
383 // Reading from mere reservations of mutable-borrows is OK.
384 if !is_active(&this.dominators, borrow, location) {
385 // If the borrow isn't active yet, reads don't invalidate it
386 assert!(allow_two_phase_borrow(borrow.kind));
387 return Control::Continue;
390 // Unique and mutable borrows are invalidated by reads from any
392 this.emit_loan_invalidated_at(borrow_index, location);
395 (Reservation(_) | Activation(_, _) | Write(_), _) => {
396 // unique or mutable borrows are invalidated by writes.
397 // Reservations count as writes since we need to check
398 // that activating the borrow will be OK
399 // FIXME(bob_twinkles) is this actually the right thing to do?
400 this.emit_loan_invalidated_at(borrow_index, location);
408 /// Generates a new `loan_invalidated_at(L, B)` fact.
409 fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
410 let lidx = self.location_table.start_index(l);
411 self.all_facts.loan_invalidated_at.push((lidx, b));
414 fn check_activations(&mut self, location: Location) {
415 // Two-phase borrow support: For each activation that is newly
416 // generated at this statement, check if it interferes with
418 for &borrow_index in self.borrow_set.activations_at_location(location) {
419 let borrow = &self.borrow_set[borrow_index];
421 // only mutable borrows should be 2-phase
422 assert!(match borrow.kind {
423 BorrowKind::Shared | BorrowKind::Shallow => false,
424 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
429 borrow.borrowed_place,
430 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
431 LocalMutationIsAllowed::No,
434 // We do not need to call `check_if_path_or_subpath_is_moved`
435 // again, as we already called it when we made the
436 // initial reservation.