]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_clone.rs
Merge remote-tracking branch 'upstream/rust-1.43.0' into backport_remerge
[rust.git] / clippy_lints / src / redundant_clone.rs
1 use crate::utils::{
2     fn_has_unsatisfiable_preds, has_drop, is_copy, match_def_path, match_type, paths, snippet_opt, span_lint_hir,
3     span_lint_hir_and_then, walk_ptrs_ty_depth,
4 };
5 use if_chain::if_chain;
6 use matches::matches;
7 use rustc::mir::{
8     self, traversal,
9     visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor as _},
10 };
11 use rustc::ty::{self, fold::TypeVisitor, Ty};
12 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
13 use rustc_errors::Applicability;
14 use rustc_hir::intravisit::FnKind;
15 use rustc_hir::{def_id, Body, FnDecl, HirId};
16 use rustc_index::bit_set::{BitSet, HybridBitSet};
17 use rustc_lint::{LateContext, LateLintPass};
18 use rustc_mir::dataflow::generic::{Analysis, AnalysisDomain, GenKill, GenKillAnalysis, ResultsCursor};
19 use rustc_mir::dataflow::BottomValue;
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::source_map::{BytePos, Span};
22 use std::convert::TryFrom;
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<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
71     #[allow(clippy::too_many_lines)]
72     fn check_fn(
73         &mut self,
74         cx: &LateContext<'a, '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) {
85             return;
86         }
87
88         let mir = cx.tcx.optimized_mir(def_id);
89         let mir_read_only = mir.unwrap_read_only();
90
91         let maybe_storage_live_result = MaybeStorageLive
92             .into_engine(cx.tcx, mir, def_id)
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_read_only);
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) && match_type(cx, arg_ty, &paths::STRING));
119
120             let from_deref = !from_borrow
121                 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
122                     || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
123
124             if !from_borrow && !from_deref {
125                 continue;
126             }
127
128             // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
129             let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
130
131             let loc = mir::Location {
132                 block: bb,
133                 statement_index: bbdata.statements.len(),
134             };
135
136             // `Local` to be cloned, and a local of `clone` call's destination
137             let (local, ret_local) = if from_borrow {
138                 // `res = clone(arg)` can be turned into `res = move arg;`
139                 // if `arg` is the only borrow of `cloned` at this point.
140
141                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
142                     continue;
143                 }
144
145                 (cloned, clone_ret)
146             } else {
147                 // `arg` is a reference as it is `.deref()`ed in the previous block.
148                 // Look into the predecessor block and find out the source of deref.
149
150                 let ps = mir_read_only.predecessors_for(bb);
151                 if ps.len() != 1 {
152                     continue;
153                 }
154                 let pred_terminator = mir[ps[0]].terminator();
155
156                 // receiver of the `deref()` call
157                 let (pred_arg, deref_clone_ret) = if_chain! {
158                     if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, res)) =
159                         is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
160                     if res == cloned;
161                     if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
162                     if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
163                         || match_type(cx, pred_arg_ty, &paths::OS_STRING);
164                     then {
165                         (pred_arg, res)
166                     } else {
167                         continue;
168                     }
169                 };
170
171                 let (local, cannot_move_out) =
172                     unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
173                 let loc = mir::Location {
174                     block: bb,
175                     statement_index: mir.basic_blocks()[bb].statements.len(),
176                 };
177
178                 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
179                 // at the last statement:
180                 //
181                 // ```
182                 // pred_arg = &local;
183                 // cloned = deref(pred_arg);
184                 // arg = &cloned;
185                 // StorageDead(pred_arg);
186                 // res = to_path_buf(cloned);
187                 // ```
188                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
189                     continue;
190                 }
191
192                 (local, deref_clone_ret)
193             };
194
195             let is_temp = mir_read_only.local_kind(ret_local) == mir::LocalKind::Temp;
196
197             // 1. `local` can be moved out if it is not used later.
198             // 2. If `ret_local` is a temporary and is neither consumed nor mutated, we can remove this `clone`
199             // call anyway.
200             let (used, consumed_or_mutated) = traversal::ReversePostorder::new(&mir, bb).skip(1).fold(
201                 (false, !is_temp),
202                 |(used, consumed), (tbb, tdata)| {
203                     // Short-circuit
204                     if (used && consumed) ||
205                         // Give up on loops
206                         tdata.terminator().successors().any(|s| *s == bb)
207                     {
208                         return (true, true);
209                     }
210
211                     let mut vis = LocalUseVisitor {
212                         used: (local, false),
213                         consumed_or_mutated: (ret_local, false),
214                     };
215                     vis.visit_basic_block_data(tbb, tdata);
216                     (used || vis.used.1, consumed || vis.consumed_or_mutated.1)
217                 },
218             );
219
220             if !used || !consumed_or_mutated {
221                 let span = terminator.source_info.span;
222                 let scope = terminator.source_info.scope;
223                 let node = mir.source_scopes[scope]
224                     .local_data
225                     .as_ref()
226                     .assert_crate_local()
227                     .lint_root;
228
229                 if_chain! {
230                     if let Some(snip) = snippet_opt(cx, span);
231                     if let Some(dot) = snip.rfind('.');
232                     then {
233                         let sugg_span = span.with_lo(
234                             span.lo() + BytePos(u32::try_from(dot).unwrap())
235                         );
236                         let mut app = Applicability::MaybeIncorrect;
237
238                         let mut call_snip = &snip[dot + 1..];
239                         // Machine applicable when `call_snip` looks like `foobar()`
240                         if call_snip.ends_with("()") {
241                             call_snip = call_snip[..call_snip.len()-2].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", |db| {
248                             db.span_suggestion(
249                                 sugg_span,
250                                 "remove this",
251                                 String::new(),
252                                 app,
253                             );
254                             if used {
255                                 db.span_note(
256                                     span,
257                                     "cloned value is neither consumed nor mutated",
258                                 );
259                             } else {
260                                 db.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
275 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
276 fn is_call_with_ref_arg<'tcx>(
277     cx: &LateContext<'_, 'tcx>,
278     mir: &'tcx mir::Body<'tcx>,
279     kind: &'tcx mir::TerminatorKind<'tcx>,
280 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
281     if_chain! {
282         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
283         if args.len() == 1;
284         if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
285         if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).kind;
286         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
287         if !is_copy(cx, inner_ty);
288         then {
289             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
290         } else {
291             None
292         }
293     }
294 }
295
296 type CannotMoveOut = bool;
297
298 /// Finds the first `to = (&)from`, and returns
299 /// ``Some((from, whether `from` cannot be moved out))``.
300 fn find_stmt_assigns_to<'tcx>(
301     cx: &LateContext<'_, 'tcx>,
302     mir: &mir::Body<'tcx>,
303     to_local: mir::Local,
304     by_ref: bool,
305     bb: mir::BasicBlock,
306 ) -> Option<(mir::Local, CannotMoveOut)> {
307     let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
308         if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
309             return if *local == to_local { Some(v) } else { None };
310         }
311
312         None
313     })?;
314
315     match (by_ref, &*rvalue) {
316         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
317             base_local_and_movability(cx, mir, *place)
318         },
319         (false, mir::Rvalue::Ref(_, _, place)) => {
320             if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
321                 base_local_and_movability(cx, mir, *place)
322             } else {
323                 None
324             }
325         },
326         _ => None,
327     }
328 }
329
330 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
331 /// if it is already a `Local`.
332 ///
333 /// Also reports whether given `place` cannot be moved out.
334 fn base_local_and_movability<'tcx>(
335     cx: &LateContext<'_, 'tcx>,
336     mir: &mir::Body<'tcx>,
337     place: mir::Place<'tcx>,
338 ) -> Option<(mir::Local, CannotMoveOut)> {
339     use rustc::mir::PlaceRef;
340
341     // Dereference. You cannot move things out from a borrowed value.
342     let mut deref = false;
343     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
344     let mut field = false;
345
346     let PlaceRef { local, mut projection } = place.as_ref();
347     while let [base @ .., elem] = projection {
348         projection = base;
349         deref |= matches!(elem, mir::ProjectionElem::Deref);
350         field |= matches!(elem, mir::ProjectionElem::Field(..))
351             && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
352     }
353
354     Some((local, deref || field))
355 }
356
357 struct LocalUseVisitor {
358     used: (mir::Local, bool),
359     consumed_or_mutated: (mir::Local, bool),
360 }
361
362 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
363     fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
364         let statements = &data.statements;
365         for (statement_index, statement) in statements.iter().enumerate() {
366             self.visit_statement(statement, mir::Location { block, statement_index });
367         }
368
369         self.visit_terminator(
370             data.terminator(),
371             mir::Location {
372                 block,
373                 statement_index: statements.len(),
374             },
375         );
376     }
377
378     fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, _: mir::Location) {
379         let local = place.local;
380
381         if local == self.used.0
382             && !matches!(ctx, PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_))
383         {
384             self.used.1 = true;
385         }
386
387         if local == self.consumed_or_mutated.0 {
388             match ctx {
389                 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
390                 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
391                     self.consumed_or_mutated.1 = true;
392                 },
393                 _ => {},
394             }
395         }
396     }
397 }
398
399 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
400 #[derive(Copy, Clone)]
401 struct MaybeStorageLive;
402
403 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
404     type Idx = mir::Local;
405     const NAME: &'static str = "maybe_storage_live";
406
407     fn bits_per_block(&self, body: &mir::Body<'tcx>) -> usize {
408         body.local_decls.len()
409     }
410
411     fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut BitSet<Self::Idx>) {
412         for arg in body.args_iter() {
413             state.insert(arg);
414         }
415     }
416 }
417
418 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
419     fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
420         match stmt.kind {
421             mir::StatementKind::StorageLive(l) => trans.gen(l),
422             mir::StatementKind::StorageDead(l) => trans.kill(l),
423             _ => (),
424         }
425     }
426
427     fn terminator_effect(
428         &self,
429         _trans: &mut impl GenKill<Self::Idx>,
430         _terminator: &mir::Terminator<'tcx>,
431         _loc: mir::Location,
432     ) {
433     }
434
435     fn call_return_effect(
436         &self,
437         _in_out: &mut impl GenKill<Self::Idx>,
438         _block: mir::BasicBlock,
439         _func: &mir::Operand<'tcx>,
440         _args: &[mir::Operand<'tcx>],
441         _return_place: &mir::Place<'tcx>,
442     ) {
443         // Nothing to do when a call returns successfully
444     }
445 }
446
447 impl BottomValue for MaybeStorageLive {
448     /// bottom = dead
449     const BOTTOM_VALUE: bool = false;
450 }
451
452 /// Collects the possible borrowers of each local.
453 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
454 /// possible borrowers of `a`.
455 struct PossibleBorrowerVisitor<'a, 'tcx> {
456     possible_borrower: TransitiveRelation<mir::Local>,
457     body: &'a mir::Body<'tcx>,
458     cx: &'a LateContext<'a, 'tcx>,
459 }
460
461 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
462     fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self {
463         Self {
464             possible_borrower: TransitiveRelation::default(),
465             cx,
466             body,
467         }
468     }
469
470     fn into_map(
471         self,
472         cx: &LateContext<'a, 'tcx>,
473         maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
474     ) -> PossibleBorrowerMap<'a, 'tcx> {
475         let mut map = FxHashMap::default();
476         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
477             if is_copy(cx, self.body.local_decls[row].ty) {
478                 continue;
479             }
480
481             let borrowers = self.possible_borrower.reachable_from(&row);
482             if !borrowers.is_empty() {
483                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
484                 for &c in borrowers {
485                     if c != mir::Local::from_usize(0) {
486                         bs.insert(c);
487                     }
488                 }
489
490                 if !bs.is_empty() {
491                     map.insert(row, bs);
492                 }
493             }
494         }
495
496         let bs = BitSet::new_empty(self.body.local_decls.len());
497         PossibleBorrowerMap {
498             map,
499             maybe_live,
500             bitset: (bs.clone(), bs),
501         }
502     }
503 }
504
505 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
506     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
507         let lhs = place.local;
508         match rvalue {
509             mir::Rvalue::Ref(_, _, borrowed) => {
510                 self.possible_borrower.add(borrowed.local, lhs);
511             },
512             other => {
513                 if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
514                     return;
515                 }
516                 rvalue_locals(other, |rhs| {
517                     if lhs != rhs {
518                         self.possible_borrower.add(rhs, lhs);
519                     }
520                 });
521             },
522         }
523     }
524
525     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
526         if let mir::TerminatorKind::Call {
527             args,
528             destination: Some((mir::Place { local: dest, .. }, _)),
529             ..
530         } = &terminator.kind
531         {
532             // If the call returns something with lifetimes,
533             // let's conservatively assume the returned value contains lifetime of all the arguments.
534             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
535             if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
536                 return;
537             }
538
539             for op in args {
540                 match op {
541                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
542                         self.possible_borrower.add(p.local, *dest);
543                     },
544                     _ => (),
545                 }
546             }
547         }
548     }
549 }
550
551 struct ContainsRegion;
552
553 impl TypeVisitor<'_> for ContainsRegion {
554     fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
555         true
556     }
557 }
558
559 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
560     use rustc::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
561
562     let mut visit_op = |op: &mir::Operand<'_>| match op {
563         mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
564         _ => (),
565     };
566
567     match rvalue {
568         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
569         Aggregate(_, ops) => ops.iter().for_each(visit_op),
570         BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
571             visit_op(lhs);
572             visit_op(rhs);
573         },
574         _ => (),
575     }
576 }
577
578 /// Result of `PossibleBorrowerVisitor`.
579 struct PossibleBorrowerMap<'a, 'tcx> {
580     /// Mapping `Local -> its possible borrowers`
581     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
582     maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
583     // Caches to avoid allocation of `BitSet` on every query
584     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
585 }
586
587 impl PossibleBorrowerMap<'_, '_> {
588     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
589     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
590         self.maybe_live.seek_after(at);
591
592         self.bitset.0.clear();
593         let maybe_live = &mut self.maybe_live;
594         if let Some(bitset) = self.map.get(&borrowed) {
595             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
596                 self.bitset.0.insert(b);
597             }
598         } else {
599             return false;
600         }
601
602         self.bitset.1.clear();
603         for b in borrowers {
604             self.bitset.1.insert(*b);
605         }
606
607         self.bitset.0 == self.bitset.1
608     }
609 }