|
| 1 | +//===--- MoveSharedPtrCheck.cpp - clang-tidy ------------------------------===// |
| 2 | +// |
| 3 | +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +// See https://llvm.org/LICENSE.txt for license information. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | +// |
| 7 | +//===----------------------------------------------------------------------===// |
| 8 | + |
| 9 | +#include "MoveSharedPtrCheck.h" |
| 10 | +#include "../utils/DeclRefExprUtils.h" |
| 11 | +#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | + |
| 13 | +using namespace clang::ast_matchers; |
| 14 | + |
| 15 | +namespace clang::tidy::performance { |
| 16 | + |
| 17 | +using utils::decl_ref_expr::allDeclRefExprs; |
| 18 | + |
| 19 | +void MoveSharedPtrCheck::registerMatchers(MatchFinder* Finder) { |
| 20 | + Finder->addMatcher( |
| 21 | + declRefExpr( |
| 22 | + hasDeclaration( |
| 23 | + varDecl(hasAncestor(functionDecl().bind("func"))).bind("decl")), |
| 24 | + hasParent(expr(hasParent(cxxConstructExpr())).bind("use_parent")) |
| 25 | + |
| 26 | + ) |
| 27 | + .bind("use"), |
| 28 | + this); |
| 29 | +} |
| 30 | + |
| 31 | +const Expr* MoveSharedPtrCheck::getLastVarUsage(const VarDecl& Var, |
| 32 | + const Decl& Func, |
| 33 | + ASTContext& Context) { |
| 34 | + auto Exprs = allDeclRefExprs(Var, Func, Context); |
| 35 | + |
| 36 | + const Expr* LastExpr = nullptr; |
| 37 | + for (const auto& Expr : Exprs) { |
| 38 | + if (!LastExpr) LastExpr = Expr; |
| 39 | + |
| 40 | + if (LastExpr->getBeginLoc() < Expr->getBeginLoc()) LastExpr = Expr; |
| 41 | + } |
| 42 | + |
| 43 | + // diag(LastExpr->getBeginLoc(), "last usage"); |
| 44 | + return LastExpr; |
| 45 | +} |
| 46 | + |
| 47 | +const std::string_view kSharedPtr = "std::shared_ptr<"; |
| 48 | + |
| 49 | +void MoveSharedPtrCheck::check(const MatchFinder::MatchResult& Result) { |
| 50 | + const auto* MatchedDecl = Result.Nodes.getNodeAs<VarDecl>("decl"); |
| 51 | + const auto* MatchedFunc = Result.Nodes.getNodeAs<FunctionDecl>("func"); |
| 52 | + const auto* MatchedUse = Result.Nodes.getNodeAs<Expr>("use"); |
| 53 | + const auto* MatchedUseCall = Result.Nodes.getNodeAs<CallExpr>("use_parent"); |
| 54 | + |
| 55 | + if (MatchedUseCall) return; |
| 56 | + |
| 57 | + auto Type = MatchedDecl->getType().getAsString(); |
| 58 | + if (std::string_view(Type).substr(0, kSharedPtr.size()) != kSharedPtr) return; |
| 59 | + |
| 60 | + const auto* LastUsage = |
| 61 | + getLastVarUsage(*MatchedDecl, *MatchedFunc, *Result.Context); |
| 62 | + if (LastUsage == nullptr) return; |
| 63 | + |
| 64 | + if (LastUsage->getBeginLoc() > MatchedUse->getBeginLoc()) { |
| 65 | + // "use" is not the last reference to x |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + diag(LastUsage->getBeginLoc(), Type); |
| 70 | + diag(LastUsage->getBeginLoc(), "Could be std::move()"); |
| 71 | +} |
| 72 | + |
| 73 | +} // namespace clang::tidy::performance |
0 commit comments