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