]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/invalidation.rs
Rollup merge of #67686 - ssomers:keys_start_slasher, r=Mark-Simulacrum
[rust.git] / src / librustc_mir / borrow_check / invalidation.rs
1 use rustc::mir::visit::Visitor;
2 use rustc::mir::TerminatorKind;
3 use rustc::mir::{BasicBlock, Body, Location, Place, ReadOnlyBodyAndCache, Rvalue};
4 use rustc::mir::{BorrowKind, Mutability, Operand};
5 use rustc::mir::{Statement, StatementKind};
6 use rustc::ty::TyCtxt;
7 use rustc_data_structures::graph::dominators::Dominators;
8
9 use crate::dataflow::indexes::BorrowIndex;
10
11 use crate::borrow_check::{
12     borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth,
13     Activation, ArtificialField, Deep, JustWrite, LocalMutationIsAllowed, MutateMode, Read,
14     ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteAndRead, WriteKind,
15 };
16
17 pub(super) fn generate_invalidates<'tcx>(
18     tcx: TyCtxt<'tcx>,
19     all_facts: &mut Option<AllFacts>,
20     location_table: &LocationTable,
21     body: ReadOnlyBodyAndCache<'_, 'tcx>,
22     borrow_set: &BorrowSet<'tcx>,
23 ) {
24     if all_facts.is_none() {
25         // Nothing to do if we don't have any facts
26         return;
27     }
28
29     if let Some(all_facts) = all_facts {
30         let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation");
31         let dominators = body.dominators();
32         let mut ig = InvalidationGenerator {
33             all_facts,
34             borrow_set,
35             tcx,
36             location_table,
37             body: &body,
38             dominators,
39         };
40         ig.visit_body(body);
41     }
42 }
43
44 struct InvalidationGenerator<'cx, 'tcx> {
45     tcx: TyCtxt<'tcx>,
46     all_facts: &'cx mut AllFacts,
47     location_table: &'cx LocationTable,
48     body: &'cx Body<'tcx>,
49     dominators: Dominators<BasicBlock>,
50     borrow_set: &'cx BorrowSet<'tcx>,
51 }
52
53 /// Visits the whole MIR and generates `invalidates()` facts.
54 /// Most of the code implementing this was stolen from `borrow_check/mod.rs`.
55 impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> {
56     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
57         self.check_activations(location);
58
59         match statement.kind {
60             StatementKind::Assign(box (ref lhs, ref rhs)) => {
61                 self.consume_rvalue(location, rhs);
62
63                 self.mutate_place(location, lhs, Shallow(None), JustWrite);
64             }
65             StatementKind::FakeRead(_, _) => {
66                 // Only relavent for initialized/liveness/safety checks.
67             }
68             StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
69                 self.mutate_place(location, place, Shallow(None), JustWrite);
70             }
71             StatementKind::InlineAsm(ref asm) => {
72                 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
73                     if o.is_indirect {
74                         // FIXME(eddyb) indirect inline asm outputs should
75                         // be encoded through MIR place derefs instead.
76                         self.access_place(
77                             location,
78                             output,
79                             (Deep, Read(ReadKind::Copy)),
80                             LocalMutationIsAllowed::No,
81                         );
82                     } else {
83                         self.mutate_place(
84                             location,
85                             output,
86                             if o.is_rw { Deep } else { Shallow(None) },
87                             if o.is_rw { WriteAndRead } else { JustWrite },
88                         );
89                     }
90                 }
91                 for (_, input) in asm.inputs.iter() {
92                     self.consume_operand(location, input);
93                 }
94             }
95             StatementKind::Nop
96             | StatementKind::AscribeUserType(..)
97             | StatementKind::Retag { .. }
98             | StatementKind::StorageLive(..) => {
99                 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
100                 // to borrow check.
101             }
102             StatementKind::StorageDead(local) => {
103                 self.access_place(
104                     location,
105                     &Place::from(local),
106                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
107                     LocalMutationIsAllowed::Yes,
108                 );
109             }
110         }
111
112         self.super_statement(statement, location);
113     }
114
115     fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
116         self.check_activations(location);
117
118         match kind {
119             TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
120                 self.consume_operand(location, discr);
121             }
122             TerminatorKind::Drop { location: ref drop_place, target: _, unwind: _ } => {
123                 self.access_place(
124                     location,
125                     drop_place,
126                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
127                     LocalMutationIsAllowed::Yes,
128                 );
129             }
130             TerminatorKind::DropAndReplace {
131                 location: ref drop_place,
132                 value: ref new_value,
133                 target: _,
134                 unwind: _,
135             } => {
136                 self.mutate_place(location, drop_place, Deep, JustWrite);
137                 self.consume_operand(location, new_value);
138             }
139             TerminatorKind::Call {
140                 ref func,
141                 ref args,
142                 ref destination,
143                 cleanup: _,
144                 from_hir_call: _,
145             } => {
146                 self.consume_operand(location, func);
147                 for arg in args {
148                     self.consume_operand(location, arg);
149                 }
150                 if let Some((ref dest, _ /*bb*/)) = *destination {
151                     self.mutate_place(location, dest, Deep, JustWrite);
152                 }
153             }
154             TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
155                 self.consume_operand(location, cond);
156                 use rustc::mir::interpret::PanicInfo;
157                 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
158                     self.consume_operand(location, len);
159                     self.consume_operand(location, index);
160                 }
161             }
162             TerminatorKind::Yield { ref value, resume, drop: _ } => {
163                 self.consume_operand(location, value);
164
165                 // Invalidate all borrows of local places
166                 let borrow_set = self.borrow_set.clone();
167                 let resume = self.location_table.start_index(resume.start_location());
168                 for i in borrow_set.borrows.indices() {
169                     if borrow_of_local_data(&borrow_set.borrows[i].borrowed_place) {
170                         self.all_facts.invalidates.push((resume, i));
171                     }
172                 }
173             }
174             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
175                 // Invalidate all borrows of local places
176                 let borrow_set = self.borrow_set.clone();
177                 let start = self.location_table.start_index(location);
178                 for i in borrow_set.borrows.indices() {
179                     if borrow_of_local_data(&borrow_set.borrows[i].borrowed_place) {
180                         self.all_facts.invalidates.push((start, i));
181                     }
182                 }
183             }
184             TerminatorKind::Goto { target: _ }
185             | TerminatorKind::Abort
186             | TerminatorKind::Unreachable
187             | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
188             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
189                 // no data used, thus irrelevant to borrowck
190             }
191         }
192
193         self.super_terminator_kind(kind, location);
194     }
195 }
196
197 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
198     /// Simulates mutation of a place.
199     fn mutate_place(
200         &mut self,
201         location: Location,
202         place: &Place<'tcx>,
203         kind: AccessDepth,
204         _mode: MutateMode,
205     ) {
206         self.access_place(
207             location,
208             place,
209             (kind, Write(WriteKind::Mutate)),
210             LocalMutationIsAllowed::ExceptUpvars,
211         );
212     }
213
214     /// Simulates consumption of an operand.
215     fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
216         match *operand {
217             Operand::Copy(ref place) => {
218                 self.access_place(
219                     location,
220                     place,
221                     (Deep, Read(ReadKind::Copy)),
222                     LocalMutationIsAllowed::No,
223                 );
224             }
225             Operand::Move(ref place) => {
226                 self.access_place(
227                     location,
228                     place,
229                     (Deep, Write(WriteKind::Move)),
230                     LocalMutationIsAllowed::Yes,
231                 );
232             }
233             Operand::Constant(_) => {}
234         }
235     }
236
237     // Simulates consumption of an rvalue
238     fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
239         match *rvalue {
240             Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
241                 let access_kind = match bk {
242                     BorrowKind::Shallow => {
243                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
244                     }
245                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
246                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
247                         let wk = WriteKind::MutableBorrow(bk);
248                         if allow_two_phase_borrow(bk) {
249                             (Deep, Reservation(wk))
250                         } else {
251                             (Deep, Write(wk))
252                         }
253                     }
254                 };
255
256                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
257             }
258
259             Rvalue::AddressOf(mutability, ref place) => {
260                 let access_kind = match mutability {
261                     Mutability::Mut => (
262                         Deep,
263                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
264                             allow_two_phase_borrow: false,
265                         })),
266                     ),
267                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
268                 };
269
270                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
271             }
272
273             Rvalue::Use(ref operand)
274             | Rvalue::Repeat(ref operand, _)
275             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
276             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
277                 self.consume_operand(location, operand)
278             }
279
280             Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
281                 let af = match *rvalue {
282                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
283                     Rvalue::Discriminant(..) => None,
284                     _ => unreachable!(),
285                 };
286                 self.access_place(
287                     location,
288                     place,
289                     (Shallow(af), Read(ReadKind::Copy)),
290                     LocalMutationIsAllowed::No,
291                 );
292             }
293
294             Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
295             | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
296                 self.consume_operand(location, operand1);
297                 self.consume_operand(location, operand2);
298             }
299
300             Rvalue::NullaryOp(_op, _ty) => {}
301
302             Rvalue::Aggregate(_, ref operands) => {
303                 for operand in operands {
304                     self.consume_operand(location, operand);
305                 }
306             }
307         }
308     }
309
310     /// Simulates an access to a place.
311     fn access_place(
312         &mut self,
313         location: Location,
314         place: &Place<'tcx>,
315         kind: (AccessDepth, ReadOrWrite),
316         _is_local_mutation_allowed: LocalMutationIsAllowed,
317     ) {
318         let (sd, rw) = kind;
319         // note: not doing check_access_permissions checks because they don't generate invalidates
320         self.check_access_for_conflict(location, place, sd, rw);
321     }
322
323     fn check_access_for_conflict(
324         &mut self,
325         location: Location,
326         place: &Place<'tcx>,
327         sd: AccessDepth,
328         rw: ReadOrWrite,
329     ) {
330         debug!(
331             "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
332              rw={:?})",
333             location, place, sd, rw,
334         );
335         let tcx = self.tcx;
336         let body = self.body;
337         let borrow_set = self.borrow_set.clone();
338         let indices = self.borrow_set.borrows.indices();
339         each_borrow_involving_path(
340             self,
341             tcx,
342             body,
343             location,
344             (sd, place),
345             &borrow_set.clone(),
346             indices,
347             |this, borrow_index, borrow| {
348                 match (rw, borrow.kind) {
349                     // Obviously an activation is compatible with its own
350                     // reservation (or even prior activating uses of same
351                     // borrow); so don't check if they interfere.
352                     //
353                     // NOTE: *reservations* do conflict with themselves;
354                     // thus aren't injecting unsoundenss w/ this check.)
355                     (Activation(_, activating), _) if activating == borrow_index => {
356                         // Activating a borrow doesn't generate any invalidations, since we
357                         // have already taken the reservation
358                     }
359
360                     (Read(_), BorrowKind::Shallow)
361                     | (Read(_), BorrowKind::Shared)
362                     | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
363                     | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
364                         // Reads don't invalidate shared or shallow borrows
365                     }
366
367                     (Read(_), BorrowKind::Unique) | (Read(_), BorrowKind::Mut { .. }) => {
368                         // Reading from mere reservations of mutable-borrows is OK.
369                         if !is_active(&this.dominators, borrow, location) {
370                             // If the borrow isn't active yet, reads don't invalidate it
371                             assert!(allow_two_phase_borrow(borrow.kind));
372                             return Control::Continue;
373                         }
374
375                         // Unique and mutable borrows are invalidated by reads from any
376                         // involved path
377                         this.generate_invalidates(borrow_index, location);
378                     }
379
380                     (Reservation(_), _) | (Activation(_, _), _) | (Write(_), _) => {
381                         // unique or mutable borrows are invalidated by writes.
382                         // Reservations count as writes since we need to check
383                         // that activating the borrow will be OK
384                         // FIXME(bob_twinkles) is this actually the right thing to do?
385                         this.generate_invalidates(borrow_index, location);
386                     }
387                 }
388                 Control::Continue
389             },
390         );
391     }
392
393     /// Generates a new `invalidates(L, B)` fact.
394     fn generate_invalidates(&mut self, b: BorrowIndex, l: Location) {
395         let lidx = self.location_table.start_index(l);
396         self.all_facts.invalidates.push((lidx, b));
397     }
398
399     fn check_activations(&mut self, location: Location) {
400         // Two-phase borrow support: For each activation that is newly
401         // generated at this statement, check if it interferes with
402         // another borrow.
403         for &borrow_index in self.borrow_set.activations_at_location(location) {
404             let borrow = &self.borrow_set[borrow_index];
405
406             // only mutable borrows should be 2-phase
407             assert!(match borrow.kind {
408                 BorrowKind::Shared | BorrowKind::Shallow => false,
409                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
410             });
411
412             self.access_place(
413                 location,
414                 &borrow.borrowed_place,
415                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
416                 LocalMutationIsAllowed::No,
417             );
418
419             // We do not need to call `check_if_path_or_subpath_is_moved`
420             // again, as we already called it when we made the
421             // initial reservation.
422         }
423     }
424 }