Skip to content

[clang-tidy] Add check performance-lost-std-move #139525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
1 change: 1 addition & 0 deletions clang-tools-extra/clang-tidy/performance/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ add_clang_library(clangTidyPerformanceModule STATIC
InefficientAlgorithmCheck.cpp
InefficientStringConcatenationCheck.cpp
InefficientVectorOperationCheck.cpp
LostStdMoveCheck.cpp
MoveConstArgCheck.cpp
MoveConstructorInitCheck.cpp
NoAutomaticMoveCheck.cpp
Expand Down
186 changes: 186 additions & 0 deletions clang-tools-extra/clang-tidy/performance/LostStdMoveCheck.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
//===--- LostStdMoveCheck.cpp - clang-tidy --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "LostStdMoveCheck.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang::tidy::performance {

template <typename Node>
void extractNodesByIdTo(ArrayRef<BoundNodes> Matches, StringRef ID,
llvm::SmallPtrSet<const Node *, 16> &Nodes) {
for (const BoundNodes &Match : Matches)
Nodes.insert(Match.getNodeAs<Node>(ID));
}

static llvm::SmallPtrSet<const DeclRefExpr *, 16>
allDeclRefExprsHonourLambda(const VarDecl &VarDecl, const Decl &Decl,
ASTContext &Context) {
auto Matches = match(
decl(forEachDescendant(
declRefExpr(to(varDecl(equalsNode(&VarDecl))),

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excessive newline. Same in other places.

unless(hasAncestor(lambdaExpr(hasAnyCapture(lambdaCapture(
capturesVar(varDecl(equalsNode(&VarDecl))))))))

)
.bind("declRef"))),
Decl, Context);
llvm::SmallPtrSet<const DeclRefExpr *, 16> DeclRefs;
extractNodesByIdTo(Matches, "declRef", DeclRefs);
return DeclRefs;
}

static const Expr *getLastVarUsage(const VarDecl &Var, const Decl &Func,
ASTContext &Context) {
auto Exprs = allDeclRefExprsHonourLambda(Var, Func, Context);

const Expr *LastExpr = nullptr;
for (const clang::DeclRefExpr *Expr : Exprs) {
if (!LastExpr)
LastExpr = Expr;

if (LastExpr->getBeginLoc() < Expr->getBeginLoc())
LastExpr = Expr;
}

return LastExpr;
}

AST_MATCHER(CXXRecordDecl, hasTrivialMoveConstructor) {
return Node.hasDefinition() && Node.hasTrivialMoveConstructor();
}

void LostStdMoveCheck::registerMatchers(MatchFinder *Finder) {
auto ReturnParent =
hasParent(expr(hasParent(cxxConstructExpr(hasParent(returnStmt())))));

auto OutermostExpr = expr(unless(hasParent(expr())));
auto LeafStatement = stmt(OutermostExpr);

Finder->addMatcher(
declRefExpr(
// not "return x;"
unless(ReturnParent),

unless(hasType(namedDecl(hasName("::std::string_view")))),

// non-trivial type
hasType(hasCanonicalType(hasDeclaration(cxxRecordDecl()))),

// non-trivial X(X&&)
unless(hasType(hasCanonicalType(
hasDeclaration(cxxRecordDecl(hasTrivialMoveConstructor()))))),

// Not in a cycle
unless(hasAncestor(forStmt())),

unless(hasAncestor(doStmt())),

unless(hasAncestor(whileStmt())),

// Not in a body of lambda
unless(hasAncestor(compoundStmt(hasAncestor(lambdaExpr())))),

// only non-X&
unless(hasDeclaration(
varDecl(hasType(qualType(lValueReferenceType()))))),

hasAncestor(LeafStatement.bind("leaf_statement")),

hasDeclaration(
varDecl(hasAncestor(functionDecl().bind("func"))).bind("decl")),

anyOf(

// f(x)
hasParent(expr(hasParent(cxxConstructExpr())).bind("use_parent")),

// f((x))
hasParent(parenExpr(hasParent(
expr(hasParent(cxxConstructExpr())).bind("use_parent"))))

)

)
.bind("use"),
this);
}

void LostStdMoveCheck::check(const MatchFinder::MatchResult &Result) {
const auto *MatchedDecl = Result.Nodes.getNodeAs<VarDecl>("decl");
const auto *MatchedFunc = Result.Nodes.getNodeAs<FunctionDecl>("func");
const auto *MatchedUse = Result.Nodes.getNodeAs<Expr>("use");
const auto *MatchedUseCall = Result.Nodes.getNodeAs<CallExpr>("use_parent");
const auto *MatchedLeafStatement =
Result.Nodes.getNodeAs<Stmt>("leaf_statement");

if (!MatchedDecl->hasLocalStorage())
return;

if (MatchedUseCall) {
return;
}

const Expr *LastUsage =
getLastVarUsage(*MatchedDecl, *MatchedFunc, *Result.Context);

if (LastUsage && LastUsage->getBeginLoc() > MatchedUse->getBeginLoc()) {
// "use" is not the last reference to x
return;
}

if (LastUsage &&
LastUsage->getSourceRange() != MatchedUse->getSourceRange()) {
return;
}

// Calculate X usage count in the statement
llvm::SmallPtrSet<const DeclRefExpr *, 16> DeclRefs;
ArrayRef<BoundNodes> Matches = match(
findAll(declRefExpr(

to(varDecl(equalsNode(MatchedDecl))),

unless(hasAncestor(lambdaExpr(hasAnyCapture(lambdaCapture(
capturesVar(varDecl(equalsNode(MatchedDecl))))))))

)
.bind("ref")),
*MatchedLeafStatement, *Result.Context);
extractNodesByIdTo(Matches, "ref", DeclRefs);
if (DeclRefs.size() > 1) {
// Unspecified order of evaluation, e.g. f(x, x)
return;
}

const SourceManager &Source = Result.Context->getSourceManager();
const auto Range =
CharSourceRange::getTokenRange(MatchedUse->getSourceRange());
const StringRef NeedleExprCode =
Lexer::getSourceText(Range, Source, Result.Context->getLangOpts());

if (NeedleExprCode == "=") {

diag(MatchedUse->getBeginLoc(), "could be std::move()")
<< FixItHint::CreateInsertion(MatchedUse->getBeginLoc(),
(MatchedDecl->getName() +
" = std::move(" +
MatchedDecl->getName() + "),")
.str());
} else {
diag(MatchedUse->getBeginLoc(), "could be std::move()")
<< FixItHint::CreateReplacement(
Range, ("std::move(" + NeedleExprCode + ")").str());
}
}

} // namespace clang::tidy::performance
35 changes: 35 additions & 0 deletions clang-tools-extra/clang-tidy/performance/LostStdMoveCheck.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//===--- LostStdMoveCheck.h - clang-tidy ------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_LOSTSTDMOVECHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_LOSTSTDMOVECHECK_H

