]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/redundant_clone.rs
b3988973256c4c16cad3c8306c6e43cf4916b062
[rust.git] / src / tools / clippy / clippy_lints / src / redundant_clone.rs
1 use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::{has_drop, is_copy, is_type_diagnostic_item, walk_ptrs_ty_depth};
4 use clippy_utils::{fn_has_unsatisfiable_preds, match_def_path, paths};
5 use if_chain::if_chain;
6 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::FnKind;
9 use rustc_hir::{def_id, Body, FnDecl, HirId};
10 use rustc_index::bit_set::{BitSet, HybridBitSet};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::mir::{
13     self, traversal,
14     visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor as _},
15     Mutability,
16 };
17 use rustc_middle::ty::{self, fold::TypeVisitor, Ty};
18 use rustc_mir_dataflow::{Analysis, AnalysisDomain, CallReturnPlaces, GenKill, GenKillAnalysis, ResultsCursor};
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
20 use rustc_span::source_map::{BytePos, Span};
21 use rustc_span::sym;
22 use std::convert::TryFrom;
23 use std::ops::ControlFlow;
24
25 macro_rules! unwrap_or_continue {
26     ($x:expr) => {
27         match $x {
28             Some(x) => x,
29             None => continue,
30         }
31     };
32 }
33
34 declare_clippy_lint! {
35     /// ### What it does
36     /// Checks for a redundant `clone()` (and its relatives) which clones an owned
37     /// value that is going to be dropped without further use.
38     ///
39     /// ### Why is this bad?
40     /// It is not always possible for the compiler to eliminate useless
41     /// allocations and deallocations generated by redundant `clone()`s.
42     ///
43     /// ### Known problems
44     /// False-negatives: analysis performed by this lint is conservative and limited.
45     ///
46     /// ### Example
47     /// ```rust
48     /// # use std::path::Path;
49     /// # #[derive(Clone)]
50     /// # struct Foo;
51     /// # impl Foo {
52     /// #     fn new() -> Self { Foo {} }
53     /// # }
54     /// # fn call(x: Foo) {}
55     /// {
56     ///     let x = Foo::new();
57     ///     call(x.clone());
58     ///     call(x.clone()); // this can just pass `x`
59     /// }
60     ///
61     /// ["lorem", "ipsum"].join(" ").to_string();
62     ///
63     /// Path::new("/a/b").join("c").to_path_buf();
64     /// ```
65     #[clippy::version = "1.32.0"]
66     pub REDUNDANT_CLONE,
67     perf,
68     "`clone()` of an owned value that is going to be dropped immediately"
69 }
70
71 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
72
73 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
74     #[allow(clippy::too_many_lines)]
75     fn check_fn(
76         &mut self,
77         cx: &LateContext<'tcx>,
78         _: FnKind<'tcx>,
79         _: &'tcx FnDecl<'_>,
80         body: &'tcx Body<'_>,
81         _: Span,
82         _: HirId,
83     ) {
84         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
85
86         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
87         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
88             return;
89         }
90
91         let mir = cx.tcx.optimized_mir(def_id.to_def_id());
92
93         let possible_origin = {
94             let mut vis = PossibleOriginVisitor::new(mir);
95             vis.visit_body(mir);
96             vis.into_map(cx)
97         };
98         let maybe_storage_live_result = MaybeStorageLive
99             .into_engine(cx.tcx, mir)
100             .pass_name("redundant_clone")
101             .iterate_to_fixpoint()
102             .into_results_cursor(mir);
103         let mut possible_borrower = {
104             let mut vis = PossibleBorrowerVisitor::new(cx, mir, possible_origin);
105             vis.visit_body(mir);
106             vis.into_map(cx, maybe_storage_live_result)
107         };
108
109         for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
110             let terminator = bbdata.terminator();
111
112             if terminator.source_info.span.from_expansion() {
113                 continue;
114             }
115
116             // Give up on loops
117             if terminator.successors().any(|s| *s == bb) {
118                 continue;
119             }
120
121             let (fn_def_id, arg, arg_ty, clone_ret) =
122                 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
123
124             let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
125                 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
126                 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD)
127                     && is_type_diagnostic_item(cx, arg_ty, sym::String));
128
129             let from_deref = !from_borrow
130                 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
131                     || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
132
133             if !from_borrow && !from_deref {
134                 continue;
135             }
136
137             if let ty::Adt(def, _) = arg_ty.kind() {
138                 if def.is_manually_drop() {
139                     continue;
140                 }
141             }
142
143             // `{ arg = &cloned; clone(move arg); }` or `{ arg = &cloned; to_path_buf(arg); }`
144             let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
145
146             let loc = mir::Location {
147                 block: bb,
148                 statement_index: bbdata.statements.len(),
149             };
150
151             // `Local` to be cloned, and a local of `clone` call's destination
152             let (local, ret_local) = if from_borrow {
153                 // `res = clone(arg)` can be turned into `res = move arg;`
154                 // if `arg` is the only borrow of `cloned` at this point.
155
156                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
157                     continue;
158                 }
159
160                 (cloned, clone_ret)
161             } else {
162                 // `arg` is a reference as it is `.deref()`ed in the previous block.
163                 // Look into the predecessor block and find out the source of deref.
164
165                 let ps = &mir.predecessors()[bb];
166                 if ps.len() != 1 {
167                     continue;
168                 }
169                 let pred_terminator = mir[ps[0]].terminator();
170
171                 // receiver of the `deref()` call
172                 let (pred_arg, deref_clone_ret) = if_chain! {
173                     if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, res)) =
174                         is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
175                     if res == cloned;
176                     if cx.tcx.is_diagnostic_item(sym::deref_method, pred_fn_def_id);
177                     if is_type_diagnostic_item(cx, pred_arg_ty, sym::PathBuf)
178                         || is_type_diagnostic_item(cx, pred_arg_ty, sym::OsString);
179                     then {
180                         (pred_arg, res)
181                     } else {
182                         continue;
183                     }
184                 };
185
186                 let (local, cannot_move_out) =
187                     unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
188                 let loc = mir::Location {
189                     block: bb,
190                     statement_index: mir.basic_blocks()[bb].statements.len(),
191                 };
192
193                 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
194                 // at the last statement:
195                 //
196                 // ```
197                 // pred_arg = &local;
198                 // cloned = deref(pred_arg);
199                 // arg = &cloned;
200                 // StorageDead(pred_arg);
201                 // res = to_path_buf(cloned);
202                 // ```
203                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
204                     continue;
205                 }
206
207                 (local, deref_clone_ret)
208             };
209
210             let clone_usage = if local == ret_local {
211                 CloneUsage {
212                     cloned_used: false,
213                     cloned_consume_or_mutate_loc: None,
214                     clone_consumed_or_mutated: true,
215                 }
216             } else {
217                 let clone_usage = visit_clone_usage(local, ret_local, mir, bb);
218                 if clone_usage.cloned_used && clone_usage.clone_consumed_or_mutated {
219                     // cloned value is used, and the clone is modified or moved
220                     continue;
221                 } else if let Some(loc) = clone_usage.cloned_consume_or_mutate_loc {
222                     // cloned value is mutated, and the clone is alive.
223                     if possible_borrower.local_is_alive_at(ret_local, loc) {
224                         continue;
225                     }
226                 }
227                 clone_usage
228             };
229
230             let span = terminator.source_info.span;
231             let scope = terminator.source_info.scope;
232             let node = mir.source_scopes[scope]
233                 .local_data
234                 .as_ref()
235                 .assert_crate_local()
236                 .lint_root;
237
238             if_chain! {
239                 if let Some(snip) = snippet_opt(cx, span);
240                 if let Some(dot) = snip.rfind('.');
241                 then {
242                     let sugg_span = span.with_lo(
243                         span.lo() + BytePos(u32::try_from(dot).unwrap())
244                     );
245                     let mut app = Applicability::MaybeIncorrect;
246
247                     let call_snip = &snip[dot + 1..];
248                     // Machine applicable when `call_snip` looks like `foobar()`
249                     if let Some(call_snip) = call_snip.strip_suffix("()").map(str::trim) {
250                         if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
251                             app = Applicability::MachineApplicable;
252                         }
253                     }
254
255                     span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
256                         diag.span_suggestion(
257                             sugg_span,
258                             "remove this",
259                             String::new(),
260                             app,
261                         );
262                         if clone_usage.cloned_used {
263                             diag.span_note(
264                                 span,
265                                 "cloned value is neither consumed nor mutated",
266                             );
267                         } else {
268                             diag.span_note(
269                                 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
270                                 "this value is dropped without further use",
271                             );
272                         }
273                     });
274                 } else {
275                     span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
276                 }
277             }
278         }
279     }
280 }
281
282 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
283 fn is_call_with_ref_arg<'tcx>(
284     cx: &LateContext<'tcx>,
285     mir: &'tcx mir::Body<'tcx>,
286     kind: &'tcx mir::TerminatorKind<'tcx>,
287 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
288     if_chain! {
289         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
290         if args.len() == 1;
291         if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
292         if let ty::FnDef(def_id, _) = *func.ty(&*mir, cx.tcx).kind();
293         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
294         if !is_copy(cx, inner_ty);
295         then {
296             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
297         } else {
298             None
299         }
300     }
301 }
302
303 type CannotMoveOut = bool;
304
305 /// Finds the first `to = (&)from`, and returns
306 /// ``Some((from, whether `from` cannot be moved out))``.
307 fn find_stmt_assigns_to<'tcx>(
308     cx: &LateContext<'tcx>,
309     mir: &mir::Body<'tcx>,
310     to_local: mir::Local,
311     by_ref: bool,
312     bb: mir::BasicBlock,
313 ) -> Option<(mir::Local, CannotMoveOut)> {
314     let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
315         if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
316             return if *local == to_local { Some(v) } else { None };
317         }
318
319         None
320     })?;
321
322     match (by_ref, &*rvalue) {
323         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
324             Some(base_local_and_movability(cx, mir, *place))
325         },
326         (false, mir::Rvalue::Ref(_, _, place)) => {
327             if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
328                 Some(base_local_and_movability(cx, mir, *place))
329             } else {
330                 None
331             }
332         },
333         _ => None,
334     }
335 }
336
337 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
338 /// if it is already a `Local`.
339 ///
340 /// Also reports whether given `place` cannot be moved out.
341 fn base_local_and_movability<'tcx>(
342     cx: &LateContext<'tcx>,
343     mir: &mir::Body<'tcx>,
344     place: mir::Place<'tcx>,
345 ) -> (mir::Local, CannotMoveOut) {
346     use rustc_middle::mir::PlaceRef;
347
348     // Dereference. You cannot move things out from a borrowed value.
349     let mut deref = false;
350     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
351     let mut field = false;
352     // If projection is a slice index then clone can be removed only if the
353     // underlying type implements Copy
354     let mut slice = false;
355
356     let PlaceRef { local, mut projection } = place.as_ref();
357     while let [base @ .., elem] = projection {
358         projection = base;
359         deref |= matches!(elem, mir::ProjectionElem::Deref);
360         field |= matches!(elem, mir::ProjectionElem::Field(..))
361             && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
362         slice |= matches!(elem, mir::ProjectionElem::Index(..))
363             && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
364     }
365
366     (local, deref || field || slice)
367 }
368
369 #[derive(Default)]
370 struct CloneUsage {
371     /// Whether the cloned value is used after the clone.
372     cloned_used: bool,
373     /// The first location where the cloned value is consumed or mutated, if any.
374     cloned_consume_or_mutate_loc: Option<mir::Location>,
375     /// Whether the clone value is mutated.
376     clone_consumed_or_mutated: bool,
377 }
378 fn visit_clone_usage(cloned: mir::Local, clone: mir::Local, mir: &mir::Body<'_>, bb: mir::BasicBlock) -> CloneUsage {
379     struct V {
380         cloned: mir::Local,
381         clone: mir::Local,
382         result: CloneUsage,
383     }
384     impl<'tcx> mir::visit::Visitor<'tcx> for V {
385         fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
386             let statements = &data.statements;
387             for (statement_index, statement) in statements.iter().enumerate() {
388                 self.visit_statement(statement, mir::Location { block, statement_index });
389             }
390
391             self.visit_terminator(
392                 data.terminator(),
393                 mir::Location {
394                     block,
395                     statement_index: statements.len(),
396                 },
397             );
398         }
399
400         fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, loc: mir::Location) {
401             let local = place.local;
402
403             if local == self.cloned
404                 && !matches!(
405                     ctx,
406                     PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_)
407                 )
408             {
409                 self.result.cloned_used = true;
410                 self.result.cloned_consume_or_mutate_loc = self.result.cloned_consume_or_mutate_loc.or_else(|| {
411                     matches!(
412                         ctx,
413                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
414                             | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
415                     )
416                     .then(|| loc)
417                 });
418             } else if local == self.clone {
419                 match ctx {
420                     PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
421                     | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
422                         self.result.clone_consumed_or_mutated = true;
423                     },
424                     _ => {},
425                 }
426             }
427         }
428     }
429
430     let init = CloneUsage {
431         cloned_used: false,
432         cloned_consume_or_mutate_loc: None,
433         // Consider non-temporary clones consumed.
434         // TODO: Actually check for mutation of non-temporaries.
435         clone_consumed_or_mutated: mir.local_kind(clone) != mir::LocalKind::Temp,
436     };
437     traversal::ReversePostorder::new(mir, bb)
438         .skip(1)
439         .fold(init, |usage, (tbb, tdata)| {
440             // Short-circuit
441             if (usage.cloned_used && usage.clone_consumed_or_mutated) ||
442                 // Give up on loops
443                 tdata.terminator().successors().any(|s| *s == bb)
444             {
445                 return CloneUsage {
446                     cloned_used: true,
447                     clone_consumed_or_mutated: true,
448                     ..usage
449                 };
450             }
451
452             let mut v = V {
453                 cloned,
454                 clone,
455                 result: usage,
456             };
457             v.visit_basic_block_data(tbb, tdata);
458             v.result
459         })
460 }
461
462 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
463 #[derive(Copy, Clone)]
464 struct MaybeStorageLive;
465
466 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
467     type Domain = BitSet<mir::Local>;
468     const NAME: &'static str = "maybe_storage_live";
469
470     fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
471         // bottom = dead
472         BitSet::new_empty(body.local_decls.len())
473     }
474
475     fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain) {
476         for arg in body.args_iter() {
477             state.insert(arg);
478         }
479     }
480 }
481
482 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
483     type Idx = mir::Local;
484
485     fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
486         match stmt.kind {
487             mir::StatementKind::StorageLive(l) => trans.gen(l),
488             mir::StatementKind::StorageDead(l) => trans.kill(l),
489             _ => (),
490         }
491     }
492
493     fn terminator_effect(
494         &self,
495         _trans: &mut impl GenKill<Self::Idx>,
496         _terminator: &mir::Terminator<'tcx>,
497         _loc: mir::Location,
498     ) {
499     }
500
501     fn call_return_effect(
502         &self,
503         _trans: &mut impl GenKill<Self::Idx>,
504         _block: mir::BasicBlock,
505         _return_places: CallReturnPlaces<'_, 'tcx>,
506     ) {
507         // Nothing to do when a call returns successfully
508     }
509 }
510
511 /// Collects the possible borrowers of each local.
512 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
513 /// possible borrowers of `a`.
514 struct PossibleBorrowerVisitor<'a, 'tcx> {
515     possible_borrower: TransitiveRelation<mir::Local>,
516     body: &'a mir::Body<'tcx>,
517     cx: &'a LateContext<'tcx>,
518     possible_origin: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
519 }
520
521 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
522     fn new(
523         cx: &'a LateContext<'tcx>,
524         body: &'a mir::Body<'tcx>,
525         possible_origin: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
526     ) -> Self {
527         Self {
528             possible_borrower: TransitiveRelation::default(),
529             cx,
530             body,
531             possible_origin,
532         }
533     }
534
535     fn into_map(
536         self,
537         cx: &LateContext<'tcx>,
538         maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
539     ) -> PossibleBorrowerMap<'a, 'tcx> {
540         let mut map = FxHashMap::default();
541         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
542             if is_copy(cx, self.body.local_decls[row].ty) {
543                 continue;
544             }
545
546             let borrowers = self.possible_borrower.reachable_from(&row);
547             if !borrowers.is_empty() {
548                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
549                 for &c in borrowers {
550                     if c != mir::Local::from_usize(0) {
551                         bs.insert(c);
552                     }
553                 }
554
555                 if !bs.is_empty() {
556                     map.insert(row, bs);
557                 }
558             }
559         }
560
561         let bs = BitSet::new_empty(self.body.local_decls.len());
562         PossibleBorrowerMap {
563             map,
564             maybe_live,
565             bitset: (bs.clone(), bs),
566         }
567     }
568 }
569
570 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
571     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
572         let lhs = place.local;
573         match rvalue {
574             mir::Rvalue::Ref(_, _, borrowed) => {
575                 self.possible_borrower.add(borrowed.local, lhs);
576             },
577             other => {
578                 if ContainsRegion
579                     .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty)
580                     .is_continue()
581                 {
582                     return;
583                 }
584                 rvalue_locals(other, |rhs| {
585                     if lhs != rhs {
586                         self.possible_borrower.add(rhs, lhs);
587                     }
588                 });
589             },
590         }
591     }
592
593     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
594         if let mir::TerminatorKind::Call {
595             args,
596             destination: Some((mir::Place { local: dest, .. }, _)),
597             ..
598         } = &terminator.kind
599         {
600             // TODO add doc
601             // If the call returns something with lifetimes,
602             // let's conservatively assume the returned value contains lifetime of all the arguments.
603             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
604
605             let mut immutable_borrowers = vec![];
606             let mut mutable_borrowers = vec![];
607
608             for op in args {
609                 match op {
610                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
611                         if let ty::Ref(_, _, Mutability::Mut) = self.body.local_decls[p.local].ty.kind() {
612                             mutable_borrowers.push(p.local);
613                         } else {
614                             immutable_borrowers.push(p.local);
615                         }
616                     },
617                     mir::Operand::Constant(..) => (),
618                 }
619             }
620
621             let mut mutable_variables: Vec<mir::Local> = mutable_borrowers
622                 .iter()
623                 .filter_map(|r| self.possible_origin.get(r))
624                 .flat_map(HybridBitSet::iter)
625                 .collect();
626
627             if ContainsRegion.visit_ty(self.body.local_decls[*dest].ty).is_break() {
628                 mutable_variables.push(*dest);
629             }
630
631             for y in mutable_variables {
632                 for x in &immutable_borrowers {
633                     self.possible_borrower.add(*x, y);
634                 }
635                 for x in &mutable_borrowers {
636                     self.possible_borrower.add(*x, y);
637                 }
638             }
639         }
640     }
641 }
642
643 /// Collect possible borrowed for every `&mut` local.
644 /// For exampel, `_1 = &mut _2` generate _1: {_2,...}
645 /// Known Problems: not sure all borrowed are tracked
646 struct PossibleOriginVisitor<'a, 'tcx> {
647     possible_origin: TransitiveRelation<mir::Local>,
648     body: &'a mir::Body<'tcx>,
649 }
650
651 impl<'a, 'tcx> PossibleOriginVisitor<'a, 'tcx> {
652     fn new(body: &'a mir::Body<'tcx>) -> Self {
653         Self {
654             possible_origin: TransitiveRelation::default(),
655             body,
656         }
657     }
658
659     fn into_map(self, cx: &LateContext<'tcx>) -> FxHashMap<mir::Local, HybridBitSet<mir::Local>> {
660         let mut map = FxHashMap::default();
661         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
662             if is_copy(cx, self.body.local_decls[row].ty) {
663                 continue;
664             }
665
666             let borrowers = self.possible_origin.reachable_from(&row);
667             if !borrowers.is_empty() {
668                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
669                 for &c in borrowers {
670                     if c != mir::Local::from_usize(0) {
671                         bs.insert(c);
672                     }
673                 }
674
675                 if !bs.is_empty() {
676                     map.insert(row, bs);
677                 }
678             }
679         }
680         map
681     }
682 }
683
684 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleOriginVisitor<'a, 'tcx> {
685     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
686         let lhs = place.local;
687         match rvalue {
688             // Only consider `&mut`, which can modify origin place
689             mir::Rvalue::Ref(_, rustc_middle::mir::BorrowKind::Mut { .. }, borrowed) |
690             // _2: &mut _;
691             // _3 = move _2
692             mir::Rvalue::Use(mir::Operand::Move(borrowed))  |
693             // _3 = move _2 as &mut _;
694             mir::Rvalue::Cast(_, mir::Operand::Move(borrowed), _)
695                 => {
696                 self.possible_origin.add(lhs, borrowed.local);
697             },
698             _ => {},
699         }
700     }
701 }
702
703 struct ContainsRegion;
704
705 impl TypeVisitor<'_> for ContainsRegion {
706     type BreakTy = ();
707
708     fn visit_region(&mut self, _: ty::Region<'_>) -> ControlFlow<Self::BreakTy> {
709         ControlFlow::BREAK
710     }
711 }
712
713 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
714     use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
715
716     let mut visit_op = |op: &mir::Operand<'_>| match op {
717         mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
718         mir::Operand::Constant(..) => (),
719     };
720
721     match rvalue {
722         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
723         Aggregate(_, ops) => ops.iter().for_each(visit_op),
724         BinaryOp(_, box (lhs, rhs)) | CheckedBinaryOp(_, box (lhs, rhs)) => {
725             visit_op(lhs);
726             visit_op(rhs);
727         },
728         _ => (),
729     }
730 }
731
732 /// Result of `PossibleBorrowerVisitor`.
733 struct PossibleBorrowerMap<'a, 'tcx> {
734     /// Mapping `Local -> its possible borrowers`
735     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
736     maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
737     // Caches to avoid allocation of `BitSet` on every query
738     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
739 }
740
741 impl PossibleBorrowerMap<'_, '_> {
742     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
743     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
744         self.maybe_live.seek_after_primary_effect(at);
745
746         self.bitset.0.clear();
747         let maybe_live = &mut self.maybe_live;
748         if let Some(bitset) = self.map.get(&borrowed) {
749             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
750                 self.bitset.0.insert(b);
751             }
752         } else {
753             return false;
754         }
755
756         self.bitset.1.clear();
757         for b in borrowers {
758             self.bitset.1.insert(*b);
759         }
760
761         self.bitset.0 == self.bitset.1
762     }
763
764     fn local_is_alive_at(&mut self, local: mir::Local, at: mir::Location) -> bool {
765         self.maybe_live.seek_after_primary_effect(at);
766         self.maybe_live.contains(local)
767     }
768 }