rustc_borrowck/polonius/legacy/
loan_invalidations.rs
1use std::ops::ControlFlow;
2
3use rustc_data_structures::graph::dominators::Dominators;
4use rustc_middle::bug;
5use rustc_middle::mir::visit::Visitor;
6use rustc_middle::mir::*;
7use rustc_middle::ty::TyCtxt;
8use tracing::debug;
9
10use super::{PoloniusFacts, PoloniusLocationTable};
11use crate::borrow_set::BorrowSet;
12use crate::path_utils::*;
13use crate::{
14 AccessDepth, Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read,
15 ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteKind,
16};
17
18pub(super) fn emit_loan_invalidations<'tcx>(
20 tcx: TyCtxt<'tcx>,
21 facts: &mut PoloniusFacts,
22 body: &Body<'tcx>,
23 location_table: &PoloniusLocationTable,
24 borrow_set: &BorrowSet<'tcx>,
25) {
26 let dominators = body.basic_blocks.dominators();
27 let mut visitor =
28 LoanInvalidationsGenerator { facts, borrow_set, tcx, location_table, body, dominators };
29 visitor.visit_body(body);
30}
31
32struct LoanInvalidationsGenerator<'a, 'tcx> {
33 tcx: TyCtxt<'tcx>,
34 facts: &'a mut PoloniusFacts,
35 body: &'a Body<'tcx>,
36 location_table: &'a PoloniusLocationTable,
37 dominators: &'a Dominators<BasicBlock>,
38 borrow_set: &'a BorrowSet<'tcx>,
39}
40
41impl<'a, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'a, 'tcx> {
44 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
45 self.check_activations(location);
46
47 match &statement.kind {
48 StatementKind::Assign(box (lhs, rhs)) => {
49 self.consume_rvalue(location, rhs);
50
51 self.mutate_place(location, *lhs, Shallow(None));
52 }
53 StatementKind::FakeRead(box (_, _)) => {
54 }
56 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => {
57 self.consume_operand(location, op);
58 }
59 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
60 src,
61 dst,
62 count,
63 })) => {
64 self.consume_operand(location, src);
65 self.consume_operand(location, dst);
66 self.consume_operand(location, count);
67 }
68 StatementKind::AscribeUserType(..)
70 | StatementKind::PlaceMention(..)
72 | StatementKind::Coverage(..)
74 | StatementKind::StorageLive(..) => {}
76 StatementKind::StorageDead(local) => {
77 self.access_place(
78 location,
79 Place::from(*local),
80 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
81 LocalMutationIsAllowed::Yes,
82 );
83 }
84 StatementKind::ConstEvalCounter
85 | StatementKind::Nop
86 | StatementKind::Retag { .. }
87 | StatementKind::Deinit(..)
88 | StatementKind::BackwardIncompatibleDropHint { .. }
89 | StatementKind::SetDiscriminant { .. } => {
90 bug!("Statement not allowed in this MIR phase")
91 }
92 }
93
94 self.super_statement(statement, location);
95 }
96
97 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
98 self.check_activations(location);
99
100 match &terminator.kind {
101 TerminatorKind::SwitchInt { discr, targets: _ } => {
102 self.consume_operand(location, discr);
103 }
104 TerminatorKind::Drop { place: drop_place, target: _, unwind: _, replace } => {
105 let write_kind =
106 if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
107 self.access_place(
108 location,
109 *drop_place,
110 (AccessDepth::Drop, Write(write_kind)),
111 LocalMutationIsAllowed::Yes,
112 );
113 }
114 TerminatorKind::Call {
115 func,
116 args,
117 destination,
118 target: _,
119 unwind: _,
120 call_source: _,
121 fn_span: _,
122 } => {
123 self.consume_operand(location, func);
124 for arg in args {
125 self.consume_operand(location, &arg.node);
126 }
127 self.mutate_place(location, *destination, Deep);
128 }
129 TerminatorKind::TailCall { func, args, .. } => {
130 self.consume_operand(location, func);
131 for arg in args {
132 self.consume_operand(location, &arg.node);
133 }
134 }
135 TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
136 self.consume_operand(location, cond);
137 use rustc_middle::mir::AssertKind;
138 if let AssertKind::BoundsCheck { len, index } = &**msg {
139 self.consume_operand(location, len);
140 self.consume_operand(location, index);
141 }
142 }
143 TerminatorKind::Yield { value, resume, resume_arg, drop: _ } => {
144 self.consume_operand(location, value);
145
146 let borrow_set = self.borrow_set;
148 let resume = self.location_table.start_index(resume.start_location());
149 for (i, data) in borrow_set.iter_enumerated() {
150 if borrow_of_local_data(data.borrowed_place) {
151 self.facts.loan_invalidated_at.push((resume, i));
152 }
153 }
154
155 self.mutate_place(location, *resume_arg, Deep);
156 }
157 TerminatorKind::UnwindResume
158 | TerminatorKind::Return
159 | TerminatorKind::CoroutineDrop => {
160 let borrow_set = self.borrow_set;
162 let start = self.location_table.start_index(location);
163 for (i, data) in borrow_set.iter_enumerated() {
164 if borrow_of_local_data(data.borrowed_place) {
165 self.facts.loan_invalidated_at.push((start, i));
166 }
167 }
168 }
169 TerminatorKind::InlineAsm {
170 asm_macro: _,
171 template: _,
172 operands,
173 options: _,
174 line_spans: _,
175 targets: _,
176 unwind: _,
177 } => {
178 for op in operands {
179 match op {
180 InlineAsmOperand::In { reg: _, 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: _, 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 | InlineAsmOperand::Label { target_index: _ } => {}
198 }
199 }
200 }
201 TerminatorKind::Goto { target: _ }
202 | TerminatorKind::UnwindTerminate(_)
203 | TerminatorKind::Unreachable
204 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
205 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
206 }
208 }
209
210 self.super_terminator(terminator, location);
211 }
212}
213
214impl<'a, 'tcx> LoanInvalidationsGenerator<'a, 'tcx> {
215 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 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 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
250 match rvalue {
251 &Rvalue::Ref(_ , bk, place) => {
252 let access_kind = match bk {
253 BorrowKind::Fake(FakeBorrowKind::Shallow) => {
254 (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
255 }
256 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
257 (Deep, Read(ReadKind::Borrow(bk)))
258 }
259 BorrowKind::Mut { .. } => {
260 let wk = WriteKind::MutableBorrow(bk);
261 if bk.allows_two_phase_borrow() {
262 (Deep, Reservation(wk))
263 } else {
264 (Deep, Write(wk))
265 }
266 }
267 };
268
269 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
270 }
271
272 &Rvalue::RawPtr(kind, place) => {
273 let access_kind = match kind {
274 RawPtrKind::Mut => (
275 Deep,
276 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
277 kind: MutBorrowKind::Default,
278 })),
279 ),
280 RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
281 RawPtrKind::FakeForPtrMetadata => {
282 (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
283 }
284 };
285
286 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
287 }
288
289 Rvalue::ThreadLocalRef(_) => {}
290
291 Rvalue::Use(operand)
292 | Rvalue::Repeat(operand, _)
293 | Rvalue::UnaryOp(_ , operand)
294 | Rvalue::Cast(_ , operand, _ )
295 | Rvalue::ShallowInitBox(operand, _ ) => self.consume_operand(location, operand),
296
297 &Rvalue::CopyForDeref(place) => {
298 let op = &Operand::Copy(place);
299 self.consume_operand(location, op);
300 }
301
302 &(Rvalue::Len(place) | Rvalue::Discriminant(place)) => {
303 let af = match rvalue {
304 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
305 Rvalue::Discriminant(..) => None,
306 _ => unreachable!(),
307 };
308 self.access_place(
309 location,
310 place,
311 (Shallow(af), Read(ReadKind::Copy)),
312 LocalMutationIsAllowed::No,
313 );
314 }
315
316 Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
317 self.consume_operand(location, operand1);
318 self.consume_operand(location, operand2);
319 }
320
321 Rvalue::NullaryOp(_op, _ty) => {}
322
323 Rvalue::Aggregate(_, operands) => {
324 for operand in operands {
325 self.consume_operand(location, operand);
326 }
327 }
328
329 Rvalue::WrapUnsafeBinder(op, _) => {
330 self.consume_operand(location, op);
331 }
332 }
333 }
334
335 fn access_place(
337 &mut self,
338 location: Location,
339 place: Place<'tcx>,
340 kind: (AccessDepth, ReadOrWrite),
341 _is_local_mutation_allowed: LocalMutationIsAllowed,
342 ) {
343 let (sd, rw) = kind;
344 self.check_access_for_conflict(location, place, sd, rw);
346 }
347
348 fn check_access_for_conflict(
349 &mut self,
350 location: Location,
351 place: Place<'tcx>,
352 sd: AccessDepth,
353 rw: ReadOrWrite,
354 ) {
355 debug!(
356 "check_access_for_conflict(location={:?}, place={:?}, sd={:?}, rw={:?})",
357 location, place, sd, rw,
358 );
359 each_borrow_involving_path(
360 self,
361 self.tcx,
362 self.body,
363 (sd, place),
364 self.borrow_set,
365 |_| true,
366 |this, borrow_index, borrow| {
367 match (rw, borrow.kind) {
368 (Activation(_, activating), _) if activating == borrow_index => {
375 }
378
379 (Read(_), BorrowKind::Fake(_) | BorrowKind::Shared)
380 | (
381 Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
382 BorrowKind::Mut { .. },
383 ) => {
384 }
386
387 (Read(_), BorrowKind::Mut { .. }) => {
388 if !is_active(this.dominators, borrow, location) {
390 assert!(borrow.kind.allows_two_phase_borrow());
392 return ControlFlow::Continue(());
393 }
394
395 this.emit_loan_invalidated_at(borrow_index, location);
398 }
399
400 (Reservation(_) | Activation(_, _) | Write(_), _) => {
401 this.emit_loan_invalidated_at(borrow_index, location);
406 }
407 }
408 ControlFlow::Continue(())
409 },
410 );
411 }
412
413 fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
415 let lidx = self.location_table.start_index(l);
416 self.facts.loan_invalidated_at.push((lidx, b));
417 }
418
419 fn check_activations(&mut self, location: Location) {
420 for &borrow_index in self.borrow_set.activations_at_location(location) {
424 let borrow = &self.borrow_set[borrow_index];
425
426 assert!(match borrow.kind {
428 BorrowKind::Shared | BorrowKind::Fake(_) => false,
429 BorrowKind::Mut { .. } => true,
430 });
431
432 self.access_place(
433 location,
434 borrow.borrowed_place,
435 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
436 LocalMutationIsAllowed::No,
437 );
438
439 }
443 }
444}