#include "../ClangTidyCheck.h"

namespace clang::tidy::performance {

/// Warns if copy constructor is used instead of std::move() and suggests a fix.
/// It honours cycles, lambdas, and unspecified call order in compound
/// expressions.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/performance/lost-std-move.html
class LostStdMoveCheck : public ClangTidyCheck {
public:
LostStdMoveCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
return LangOpts.CPlusPlus11;
}
};

} // namespace clang::tidy::performance

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_LOSTSTDMOVECHECK_H
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "InefficientAlgorithmCheck.h"
#include "InefficientStringConcatenationCheck.h"
#include "InefficientVectorOperationCheck.h"
#include "LostStdMoveCheck.h"
#include "MoveConstArgCheck.h"
#include "MoveConstructorInitCheck.h"
#include "NoAutomaticMoveCheck.h"
Expand Down Expand Up @@ -49,6 +50,7 @@ class PerformanceModule : public ClangTidyModule {
"performance-inefficient-string-concatenation");
CheckFactories.registerCheck<InefficientVectorOperationCheck>(
"performance-inefficient-vector-operation");
CheckFactories.registerCheck<LostStdMoveCheck>("performance-lost-std-move");
CheckFactories.registerCheck<MoveConstArgCheck>(
"performance-move-const-arg");
CheckFactories.registerCheck<MoveConstructorInitCheck>(
Expand Down
6 changes: 6 additions & 0 deletions clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ New checks
Finds unintended character output from ``unsigned char`` and ``signed char``
to an ``ostream``.

- New :doc:`performance-lost-std-move
<clang-tidy/checks/performance/lost-std-move>` check.

Warns if copy constructor is used instead of std::move() and suggests a fix.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Warns if copy constructor is used instead of std::move() and suggests a fix.
Warns if copy constructor is used instead of ``std::move()`` and suggests a fix.

It honours cycles, lambdas, and unspecified call order in compound expressions.

- New :doc:`portability-avoid-pragma-once
<clang-tidy/checks/portability/avoid-pragma-once>` check.

Expand Down
1 change: 1 addition & 0 deletions clang-tools-extra/docs/clang-tidy/checks/list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ Clang-Tidy Checks
:doc:`performance-inefficient-algorithm <performance/inefficient-algorithm>`, "Yes"
:doc:`performance-inefficient-string-concatenation <performance/inefficient-string-concatenation>`,
:doc:`performance-inefficient-vector-operation <performance/inefficient-vector-operation>`, "Yes"
:doc:`performance-lost-std-move <performance/lost-std-move>`, "Yes"
:doc:`performance-move-const-arg <performance/move-const-arg>`, "Yes"
:doc:`performance-move-constructor-init <performance/move-constructor-init>`,
:doc:`performance-no-automatic-move <performance/no-automatic-move>`,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
.. title:: clang-tidy - performance-lost-std-move

performance-lost-std-move
=========================

Warns if copy constructor is used instead of std::move() and suggests a fix.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Warns if copy constructor is used instead of std::move() and suggests a fix.
Warns if copy constructor is used instead of ``std::move()`` and suggests a fix.

It honours cycles, lambdas, and unspecified call order in compound expressions.

.. code-block:: c++

void f(X);

void g(X x) {
f(x); // warning: Could be std::move() [performance-lost-std-move]
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Give examples when check will not warn


It finds the last local variable usage, and if it is a copy, emits a warning.
The check is based on pure AST matching and doesn't take into account any data flow information.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please follow 80-characters limit.

Thus, it doesn't catch assign-after-copy cases.
Also it doesn't notice variable references "behind the scenes":

.. code-block:: c++

void f(X);

void g(X x) {
auto &y = x;
f(x); // emits a warning...
y.f(); // ...but it is still used
}
Comment on lines +19 to +30
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I strongly oppose this design decision. In this check we should minimize the number of false-positives (and not leave any known false-positives). It's better to have false-negatives than false-positives, so an easy solution to this case could be:
If the variable is binded to a reference then we can not emit a warning.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is that any binding to a reference should skip the check. E.g.

void f(X);
void g(X&);

void func(X x) {
  g(x); // reference is created, we may not move from x anymore
  f(x); // no fix
}

I'm afraid too many cases are skipped due to this problem.

Copy link
Contributor

@vbvictor vbvictor Jun 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can distinguish cases where a variable was an initializer to VarDecl of type X& and where the variable was used as a function parameter as DeclRefExpr, https://godbolt.org/z/brKdcsn61.
Even if this can't be fixed, I think it's better to skip cases than have false-positives for this check.

In your 3-liner example, it may be easy to spot a false-positive, but if void g(X x) is 100+ lines long it will be hard to verify correctness. Thought clang-static-analyzer may find these cases, not everyone use it.

May other reviews share their opinions on this matter.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is that any binding to a reference should skip the check. E.g.

void f(X);
void g(X&);

void func(X x) {
  g(x); // reference is created, we may not move from x anymore
  f(x); // no fix
}

I'm afraid too many cases are skipped due to this problem.

Would it be a compromise to enable this via an option that is disabled by default?
Also, disable automatic fixes for those cases, so every change has to be done on purpose?


Such rare cases should be silenced using `// NOLINT`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should general functionality be mentioned?

Loading
Loading