[clang-tools-extra] 12a9996 - [clang-tidy] Prevent false-positive in presence of derived-to-base cast in bugprone.use-after-move (#189638)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Apr 17 15:03:56 PDT 2026
Author: serge-sans-paille
Date: 2026-04-17T22:03:51Z
New Revision: 12a9996192f66e7b3b5534b43e50b2e387214097
URL: https://github.com/llvm/llvm-project/commit/12a9996192f66e7b3b5534b43e50b2e387214097
DIFF: https://github.com/llvm/llvm-project/commit/12a9996192f66e7b3b5534b43e50b2e387214097.diff
LOG: [clang-tidy] Prevent false-positive in presence of derived-to-base cast in bugprone.use-after-move (#189638)
The following scenario is quite common, but was reported as a
use-after-move:
```cpp
struct Base {
Base(Base&&);
};
struct C : Base {
int field;
C(C&& c) :
Base(std::move(c)), // << only moves through the base type
field(c.field) // << this is a valid use-after-move
{}
};
```
Fix this by checking field origin when the moved value is immediately
cast to base.
Added:
clang-tools-extra/test/clang-tidy/checkers/bugprone/use-after-move-derived-to-base.cpp
Modified:
clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
Removed:
################################################################################
diff --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index 9e9dfdc5de11e..31c70b3643be6 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -31,6 +31,20 @@ namespace clang::tidy::bugprone {
using matchers::hasUnevaluatedContext;
namespace {
+AST_MATCHER_P(Expr, hasParentIgnoringParenImpCasts,
+ ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
+ const Expr *E = &Node;
+ do {
+ const DynTypedNodeList Parents = Finder->getASTContext().getParents(*E);
+ if (Parents.size() != 1)
+ return false;
+ E = Parents[0].get<Expr>();
+ if (!E)
+ return false;
+ } while (isa<ImplicitCastExpr, ParenExpr>(E));
+
+ return InnerMatcher.matches(*E, Finder, Builder);
+}
/// Contains information about a use-after-move.
struct UseAfterMove {
@@ -52,7 +66,8 @@ class UseAfterMoveFinder {
public:
UseAfterMoveFinder(ASTContext *TheContext,
llvm::ArrayRef<StringRef> InvalidationFunctions,
- llvm::ArrayRef<StringRef> ReinitializationFunctions);
+ llvm::ArrayRef<StringRef> ReinitializationFunctions,
+ const CXXRecordDecl *MovedAs);
// Within the given code block, finds the first use of 'MovedVariable' that
// occurs after 'MovingCall' (the expression that performs the move). If a
@@ -77,26 +92,12 @@ class UseAfterMoveFinder {
ASTContext *Context;
llvm::ArrayRef<StringRef> InvalidationFunctions;
llvm::ArrayRef<StringRef> ReinitializationFunctions;
+ const CXXRecordDecl *MovedAs;
std::unique_ptr<ExprSequence> Sequence;
std::unique_ptr<StmtToBlockMap> BlockMap;
llvm::SmallPtrSet<const CFGBlock *, 8> Visited;
};
-AST_MATCHER_P(Expr, hasParentIgnoringParenImpCasts,
- ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
- const Expr *E = &Node;
- do {
- const DynTypedNodeList Parents = Finder->getASTContext().getParents(*E);
- if (Parents.size() != 1)
- return false;
- E = Parents[0].get<Expr>();
- if (!E)
- return false;
- } while (isa<ImplicitCastExpr, ParenExpr>(E));
-
- return InnerMatcher.matches(*E, Finder, Builder);
-}
-
} // namespace
static auto getNameMatcher(llvm::ArrayRef<StringRef> InvalidationFunctions) {
@@ -193,9 +194,10 @@ static StatementMatcher inDecltypeOrTemplateArg() {
UseAfterMoveFinder::UseAfterMoveFinder(
ASTContext *TheContext, llvm::ArrayRef<StringRef> InvalidationFunctions,
- llvm::ArrayRef<StringRef> ReinitializationFunctions)
+ llvm::ArrayRef<StringRef> ReinitializationFunctions,
+ const CXXRecordDecl *MovedAs)
: Context(TheContext), InvalidationFunctions(InvalidationFunctions),
- ReinitializationFunctions(ReinitializationFunctions) {}
+ ReinitializationFunctions(ReinitializationFunctions), MovedAs(MovedAs) {}
std::optional<UseAfterMove>
UseAfterMoveFinder::find(Stmt *CodeBlock, const Expr *MovingCall,
@@ -405,7 +407,13 @@ void UseAfterMoveFinder::getDeclRefs(
DeclRefs](const ArrayRef<BoundNodes> Matches) {
for (const auto &Match : Matches) {
const auto *DeclRef = Match.getNodeAs<DeclRefExpr>("declref");
+ const auto *Member = Match.getNodeAs<MemberExpr>("member-expr");
const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>("operator");
+ // Non-moved member as the move only implies a base class.
+ if (Member && MovedAs && !isa<CXXMethodDecl>(Member->getMemberDecl()) &&
+ !MovedAs->hasMemberName(Member->getMemberDecl()->getIdentifier())) {
+ continue;
+ }
if (DeclRef && BlockMap->blockContainingStmt(DeclRef) == Block) {
// Ignore uses of a standard smart pointer or classes annotated as
// "null_after_move" (smart-pointer-like behavior) that don't
@@ -420,7 +428,9 @@ void UseAfterMoveFinder::getDeclRefs(
declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
unless(inDecltypeOrTemplateArg()),
unless(hasParentIgnoringParenImpCasts(
- memberExpr(hasDeclaration(cxxDestructorDecl())))))
+ memberExpr(hasDeclaration(cxxDestructorDecl())))),
+ optionally(hasParentIgnoringParenImpCasts(
+ memberExpr().bind("member-expr"))))
.bind("declref");
AddDeclRefs(match(traverse(TK_AsIs, findAll(DeclRefMatcher)), *S->getStmt(),
@@ -540,25 +550,27 @@ void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
cxxMemberCallExpr(callee(cxxMethodDecl(hasName("try_emplace"))));
auto Arg = declRefExpr().bind("arg");
auto IsMemberCallee = callee(functionDecl(unless(isStaticStorageClass())));
- auto CallMoveMatcher =
- callExpr(callee(functionDecl(getNameMatcher(InvalidationFunctions))
- .bind("move-decl")),
- anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
- callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
- hasArgument(0, Arg))),
- unless(inDecltypeOrTemplateArg()),
- unless(hasParent(TryEmplaceMatcher)), expr().bind("call-move"),
- anyOf(hasAncestor(compoundStmt(
- hasParent(lambdaExpr().bind("containing-lambda")))),
- hasAncestor(functionDecl(anyOf(
- cxxConstructorDecl(
- hasAnyConstructorInitializer(withInitializer(
- expr(anyOf(equalsBoundNode("call-move"),
- hasDescendant(expr(
- equalsBoundNode("call-move")))))
- .bind("containing-ctor-init"))))
- .bind("containing-ctor"),
- functionDecl().bind("containing-func"))))));
+ auto CallMoveMatcher = callExpr(
+ callee(functionDecl(getNameMatcher(InvalidationFunctions))
+ .bind("move-decl")),
+ anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
+ callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
+ hasArgument(0, Arg))),
+ unless(inDecltypeOrTemplateArg()), unless(hasParent(TryEmplaceMatcher)),
+ expr().bind("call-move"),
+ optionally(hasParent(implicitCastExpr(hasCastKind(CK_DerivedToBase))
+ .bind("optional-cast"))),
+ anyOf(hasAncestor(compoundStmt(
+ hasParent(lambdaExpr().bind("containing-lambda")))),
+ hasAncestor(functionDecl(
+ anyOf(cxxConstructorDecl(
+ hasAnyConstructorInitializer(withInitializer(
+ expr(anyOf(equalsBoundNode("call-move"),
+ hasDescendant(expr(
+ equalsBoundNode("call-move")))))
+ .bind("containing-ctor-init"))))
+ .bind("containing-ctor"),
+ functionDecl().bind("containing-func"))))));
Finder->addMatcher(
traverse(
@@ -593,6 +605,8 @@ void UseAfterMoveCheck::check(const MatchFinder::MatchResult &Result) {
const auto *MovingCall = Result.Nodes.getNodeAs<Expr>("moving-call");
const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>("arg");
const auto *MoveDecl = Result.Nodes.getNodeAs<FunctionDecl>("move-decl");
+ const auto *ParentCast =
+ Result.Nodes.getNodeAs<ImplicitCastExpr>("optional-cast");
if (!MovingCall || !MovingCall->getExprLoc().isValid())
MovingCall = CallMove;
@@ -623,9 +637,12 @@ void UseAfterMoveCheck::check(const MatchFinder::MatchResult &Result) {
CodeBlocks.push_back(ContainingFunc->getBody());
}
+ const CXXRecordDecl *MovedAs =
+ ParentCast ? ParentCast->getType()->getAsCXXRecordDecl() : nullptr;
+
for (Stmt *CodeBlock : CodeBlocks) {
UseAfterMoveFinder Finder(Result.Context, InvalidationFunctions,
- ReinitializationFunctions);
+ ReinitializationFunctions, MovedAs);
if (auto Use = Finder.find(CodeBlock, MovingCall, Arg))
emitDiagnostic(MovingCall, Arg, *Use, this, Result.Context,
determineMoveType(MoveDecl), MoveDecl);
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst
index 329d0a42aef7a..95ed0061d654c 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -318,6 +318,9 @@ Changes in existing checks
- Do not report explicit call to destructor after move as an invalid use.
+ - Avoid false positives when moving object to a base type then accessing
+ non-base members.
+
- Improved :doc:`cppcoreguidelines-avoid-capturing-lambda-coroutines
<clang-tidy/checks/cppcoreguidelines/avoid-capturing-lambda-coroutines>`
check by adding the `AllowExplicitObjectParameters` option. When enabled,
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/use-after-move-derived-to-base.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/use-after-move-derived-to-base.cpp
new file mode 100644
index 0000000000000..bd1a0a6f6c180
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/use-after-move-derived-to-base.cpp
@@ -0,0 +1,38 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s bugprone-use-after-move %t
+
+#include <utility>
+
+struct A {
+ int a;
+};
+
+struct B : A {
+ int b;
+ void f();
+ B(B&& other) :
+ A(std::move(other)),
+ b(std::move(other.b))
+ // CHECK-NOTES-NOT: [[@LINE-1]]:17: warning: 'other' used after it was moved
+ {
+ other.f();
+ // CHECK-NOTES: [[@LINE-1]]:7: warning: 'other' used after it was moved
+ // CHECK-NOTES: [[@LINE-6]]:5: note: move occurred here
+ }
+};
+
+struct C : A {
+ int c;
+ C(C&& other) :
+ A(std::move(other))
+ {
+ other.a;
+ // CHECK-NOTES: [[@LINE-1]]:7: warning: 'other' used after it was moved
+ // CHECK-NOTES: [[@LINE-4]]:5: note: move occurred here
+ }
+};
+
+struct D { int d; };
+struct E : A, D {
+ E(E&& other) : A(std::move(other)) { other.d; }
+};
+
More information about the cfe-commits
mailing list