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,
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::{
14 visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor as _},
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};
21 use std::convert::TryFrom;
22 use std::ops::ControlFlow;
24 macro_rules! unwrap_or_continue {
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.
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.
40 /// **Known problems:**
42 /// False-negatives: analysis performed by this lint is conservative and limited.
46 /// # use std::path::Path;
47 /// # #[derive(Clone)]
50 /// # fn new() -> Self { Foo {} }
52 /// # fn call(x: Foo) {}
54 /// let x = Foo::new();
56 /// call(x.clone()); // this can just pass `x`
59 /// ["lorem", "ipsum"].join(" ").to_string();
61 /// Path::new("/a/b").join("c").to_path_buf();
65 "`clone()` of an owned value that is going to be dropped immediately"
68 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
70 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
71 #[allow(clippy::too_many_lines)]
74 cx: &LateContext<'tcx>,
81 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
83 // Building MIR for `fn`s with unsatisfiable preds results in ICE.
84 if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
88 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
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);
98 vis.into_map(cx, maybe_storage_live_result)
101 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
102 let terminator = bbdata.terminator();
104 if terminator.source_info.span.from_expansion() {
109 if terminator.successors().any(|s| *s == bb) {
113 let (fn_def_id, arg, arg_ty, clone_ret) =
114 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
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));
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));
125 if !from_borrow && !from_deref {
129 if let ty::Adt(ref def, _) = arg_ty.kind() {
130 if match_def_path(cx, def.did, &paths::MEM_MANUALLY_DROP) {
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));
138 let loc = mir::Location {
140 statement_index: bbdata.statements.len(),
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.
148 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
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.
157 let ps = &mir.predecessors()[bb];
161 let pred_terminator = mir[ps[0]].terminator();
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);
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);
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 {
182 statement_index: mir.basic_blocks()[bb].statements.len(),
185 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
186 // at the last statement:
189 // pred_arg = &local;
190 // cloned = deref(pred_arg);
192 // StorageDead(pred_arg);
193 // res = to_path_buf(cloned);
195 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
199 (local, deref_clone_ret)
202 let is_temp = mir.local_kind(ret_local) == mir::LocalKind::Temp;
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`
207 let (used, consumed_or_mutated) = traversal::ReversePostorder::new(&mir, bb).skip(1).fold(
209 |(used, consumed), (tbb, tdata)| {
211 if (used && consumed) ||
213 tdata.terminator().successors().any(|s| *s == bb)
218 let mut vis = LocalUseVisitor {
219 used: (local, false),
220 consumed_or_mutated: (ret_local, false),
222 vis.visit_basic_block_data(tbb, tdata);
223 (used || vis.used.1, consumed || vis.consumed_or_mutated.1)
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]
233 .assert_crate_local()
237 if let Some(snip) = snippet_opt(cx, span);
238 if let Some(dot) = snip.rfind('.');
240 let sugg_span = span.with_lo(
241 span.lo() + BytePos(u32::try_from(dot).unwrap())
243 let mut app = Applicability::MaybeIncorrect;
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;
253 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
254 diag.span_suggestion(
263 "cloned value is neither consumed nor mutated",
267 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
268 "this value is dropped without further use",
273 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
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)> {
288 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
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);
295 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
302 type CannotMoveOut = bool;
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,
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 };
321 match (by_ref, &*rvalue) {
322 (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
323 Some(base_local_and_movability(cx, mir, *place))
325 (false, mir::Rvalue::Ref(_, _, place)) => {
326 if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
327 Some(base_local_and_movability(cx, mir, *place))
336 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
337 /// if it is already a `Local`.
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 ) -> (mir::Local, CannotMoveOut) {
345 use rustc_middle::mir::PlaceRef;
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;
355 let PlaceRef { local, mut projection } = place.as_ref();
356 while let [base @ .., elem] = projection {
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);
365 (local, deref || field || slice)
368 struct LocalUseVisitor {
369 used: (mir::Local, bool),
370 consumed_or_mutated: (mir::Local, bool),
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 });
380 self.visit_terminator(
384 statement_index: statements.len(),
389 fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, _: mir::Location) {
390 let local = place.local;
392 if local == self.used.0
395 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_)
401 if local == self.consumed_or_mutated.0 {
403 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
404 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
405 self.consumed_or_mutated.1 = true;
413 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
414 #[derive(Copy, Clone)]
415 struct MaybeStorageLive;
417 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
418 type Domain = BitSet<mir::Local>;
419 const NAME: &'static str = "maybe_storage_live";
421 fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
423 BitSet::new_empty(body.local_decls.len())
426 fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain) {
427 for arg in body.args_iter() {
433 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
434 type Idx = mir::Local;
436 fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
438 mir::StatementKind::StorageLive(l) => trans.gen(l),
439 mir::StatementKind::StorageDead(l) => trans.kill(l),
444 fn terminator_effect(
446 _trans: &mut impl GenKill<Self::Idx>,
447 _terminator: &mir::Terminator<'tcx>,
452 fn call_return_effect(
454 _in_out: &mut impl GenKill<Self::Idx>,
455 _block: mir::BasicBlock,
456 _func: &mir::Operand<'tcx>,
457 _args: &[mir::Operand<'tcx>],
458 _return_place: mir::Place<'tcx>,
460 // Nothing to do when a call returns successfully
464 /// Collects the possible borrowers of each local.
465 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
466 /// possible borrowers of `a`.
467 struct PossibleBorrowerVisitor<'a, 'tcx> {
468 possible_borrower: TransitiveRelation<mir::Local>,
469 body: &'a mir::Body<'tcx>,
470 cx: &'a LateContext<'tcx>,
473 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
474 fn new(cx: &'a LateContext<'tcx>, body: &'a mir::Body<'tcx>) -> Self {
476 possible_borrower: TransitiveRelation::default(),
484 cx: &LateContext<'tcx>,
485 maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
486 ) -> PossibleBorrowerMap<'a, 'tcx> {
487 let mut map = FxHashMap::default();
488 for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
489 if is_copy(cx, self.body.local_decls[row].ty) {
493 let borrowers = self.possible_borrower.reachable_from(&row);
494 if !borrowers.is_empty() {
495 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
496 for &c in borrowers {
497 if c != mir::Local::from_usize(0) {
508 let bs = BitSet::new_empty(self.body.local_decls.len());
509 PossibleBorrowerMap {
512 bitset: (bs.clone(), bs),
517 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
518 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
519 let lhs = place.local;
521 mir::Rvalue::Ref(_, _, borrowed) => {
522 self.possible_borrower.add(borrowed.local, lhs);
526 .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty)
531 rvalue_locals(other, |rhs| {
533 self.possible_borrower.add(rhs, lhs);
540 fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
541 if let mir::TerminatorKind::Call {
543 destination: Some((mir::Place { local: dest, .. }, _)),
547 // If the call returns something with lifetimes,
548 // let's conservatively assume the returned value contains lifetime of all the arguments.
549 // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
550 if ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty).is_continue() {
556 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
557 self.possible_borrower.add(p.local, *dest);
566 struct ContainsRegion;
568 impl TypeVisitor<'_> for ContainsRegion {
571 fn visit_region(&mut self, _: ty::Region<'_>) -> ControlFlow<Self::BreakTy> {
576 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
577 use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
579 let mut visit_op = |op: &mir::Operand<'_>| match op {
580 mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
585 Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
586 Aggregate(_, ops) => ops.iter().for_each(visit_op),
587 BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
595 /// Result of `PossibleBorrowerVisitor`.
596 struct PossibleBorrowerMap<'a, 'tcx> {
597 /// Mapping `Local -> its possible borrowers`
598 map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
599 maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
600 // Caches to avoid allocation of `BitSet` on every query
601 bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
604 impl PossibleBorrowerMap<'_, '_> {
605 /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
606 fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
607 self.maybe_live.seek_after_primary_effect(at);
609 self.bitset.0.clear();
610 let maybe_live = &mut self.maybe_live;
611 if let Some(bitset) = self.map.get(&borrowed) {
612 for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
613 self.bitset.0.insert(b);
619 self.bitset.1.clear();
621 self.bitset.1.insert(*b);
624 self.bitset.0 == self.bitset.1