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;
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::{
14 visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor as _},
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};
22 use std::convert::TryFrom;
23 use std::ops::ControlFlow;
25 macro_rules! unwrap_or_continue {
34 declare_clippy_lint! {
36 /// Checks for a redundant `clone()` (and its relatives) which clones an owned
37 /// value that is going to be dropped without further use.
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.
43 /// ### Known problems
44 /// False-negatives: analysis performed by this lint is conservative and limited.
48 /// # use std::path::Path;
49 /// # #[derive(Clone)]
52 /// # fn new() -> Self { Foo {} }
54 /// # fn call(x: Foo) {}
56 /// let x = Foo::new();
58 /// call(x.clone()); // this can just pass `x`
61 /// ["lorem", "ipsum"].join(" ").to_string();
63 /// Path::new("/a/b").join("c").to_path_buf();
65 #[clippy::version = "1.32.0"]
68 "`clone()` of an owned value that is going to be dropped immediately"
71 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
73 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
74 #[allow(clippy::too_many_lines)]
77 cx: &LateContext<'tcx>,
84 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
86 // Building MIR for `fn`s with unsatisfiable preds results in ICE.
87 if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
91 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
93 let possible_origin = {
94 let mut vis = PossibleOriginVisitor::new(mir);
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);
106 vis.into_map(cx, maybe_storage_live_result)
109 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
110 let terminator = bbdata.terminator();
112 if terminator.source_info.span.from_expansion() {
117 if terminator.successors().any(|s| *s == bb) {
121 let (fn_def_id, arg, arg_ty, clone_ret) =
122 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
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));
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));
133 if !from_borrow && !from_deref {
137 if let ty::Adt(def, _) = arg_ty.kind() {
138 if def.is_manually_drop() {
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));
146 let loc = mir::Location {
148 statement_index: bbdata.statements.len(),
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.
156 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
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.
165 let ps = &mir.predecessors()[bb];
169 let pred_terminator = mir[ps[0]].terminator();
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);
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);
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 {
190 statement_index: mir.basic_blocks()[bb].statements.len(),
193 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
194 // at the last statement:
197 // pred_arg = &local;
198 // cloned = deref(pred_arg);
200 // StorageDead(pred_arg);
201 // res = to_path_buf(cloned);
203 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
207 (local, deref_clone_ret)
210 let clone_usage = if local == ret_local {
213 cloned_consume_or_mutate_loc: None,
214 clone_consumed_or_mutated: true,
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
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) {
230 let span = terminator.source_info.span;
231 let scope = terminator.source_info.scope;
232 let node = mir.source_scopes[scope]
235 .assert_crate_local()
239 if let Some(snip) = snippet_opt(cx, span);
240 if let Some(dot) = snip.rfind('.');
242 let sugg_span = span.with_lo(
243 span.lo() + BytePos(u32::try_from(dot).unwrap())
245 let mut app = Applicability::MaybeIncorrect;
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;
255 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
256 diag.span_suggestion(
262 if clone_usage.cloned_used {
265 "cloned value is neither consumed nor mutated",
269 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
270 "this value is dropped without further use",
275 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
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)> {
289 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
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);
296 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
303 type CannotMoveOut = bool;
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,
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 };
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))
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))
337 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
338 /// if it is already a `Local`.
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;
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;
356 let PlaceRef { local, mut projection } = place.as_ref();
357 while let [base @ .., elem] = projection {
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);
366 (local, deref || field || slice)
371 /// Whether the cloned value is used after the clone.
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,
378 fn visit_clone_usage(cloned: mir::Local, clone: mir::Local, mir: &mir::Body<'_>, bb: mir::BasicBlock) -> CloneUsage {
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 });
391 self.visit_terminator(
395 statement_index: statements.len(),
400 fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, loc: mir::Location) {
401 let local = place.local;
403 if local == self.cloned
406 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_)
409 self.result.cloned_used = true;
410 self.result.cloned_consume_or_mutate_loc = self.result.cloned_consume_or_mutate_loc.or_else(|| {
413 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
414 | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
418 } else if local == self.clone {
420 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
421 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
422 self.result.clone_consumed_or_mutated = true;
430 let init = CloneUsage {
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,
437 traversal::ReversePostorder::new(mir, bb)
439 .fold(init, |usage, (tbb, tdata)| {
441 if (usage.cloned_used && usage.clone_consumed_or_mutated) ||
443 tdata.terminator().successors().any(|s| *s == bb)
447 clone_consumed_or_mutated: true,
457 v.visit_basic_block_data(tbb, tdata);
462 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
463 #[derive(Copy, Clone)]
464 struct MaybeStorageLive;
466 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
467 type Domain = BitSet<mir::Local>;
468 const NAME: &'static str = "maybe_storage_live";
470 fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
472 BitSet::new_empty(body.local_decls.len())
475 fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain) {
476 for arg in body.args_iter() {
482 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
483 type Idx = mir::Local;
485 fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
487 mir::StatementKind::StorageLive(l) => trans.gen(l),
488 mir::StatementKind::StorageDead(l) => trans.kill(l),
493 fn terminator_effect(
495 _trans: &mut impl GenKill<Self::Idx>,
496 _terminator: &mir::Terminator<'tcx>,
501 fn call_return_effect(
503 _trans: &mut impl GenKill<Self::Idx>,
504 _block: mir::BasicBlock,
505 _return_places: CallReturnPlaces<'_, 'tcx>,
507 // Nothing to do when a call returns successfully
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,
516 body: &'a mir::Body<'tcx>,
517 cx: &'a LateContext<'tcx>,
518 possible_origin: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
521 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
523 cx: &'a LateContext<'tcx>,
524 body: &'a mir::Body<'tcx>,
525 possible_origin: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
528 possible_borrower: TransitiveRelation::default(),
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) {
546 let mut borrowers = self.possible_borrower.reachable_from(row, self.body.local_decls.len());
547 borrowers.remove(mir::Local::from_usize(0));
548 if !borrowers.is_empty() {
549 map.insert(row, borrowers);
553 let bs = BitSet::new_empty(self.body.local_decls.len());
554 PossibleBorrowerMap {
557 bitset: (bs.clone(), bs),
562 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
563 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
564 let lhs = place.local;
566 mir::Rvalue::Ref(_, _, borrowed) => {
567 self.possible_borrower.add(borrowed.local, lhs);
571 .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty)
576 rvalue_locals(other, |rhs| {
578 self.possible_borrower.add(rhs, lhs);
585 fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
586 if let mir::TerminatorKind::Call {
588 destination: Some((mir::Place { local: dest, .. }, _)),
593 // If the call returns something with lifetimes,
594 // let's conservatively assume the returned value contains lifetime of all the arguments.
595 // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
597 let mut immutable_borrowers = vec![];
598 let mut mutable_borrowers = vec![];
602 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
603 if let ty::Ref(_, _, Mutability::Mut) = self.body.local_decls[p.local].ty.kind() {
604 mutable_borrowers.push(p.local);
606 immutable_borrowers.push(p.local);
609 mir::Operand::Constant(..) => (),
613 let mut mutable_variables: Vec<mir::Local> = mutable_borrowers
615 .filter_map(|r| self.possible_origin.get(r))
616 .flat_map(HybridBitSet::iter)
619 if ContainsRegion.visit_ty(self.body.local_decls[*dest].ty).is_break() {
620 mutable_variables.push(*dest);
623 for y in mutable_variables {
624 for x in &immutable_borrowers {
625 self.possible_borrower.add(*x, y);
627 for x in &mutable_borrowers {
628 self.possible_borrower.add(*x, y);
635 /// Collect possible borrowed for every `&mut` local.
636 /// For exampel, `_1 = &mut _2` generate _1: {_2,...}
637 /// Known Problems: not sure all borrowed are tracked
638 struct PossibleOriginVisitor<'a, 'tcx> {
639 possible_origin: TransitiveRelation,
640 body: &'a mir::Body<'tcx>,
643 impl<'a, 'tcx> PossibleOriginVisitor<'a, 'tcx> {
644 fn new(body: &'a mir::Body<'tcx>) -> Self {
646 possible_origin: TransitiveRelation::default(),
651 fn into_map(self, cx: &LateContext<'tcx>) -> FxHashMap<mir::Local, HybridBitSet<mir::Local>> {
652 let mut map = FxHashMap::default();
653 for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
654 if is_copy(cx, self.body.local_decls[row].ty) {
658 let mut borrowers = self.possible_origin.reachable_from(row, self.body.local_decls.len());
659 borrowers.remove(mir::Local::from_usize(0));
660 if !borrowers.is_empty() {
661 map.insert(row, borrowers);
668 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleOriginVisitor<'a, 'tcx> {
669 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
670 let lhs = place.local;
672 // Only consider `&mut`, which can modify origin place
673 mir::Rvalue::Ref(_, rustc_middle::mir::BorrowKind::Mut { .. }, borrowed) |
676 mir::Rvalue::Use(mir::Operand::Move(borrowed)) |
677 // _3 = move _2 as &mut _;
678 mir::Rvalue::Cast(_, mir::Operand::Move(borrowed), _)
680 self.possible_origin.add(lhs, borrowed.local);
687 struct ContainsRegion;
689 impl TypeVisitor<'_> for ContainsRegion {
692 fn visit_region(&mut self, _: ty::Region<'_>) -> ControlFlow<Self::BreakTy> {
697 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
698 use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
700 let mut visit_op = |op: &mir::Operand<'_>| match op {
701 mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
702 mir::Operand::Constant(..) => (),
706 Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
707 Aggregate(_, ops) => ops.iter().for_each(visit_op),
708 BinaryOp(_, box (lhs, rhs)) | CheckedBinaryOp(_, box (lhs, rhs)) => {
716 /// Result of `PossibleBorrowerVisitor`.
717 struct PossibleBorrowerMap<'a, 'tcx> {
718 /// Mapping `Local -> its possible borrowers`
719 map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
720 maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
721 // Caches to avoid allocation of `BitSet` on every query
722 bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
725 impl PossibleBorrowerMap<'_, '_> {
726 /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
727 fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
728 self.maybe_live.seek_after_primary_effect(at);
730 self.bitset.0.clear();
731 let maybe_live = &mut self.maybe_live;
732 if let Some(bitset) = self.map.get(&borrowed) {
733 for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
734 self.bitset.0.insert(b);
740 self.bitset.1.clear();
742 self.bitset.1.insert(*b);
745 self.bitset.0 == self.bitset.1
748 fn local_is_alive_at(&mut self, local: mir::Local, at: mir::Location) -> bool {
749 self.maybe_live.seek_after_primary_effect(at);
750 self.maybe_live.contains(local)
755 struct TransitiveRelation {
756 relations: FxHashMap<mir::Local, Vec<mir::Local>>,
758 impl TransitiveRelation {
759 fn add(&mut self, a: mir::Local, b: mir::Local) {
760 self.relations.entry(a).or_default().push(b);
763 fn reachable_from(&self, a: mir::Local, domain_size: usize) -> HybridBitSet<mir::Local> {
764 let mut seen = HybridBitSet::new_empty(domain_size);
765 let mut stack = vec![a];
766 while let Some(u) = stack.pop() {
767 if let Some(edges) = self.relations.get(&u) {