]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/invalidation.rs
Merge commit 'a98e7ab8b94485be6bd03e0c6b8682ecab5b52e6' into clippyup
[rust.git] / compiler / rustc_borrowck / src / invalidation.rs
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;
8
9 use crate::{
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,
13 };
14
15 pub(super) fn generate_invalidates<'tcx>(
16     tcx: TyCtxt<'tcx>,
17     all_facts: &mut Option<AllFacts>,
18     location_table: &LocationTable,
19     body: &Body<'tcx>,
20     borrow_set: &BorrowSet<'tcx>,
21 ) {
22     if all_facts.is_none() {
23         // Nothing to do if we don't have any facts
24         return;
25     }
26
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 {
31             all_facts,
32             borrow_set,
33             tcx,
34             location_table,
35             body: &body,
36             dominators,
37         };
38         ig.visit_body(body);
39     }
40 }
41
42 struct InvalidationGenerator<'cx, 'tcx> {
43     tcx: TyCtxt<'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>,
49 }
50
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);
56
57         match &statement.kind {
58             StatementKind::Assign(box (lhs, rhs)) => {
59                 self.consume_rvalue(location, rhs);
60
61                 self.mutate_place(location, *lhs, Shallow(None));
62             }
63             StatementKind::FakeRead(box (_, _)) => {
64                 // Only relevant for initialized/liveness/safety checks.
65             }
66             StatementKind::SetDiscriminant { place, variant_index: _ } => {
67                 self.mutate_place(location, **place, Shallow(None));
68             }
69             StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
70                 ref src,
71                 ref dst,
72                 ref count,
73             }) => {
74                 self.consume_operand(location, src);
75                 self.consume_operand(location, dst);
76                 self.consume_operand(location, count);
77             }
78             StatementKind::Nop
79             | StatementKind::Coverage(..)
80             | StatementKind::AscribeUserType(..)
81             | StatementKind::Retag { .. }
82             | StatementKind::StorageLive(..) => {
83                 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
84                 // to borrow check.
85             }
86             StatementKind::StorageDead(local) => {
87                 self.access_place(
88                     location,
89                     Place::from(*local),
90                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
91                     LocalMutationIsAllowed::Yes,
92                 );
93             }
94         }
95
96         self.super_statement(statement, location);
97     }
98
99     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
100         self.check_activations(location);
101
102         match &terminator.kind {
103             TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
104                 self.consume_operand(location, discr);
105             }
106             TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
107                 self.access_place(
108                     location,
109                     *drop_place,
110                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
111                     LocalMutationIsAllowed::Yes,
112                 );
113             }
114             TerminatorKind::DropAndReplace {
115                 place: drop_place,
116                 value: ref new_value,
117                 target: _,
118                 unwind: _,
119             } => {
120                 self.mutate_place(location, *drop_place, Deep);
121                 self.consume_operand(location, new_value);
122             }
123             TerminatorKind::Call {
124                 ref func,
125                 ref args,
126                 destination,
127                 cleanup: _,
128                 from_hir_call: _,
129                 fn_span: _,
130             } => {
131                 self.consume_operand(location, func);
132                 for arg in args {
133                     self.consume_operand(location, arg);
134                 }
135                 if let Some((dest, _ /*bb*/)) = destination {
136                     self.mutate_place(location, *dest, Deep);
137                 }
138             }
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);
145                 }
146             }
147             TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
148                 self.consume_operand(location, value);
149
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));
156                     }
157                 }
158
159                 self.mutate_place(location, *resume_arg, Deep);
160             }
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));
168                     }
169                 }
170             }
171             TerminatorKind::InlineAsm {
172                 template: _,
173                 ref operands,
174                 options: _,
175                 line_spans: _,
176                 destination: _,
177                 cleanup: _,
178             } => {
179                 for op in operands {
180                     match *op {
181                         InlineAsmOperand::In { reg: _, ref value } => {
182                             self.consume_operand(location, value);
183                         }
184                         InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
185                             if let Some(place) = place {
186                                 self.mutate_place(location, place, Shallow(None));
187                             }
188                         }
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));
193                             }
194                         }
195                         InlineAsmOperand::Const { value: _ }
196                         | InlineAsmOperand::SymFn { value: _ }
197                         | InlineAsmOperand::SymStatic { def_id: _ } => {}
198                     }
199                 }
200             }
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
207             }
208         }
209
210         self.super_terminator(terminator, location);
211     }
212 }
213
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) {
217         self.access_place(
218             location,
219             place,
220             (kind, Write(WriteKind::Mutate)),
221             LocalMutationIsAllowed::ExceptUpvars,
222         );
223     }
224
225     /// Simulates consumption of an operand.
226     fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
227         match *operand {
228             Operand::Copy(place) => {
229                 self.access_place(
230                     location,
231                     place,
232                     (Deep, Read(ReadKind::Copy)),
233                     LocalMutationIsAllowed::No,
234                 );
235             }
236             Operand::Move(place) => {
237                 self.access_place(
238                     location,
239                     place,
240                     (Deep, Write(WriteKind::Move)),
241                     LocalMutationIsAllowed::Yes,
242                 );
243             }
244             Operand::Constant(_) => {}
245         }
246     }
247
248     // Simulates consumption of an rvalue
249     fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
250         match *rvalue {
251             Rvalue::Ref(_ /*rgn*/, bk, place) => {
252                 let access_kind = match bk {
253                     BorrowKind::Shallow => {
254                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
255                     }
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))
261                         } else {
262                             (Deep, Write(wk))
263                         }
264                     }
265                 };
266
267                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
268             }
269
270             Rvalue::AddressOf(mutability, place) => {
271                 let access_kind = match mutability {
272                     Mutability::Mut => (
273                         Deep,
274                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
275                             allow_two_phase_borrow: false,
276                         })),
277                     ),
278                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
279                 };
280
281                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
282             }
283
284             Rvalue::ThreadLocalRef(_) => {}
285
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)
292             }
293
294             Rvalue::Len(place) | Rvalue::Discriminant(place) => {
295                 let af = match *rvalue {
296                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
297                     Rvalue::Discriminant(..) => None,
298                     _ => unreachable!(),
299                 };
300                 self.access_place(
301                     location,
302                     place,
303                     (Shallow(af), Read(ReadKind::Copy)),
304                     LocalMutationIsAllowed::No,
305                 );
306             }
307
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);
312             }
313
314             Rvalue::NullaryOp(_op, _ty) => {}
315
316             Rvalue::Aggregate(_, ref operands) => {
317                 for operand in operands {
318                     self.consume_operand(location, operand);
319                 }
320             }
321         }
322     }
323
324     /// Simulates an access to a place.
325     fn access_place(
326         &mut self,
327         location: Location,
328         place: Place<'tcx>,
329         kind: (AccessDepth, ReadOrWrite),
330         _is_local_mutation_allowed: LocalMutationIsAllowed,
331     ) {
332         let (sd, rw) = kind;
333         // note: not doing check_access_permissions checks because they don't generate invalidates
334         self.check_access_for_conflict(location, place, sd, rw);
335     }
336
337     fn check_access_for_conflict(
338         &mut self,
339         location: Location,
340         place: Place<'tcx>,
341         sd: AccessDepth,
342         rw: ReadOrWrite,
343     ) {
344         debug!(
345             "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
346              rw={:?})",
347             location, place, sd, rw,
348         );
349         let tcx = self.tcx;
350         let body = self.body;
351         let borrow_set = self.borrow_set;
352         let indices = self.borrow_set.indices();
353         each_borrow_involving_path(
354             self,
355             tcx,
356             body,
357             location,
358             (sd, place),
359             borrow_set,
360             indices,
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.
366                     //
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
372                     }
373
374                     (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
375                     | (
376                         Read(ReadKind::Borrow(BorrowKind::Shallow)),
377                         BorrowKind::Unique | BorrowKind::Mut { .. },
378                     ) => {
379                         // Reads don't invalidate shared or shallow borrows
380                     }
381
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;
388                         }
389
390                         // Unique and mutable borrows are invalidated by reads from any
391                         // involved path
392                         this.emit_loan_invalidated_at(borrow_index, location);
393                     }
394
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);
401                     }
402                 }
403                 Control::Continue
404             },
405         );
406     }
407
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));
412     }
413
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
417         // another borrow.
418         for &borrow_index in self.borrow_set.activations_at_location(location) {
419             let borrow = &self.borrow_set[borrow_index];
420
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,
425             });
426
427             self.access_place(
428                 location,
429                 borrow.borrowed_place,
430                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
431                 LocalMutationIsAllowed::No,
432             );
433
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.
437         }
438     }
439 }