]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_clone.rs
Auto merge of #6325 - flip1995:rustup, r=flip1995
[rust.git] / clippy_lints / src / redundant_clone.rs
1 use crate::utils::{
2     fn_has_unsatisfiable_preds, has_drop, is_copy, is_type_diagnostic_item, match_def_path, match_type, paths,
3     snippet_opt, span_lint_hir, span_lint_hir_and_then, walk_ptrs_ty_depth,
4 };
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(ref def, _) = arg_ty.kind() {
130                 if match_def_path(cx, def.did, &paths::MEM_MANUALLY_DROP) {
131                     continue;
132                 }
133             }
134
135             // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
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 match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
169                     if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
170                         || match_type(cx, pred_arg_ty, &paths::OS_STRING);
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 is_temp = mir.local_kind(ret_local) == mir::LocalKind::Temp;
203
204             // 1. `local` can be moved out if it is not used later.
205             // 2. If `ret_local` is a temporary and is neither consumed nor mutated, we can remove this `clone`
206             // call anyway.
207             let (used, consumed_or_mutated) = traversal::ReversePostorder::new(&mir, bb).skip(1).fold(
208                 (false, !is_temp),
209                 |(used, consumed), (tbb, tdata)| {
210                     // Short-circuit
211                     if (used && consumed) ||
212                         // Give up on loops
213                         tdata.terminator().successors().any(|s| *s == bb)
214                     {
215                         return (true, true);
216                     }
217
218                     let mut vis = LocalUseVisitor {
219                         used: (local, false),
220                         consumed_or_mutated: (ret_local, false),
221                     };
222                     vis.visit_basic_block_data(tbb, tdata);
223                     (used || vis.used.1, consumed || vis.consumed_or_mutated.1)
224                 },
225             );
226
227             if !used || !consumed_or_mutated {
228                 let span = terminator.source_info.span;
229                 let scope = terminator.source_info.scope;
230                 let node = mir.source_scopes[scope]
231                     .local_data
232                     .as_ref()
233                     .assert_crate_local()
234                     .lint_root;
235
236                 if_chain! {
237                     if let Some(snip) = snippet_opt(cx, span);
238                     if let Some(dot) = snip.rfind('.');
239                     then {
240                         let sugg_span = span.with_lo(
241                             span.lo() + BytePos(u32::try_from(dot).unwrap())
242                         );
243                         let mut app = Applicability::MaybeIncorrect;
244
245                         let call_snip = &snip[dot + 1..];
246                         // Machine applicable when `call_snip` looks like `foobar()`
247                         if let Some(call_snip) = call_snip.strip_suffix("()").map(str::trim) {
248                             if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
249                                 app = Applicability::MachineApplicable;
250                             }
251                         }
252
253                         span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
254                             diag.span_suggestion(
255                                 sugg_span,
256                                 "remove this",
257                                 String::new(),
258                                 app,
259                             );
260                             if used {
261                                 diag.span_note(
262                                     span,
263                                     "cloned value is neither consumed nor mutated",
264                                 );
265                             } else {
266                                 diag.span_note(
267                                     span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
268                                     "this value is dropped without further use",
269                                 );
270                             }
271                         });
272                     } else {
273                         span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
274                     }
275                 }
276             }
277         }
278     }
279 }
280
281 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
282 fn is_call_with_ref_arg<'tcx>(
283     cx: &LateContext<'tcx>,
284     mir: &'tcx mir::Body<'tcx>,
285     kind: &'tcx mir::TerminatorKind<'tcx>,
286 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
287     if_chain! {
288         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
289         if args.len() == 1;
290         if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
291         if let ty::FnDef(def_id, _) = *func.ty(&*mir, cx.tcx).kind();
292         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
293         if !is_copy(cx, inner_ty);
294         then {
295             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
296         } else {
297             None
298         }
299     }
300 }
301
302 type CannotMoveOut = bool;
303
304 /// Finds the first `to = (&)from`, and returns
305 /// ``Some((from, whether `from` cannot be moved out))``.
306 fn find_stmt_assigns_to<'tcx>(
307     cx: &LateContext<'tcx>,
308     mir: &mir::Body<'tcx>,
309     to_local: mir::Local,
310     by_ref: bool,
311     bb: mir::BasicBlock,
312 ) -> Option<(mir::Local, CannotMoveOut)> {
313     let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
314         if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
315             return if *local == to_local { Some(v) } else { None };
316         }
317
318         None
319     })?;
320
321     match (by_ref, &*rvalue) {
322         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
323             base_local_and_movability(cx, mir, *place)
324         },
325         (false, mir::Rvalue::Ref(_, _, place)) => {
326             if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
327                 base_local_and_movability(cx, mir, *place)
328             } else {
329                 None
330             }
331         },
332         _ => None,
333     }
334 }
335
336 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
337 /// if it is already a `Local`.
338 ///
339 /// Also reports whether given `place` cannot be moved out.
340 fn base_local_and_movability<'tcx>(
341     cx: &LateContext<'tcx>,
342     mir: &mir::Body<'tcx>,
343     place: mir::Place<'tcx>,
344 ) -> Option<(mir::Local, CannotMoveOut)> {
345     use rustc_middle::mir::PlaceRef;
346
347     // Dereference. You cannot move things out from a borrowed value.
348     let mut deref = false;
349     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
350     let mut field = false;
351     // If projection is a slice index then clone can be removed only if the
352     // underlying type implements Copy
353     let mut slice = false;
354
355     let PlaceRef { local, mut projection } = place.as_ref();
356     while let [base @ .., elem] = projection {
357         projection = base;
358         deref |= matches!(elem, mir::ProjectionElem::Deref);
359         field |= matches!(elem, mir::ProjectionElem::Field(..))
360             && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
361         slice |= matches!(elem, mir::ProjectionElem::Index(..))
362             && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
363     }
364
365     Some((local, deref || field || slice))
366 }
367
368 struct LocalUseVisitor {
369     used: (mir::Local, bool),
370     consumed_or_mutated: (mir::Local, bool),
371 }
372
373 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
374     fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
375         let statements = &data.statements;
376         for (statement_index, statement) in statements.iter().enumerate() {
377             self.visit_statement(statement, mir::Location { block, statement_index });
378         }
379
380         self.visit_terminator(
381             data.terminator(),
382             mir::Location {
383                 block,
384                 statement_index: statements.len(),
385             },
386         );
387     }
388
389     fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, _: mir::Location) {
390         let local = place.local;
391
392         if local == self.used.0
393             && !matches!(ctx, PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_))
394         {
395             self.used.1 = true;
396         }
397
398         if local == self.consumed_or_mutated.0 {
399             match ctx {
400                 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
401                 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
402                     self.consumed_or_mutated.1 = true;
403                 },
404                 _ => {},
405             }
406         }
407     }
408 }
409
410 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
411 #[derive(Copy, Clone)]
412 struct MaybeStorageLive;
413
414 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
415     type Domain = BitSet<mir::Local>;
416     const NAME: &'static str = "maybe_storage_live";
417
418     fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
419         // bottom = dead
420         BitSet::new_empty(body.local_decls.len())
421     }
422
423     fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain) {
424         for arg in body.args_iter() {
425             state.insert(arg);
426         }
427     }
428 }
429
430 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
431     type Idx = mir::Local;
432
433     fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
434         match stmt.kind {
435             mir::StatementKind::StorageLive(l) => trans.gen(l),
436             mir::StatementKind::StorageDead(l) => trans.kill(l),
437             _ => (),
438         }
439     }
440
441     fn terminator_effect(
442         &self,
443         _trans: &mut impl GenKill<Self::Idx>,
444         _terminator: &mir::Terminator<'tcx>,
445         _loc: mir::Location,
446     ) {
447     }
448
449     fn call_return_effect(
450         &self,
451         _in_out: &mut impl GenKill<Self::Idx>,
452         _block: mir::BasicBlock,
453         _func: &mir::Operand<'tcx>,
454         _args: &[mir::Operand<'tcx>],
455         _return_place: mir::Place<'tcx>,
456     ) {
457         // Nothing to do when a call returns successfully
458     }
459 }
460
461 /// Collects the possible borrowers of each local.
462 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
463 /// possible borrowers of `a`.
464 struct PossibleBorrowerVisitor<'a, 'tcx> {
465     possible_borrower: TransitiveRelation<mir::Local>,
466     body: &'a mir::Body<'tcx>,
467     cx: &'a LateContext<'tcx>,
468 }
469
470 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
471     fn new(cx: &'a LateContext<'tcx>, body: &'a mir::Body<'tcx>) -> Self {
472         Self {
473             possible_borrower: TransitiveRelation::default(),
474             cx,
475             body,
476         }
477     }
478
479     fn into_map(
480         self,
481         cx: &LateContext<'tcx>,
482         maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
483     ) -> PossibleBorrowerMap<'a, 'tcx> {
484         let mut map = FxHashMap::default();
485         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
486             if is_copy(cx, self.body.local_decls[row].ty) {
487                 continue;
488             }
489
490             let borrowers = self.possible_borrower.reachable_from(&row);
491             if !borrowers.is_empty() {
492                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
493                 for &c in borrowers {
494                     if c != mir::Local::from_usize(0) {
495                         bs.insert(c);
496                     }
497                 }
498
499                 if !bs.is_empty() {
500                     map.insert(row, bs);
501                 }
502             }
503         }
504
505         let bs = BitSet::new_empty(self.body.local_decls.len());
506         PossibleBorrowerMap {
507             map,
508             maybe_live,
509             bitset: (bs.clone(), bs),
510         }
511     }
512 }
513
514 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
515     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
516         let lhs = place.local;
517         match rvalue {
518             mir::Rvalue::Ref(_, _, borrowed) => {
519                 self.possible_borrower.add(borrowed.local, lhs);
520             },
521             other => {
522                 if ContainsRegion
523                     .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty)
524                     .is_continue()
525                 {
526                     return;
527                 }
528                 rvalue_locals(other, |rhs| {
529                     if lhs != rhs {
530                         self.possible_borrower.add(rhs, lhs);
531                     }
532                 });
533             },
534         }
535     }
536
537     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
538         if let mir::TerminatorKind::Call {
539             args,
540             destination: Some((mir::Place { local: dest, .. }, _)),
541             ..
542         } = &terminator.kind
543         {
544             // If the call returns something with lifetimes,
545             // let's conservatively assume the returned value contains lifetime of all the arguments.
546             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
547             if ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty).is_continue() {
548                 return;
549             }
550
551             for op in args {
552                 match op {
553                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
554                         self.possible_borrower.add(p.local, *dest);
555                     },
556                     _ => (),
557                 }
558             }
559         }
560     }
561 }
562
563 struct ContainsRegion;
564
565 impl TypeVisitor<'_> for ContainsRegion {
566     fn visit_region(&mut self, _: ty::Region<'_>) -> ControlFlow<()> {
567         ControlFlow::BREAK
568     }
569 }
570
571 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
572     use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
573
574     let mut visit_op = |op: &mir::Operand<'_>| match op {
575         mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
576         _ => (),
577     };
578
579     match rvalue {
580         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
581         Aggregate(_, ops) => ops.iter().for_each(visit_op),
582         BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
583             visit_op(lhs);
584             visit_op(rhs);
585         },
586         _ => (),
587     }
588 }
589
590 /// Result of `PossibleBorrowerVisitor`.
591 struct PossibleBorrowerMap<'a, 'tcx> {
592     /// Mapping `Local -> its possible borrowers`
593     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
594     maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
595     // Caches to avoid allocation of `BitSet` on every query
596     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
597 }
598
599 impl PossibleBorrowerMap<'_, '_> {
600     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
601     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
602         self.maybe_live.seek_after_primary_effect(at);
603
604         self.bitset.0.clear();
605         let maybe_live = &mut self.maybe_live;
606         if let Some(bitset) = self.map.get(&borrowed) {
607             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
608                 self.bitset.0.insert(b);
609             }
610         } else {
611             return false;
612         }
613
614         self.bitset.1.clear();
615         for b in borrowers {
616             self.bitset.1.insert(*b);
617         }
618
619         self.bitset.0 == self.bitset.1
620     }
621 }