12 #include "../utils/DeclRefExprUtils.h"
13 #include "../utils/FixItHintUtils.h"
14 #include "../utils/Matchers.h"
15 #include "../utils/TypeTraits.h"
16 #include "clang/Frontend/CompilerInstance.h"
17 #include "clang/Lex/Lexer.h"
18 #include "clang/Lex/Preprocessor.h"
20 using namespace clang::ast_matchers;
24 namespace performance {
28 std::string paramNameOrIndex(StringRef
Name,
size_t Index) {
29 return (Name.empty() ? llvm::Twine(
'#') + llvm::Twine(Index + 1)
30 : llvm::Twine(
'\'') + Name + llvm::Twine(
'\''))
35 bool isSubset(
const S &SubsetCandidate,
const S &SupersetCandidate) {
36 for (
const auto &E : SubsetCandidate)
37 if (SupersetCandidate.count(E) == 0)
42 bool isReferencedOutsideOfCallExpr(
const FunctionDecl &Function,
44 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
45 unless(hasAncestor(callExpr()))),
47 return !Matches.empty();
50 bool hasLoopStmtAncestor(
const DeclRefExpr &
DeclRef,
const Decl &Decl,
51 ASTContext &Context) {
53 match(decl(forEachDescendant(declRefExpr(
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
56 whileStmt(), doStmt()))))))),
58 return Matches.empty();
63 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
66 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
67 Options.get(
"IncludeStyle",
"llvm"))) {}
70 const auto ExpensiveValueParamDecl =
71 parmVarDecl(hasType(hasCanonicalType(allOf(
73 decl().bind(
"param"));
75 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
76 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
77 has(typeLoc(forEach(ExpensiveValueParamDecl))),
78 unless(isInstantiated()), decl().bind(
"functionDecl")),
83 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>(
"param");
84 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>(
"functionDecl");
85 const size_t Index = std::find(Function->parameters().begin(),
86 Function->parameters().end(), Param) -
87 Function->parameters().begin();
88 bool IsConstQualified =
89 Param->getType().getCanonicalType().isConstQualified();
92 *Param, *Function, *Result.Context);
94 *Param, *Function, *Result.Context);
98 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
106 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
107 auto CanonicalType = Param->getType().getCanonicalType();
108 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
110 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
113 DeclRefExpr, *Function, *Result.Context)) ||
116 DeclRefExpr, *Function, *Result.Context)))) {
117 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
123 diag(Param->getLocation(),
124 IsConstQualified ?
"the const qualified parameter %0 is "
125 "copied for each invocation; consider "
126 "making it a reference"
127 :
"the parameter %0 is copied for each "
128 "invocation but only used as a const reference; "
129 "consider making it a const reference")
130 << paramNameOrIndex(Param->getName(), Index);
136 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
137 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
138 isReferencedOutsideOfCallExpr(*Function, *Result.Context))
140 for (
const auto *FunctionDecl = Function; FunctionDecl !=
nullptr;
141 FunctionDecl = FunctionDecl->getPreviousDecl()) {
142 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
148 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
154 CompilerInstance &Compiler) {
156 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
157 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
166 void UnnecessaryValueParamCheck::handleMoveFix(
const ParmVarDecl &Var,
167 const DeclRefExpr &CopyArgument,
168 const ASTContext &Context) {
169 auto Diag =
diag(CopyArgument.getLocStart(),
170 "parameter %0 is passed by value and only copied once; "
171 "consider moving it to avoid unnecessary copies")
174 if (CopyArgument.getLocStart().isMacroID())
176 const auto &
SM = Context.getSourceManager();
177 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0,
SM,
178 Context.getLangOpts());
179 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(),
"std::move(")
180 << FixItHint::CreateInsertion(EndLoc,
")");
181 if (
auto IncludeFixit = Inserter->CreateIncludeInsertion(
182 SM.getFileID(CopyArgument.getLocStart()),
"utility",
184 Diag << *IncludeFixit;
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
std::unique_ptr< ast_matchers::MatchFinder > Finder
bool isCopyConstructorArgument(const DeclRefExpr &DeclRef, const Decl &Decl, ASTContext &Context)
Returns true if DeclRefExpr is the argument of a copy-constructor call expression within Decl...
static StringRef toString(IncludeStyle Style)
Converts IncludeStyle to string representation.
Base class for all clang-tidy checks.
bool hasNonTrivialMoveConstructor(QualType Type)
Returns true if Type has a non-trivial move constructor.
llvm::Optional< bool > isExpensiveToCopy(QualType Type, const ASTContext &Context)
Returns true if Type is expensive to copy.
SmallPtrSet< const DeclRefExpr *, 16 > constReferenceDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt where VarDecl is guaranteed to be accessed in ...
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
std::map< std::string, std::string > OptionMap
Produces fixes to insert specified includes to source files, if not yet present.
ClangTidyContext & Context
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
bool isCopyAssignmentArgument(const DeclRefExpr &DeclRef, const Decl &Decl, ASTContext &Context)
Returns true if DeclRefExpr is the argument of a copy-assignment operator CallExpr within Decl...
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
bool hasNonTrivialMoveAssignment(QualType Type)
Return true if Type has a non-trivial move assignment operator.
FixItHint changeVarDeclToConst(const VarDecl &Var)
Creates fix to make VarDecl const qualified.
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.