]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/invalidation.rs
Rollup merge of #98886 - michaelwoerister:tracked-split-dwarf-kind, r=davidtwco
[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::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
67                 ref src,
68                 ref dst,
69                 ref count,
70             }) => {
71                 self.consume_operand(location, src);
72                 self.consume_operand(location, dst);
73                 self.consume_operand(location, count);
74             }
75             StatementKind::Nop
76             | StatementKind::Coverage(..)
77             | StatementKind::AscribeUserType(..)
78             | StatementKind::Retag { .. }
79             | StatementKind::StorageLive(..) => {
80                 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
81                 // to borrow check.
82             }
83             StatementKind::StorageDead(local) => {
84                 self.access_place(
85                     location,
86                     Place::from(*local),
87                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
88                     LocalMutationIsAllowed::Yes,
89                 );
90             }
91             StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
92                 bug!("Statement not allowed in this MIR phase")
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                 target: _,
128                 cleanup: _,
129                 from_hir_call: _,
130                 fn_span: _,
131             } => {
132                 self.consume_operand(location, func);
133                 for arg in args {
134                     self.consume_operand(location, arg);
135                 }
136                 self.mutate_place(location, *destination, Deep);
137             }
138             TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
139                 self.consume_operand(location, cond);
140                 use rustc_middle::mir::AssertKind;
141                 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
142                     self.consume_operand(location, len);
143                     self.consume_operand(location, index);
144                 }
145             }
146             TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
147                 self.consume_operand(location, value);
148
149                 // Invalidate all borrows of local places
150                 let borrow_set = self.borrow_set;
151                 let resume = self.location_table.start_index(resume.start_location());
152                 for (i, data) in borrow_set.iter_enumerated() {
153                     if borrow_of_local_data(data.borrowed_place) {
154                         self.all_facts.loan_invalidated_at.push((resume, i));
155                     }
156                 }
157
158                 self.mutate_place(location, *resume_arg, Deep);
159             }
160             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
161                 // Invalidate all borrows of local places
162                 let borrow_set = self.borrow_set;
163                 let start = self.location_table.start_index(location);
164                 for (i, data) in borrow_set.iter_enumerated() {
165                     if borrow_of_local_data(data.borrowed_place) {
166                         self.all_facts.loan_invalidated_at.push((start, i));
167                     }
168                 }
169             }
170             TerminatorKind::InlineAsm {
171                 template: _,
172                 ref operands,
173                 options: _,
174                 line_spans: _,
175                 destination: _,
176                 cleanup: _,
177             } => {
178                 for op in operands {
179                     match *op {
180                         InlineAsmOperand::In { reg: _, ref value } => {
181                             self.consume_operand(location, value);
182                         }
183                         InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
184                             if let Some(place) = place {
185                                 self.mutate_place(location, place, Shallow(None));
186                             }
187                         }
188                         InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
189                             self.consume_operand(location, in_value);
190                             if let Some(out_place) = out_place {
191                                 self.mutate_place(location, out_place, Shallow(None));
192                             }
193                         }
194                         InlineAsmOperand::Const { value: _ }
195                         | InlineAsmOperand::SymFn { value: _ }
196                         | InlineAsmOperand::SymStatic { def_id: _ } => {}
197                     }
198                 }
199             }
200             TerminatorKind::Goto { target: _ }
201             | TerminatorKind::Abort
202             | TerminatorKind::Unreachable
203             | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
204             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
205                 // no data used, thus irrelevant to borrowck
206             }
207         }
208
209         self.super_terminator(terminator, location);
210     }
211 }
212
213 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
214     /// Simulates mutation of a place.
215     fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
216         self.access_place(
217             location,
218             place,
219             (kind, Write(WriteKind::Mutate)),
220             LocalMutationIsAllowed::ExceptUpvars,
221         );
222     }
223
224     /// Simulates consumption of an operand.
225     fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
226         match *operand {
227             Operand::Copy(place) => {
228                 self.access_place(
229                     location,
230                     place,
231                     (Deep, Read(ReadKind::Copy)),
232                     LocalMutationIsAllowed::No,
233                 );
234             }
235             Operand::Move(place) => {
236                 self.access_place(
237                     location,
238                     place,
239                     (Deep, Write(WriteKind::Move)),
240                     LocalMutationIsAllowed::Yes,
241                 );
242             }
243             Operand::Constant(_) => {}
244         }
245     }
246
247     // Simulates consumption of an rvalue
248     fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
249         match *rvalue {
250             Rvalue::Ref(_ /*rgn*/, bk, place) => {
251                 let access_kind = match bk {
252                     BorrowKind::Shallow => {
253                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
254                     }
255                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
256                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
257                         let wk = WriteKind::MutableBorrow(bk);
258                         if allow_two_phase_borrow(bk) {
259                             (Deep, Reservation(wk))
260                         } else {
261                             (Deep, Write(wk))
262                         }
263                     }
264                 };
265
266                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
267             }
268
269             Rvalue::AddressOf(mutability, place) => {
270                 let access_kind = match mutability {
271                     Mutability::Mut => (
272                         Deep,
273                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
274                             allow_two_phase_borrow: false,
275                         })),
276                     ),
277                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
278                 };
279
280                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
281             }
282
283             Rvalue::ThreadLocalRef(_) => {}
284
285             Rvalue::Use(ref operand)
286             | Rvalue::Repeat(ref operand, _)
287             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
288             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
289             | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
290                 self.consume_operand(location, operand)
291             }
292
293             Rvalue::Len(place) | Rvalue::Discriminant(place) => {
294                 let af = match *rvalue {
295                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
296                     Rvalue::Discriminant(..) => None,
297                     _ => unreachable!(),
298                 };
299                 self.access_place(
300                     location,
301                     place,
302                     (Shallow(af), Read(ReadKind::Copy)),
303                     LocalMutationIsAllowed::No,
304                 );
305             }
306
307             Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
308             | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
309                 self.consume_operand(location, operand1);
310                 self.consume_operand(location, operand2);
311             }
312
313             Rvalue::NullaryOp(_op, _ty) => {}
314
315             Rvalue::Aggregate(_, ref operands) => {
316                 for operand in operands {
317                     self.consume_operand(location, operand);
318                 }
319             }
320         }
321     }
322
323     /// Simulates an access to a place.
324     fn access_place(
325         &mut self,
326         location: Location,
327         place: Place<'tcx>,
328         kind: (AccessDepth, ReadOrWrite),
329         _is_local_mutation_allowed: LocalMutationIsAllowed,
330     ) {
331         let (sd, rw) = kind;
332         // note: not doing check_access_permissions checks because they don't generate invalidates
333         self.check_access_for_conflict(location, place, sd, rw);
334     }
335
336     fn check_access_for_conflict(
337         &mut self,
338         location: Location,
339         place: Place<'tcx>,
340         sd: AccessDepth,
341         rw: ReadOrWrite,
342     ) {
343         debug!(
344             "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
345              rw={:?})",
346             location, place, sd, rw,
347         );
348         let tcx = self.tcx;
349         let body = self.body;
350         let borrow_set = self.borrow_set;
351         let indices = self.borrow_set.indices();
352         each_borrow_involving_path(
353             self,
354             tcx,
355             body,
356             location,
357             (sd, place),
358             borrow_set,
359             indices,
360             |this, borrow_index, borrow| {
361                 match (rw, borrow.kind) {
362                     // Obviously an activation is compatible with its own
363                     // reservation (or even prior activating uses of same
364                     // borrow); so don't check if they interfere.
365                     //
366                     // NOTE: *reservations* do conflict with themselves;
367                     // thus aren't injecting unsoundness w/ this check.)
368                     (Activation(_, activating), _) if activating == borrow_index => {
369                         // Activating a borrow doesn't generate any invalidations, since we
370                         // have already taken the reservation
371                     }
372
373                     (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
374                     | (
375                         Read(ReadKind::Borrow(BorrowKind::Shallow)),
376                         BorrowKind::Unique | BorrowKind::Mut { .. },
377                     ) => {
378                         // Reads don't invalidate shared or shallow borrows
379                     }
380
381                     (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
382                         // Reading from mere reservations of mutable-borrows is OK.
383                         if !is_active(&this.dominators, borrow, location) {
384                             // If the borrow isn't active yet, reads don't invalidate it
385                             assert!(allow_two_phase_borrow(borrow.kind));
386                             return Control::Continue;
387                         }
388
389                         // Unique and mutable borrows are invalidated by reads from any
390                         // involved path
391                         this.emit_loan_invalidated_at(borrow_index, location);
392                     }
393
394                     (Reservation(_) | Activation(_, _) | Write(_), _) => {
395                         // unique or mutable borrows are invalidated by writes.
396                         // Reservations count as writes since we need to check
397                         // that activating the borrow will be OK
398                         // FIXME(bob_twinkles) is this actually the right thing to do?
399                         this.emit_loan_invalidated_at(borrow_index, location);
400                     }
401                 }
402                 Control::Continue
403             },
404         );
405     }
406
407     /// Generates a new `loan_invalidated_at(L, B)` fact.
408     fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
409         let lidx = self.location_table.start_index(l);
410         self.all_facts.loan_invalidated_at.push((lidx, b));
411     }
412
413     fn check_activations(&mut self, location: Location) {
414         // Two-phase borrow support: For each activation that is newly
415         // generated at this statement, check if it interferes with
416         // another borrow.
417         for &borrow_index in self.borrow_set.activations_at_location(location) {
418             let borrow = &self.borrow_set[borrow_index];
419
420             // only mutable borrows should be 2-phase
421             assert!(match borrow.kind {
422                 BorrowKind::Shared | BorrowKind::Shallow => false,
423                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
424             });
425
426             self.access_place(
427                 location,
428                 borrow.borrowed_place,
429                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
430                 LocalMutationIsAllowed::No,
431             );
432
433             // We do not need to call `check_if_path_or_subpath_is_moved`
434             // again, as we already called it when we made the
435             // initial reservation.
436         }
437     }
438 }