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 =
72 unless(referenceType())))),
73 decl().bind(
"param"));
75 functionDecl(hasBody(stmt()), isDefinition(),
76 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
77 unless(isInstantiated()),
78 has(typeLoc(forEach(ExpensiveValueParamDecl))),
79 decl().bind(
"functionDecl")),
84 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>(
"param");
85 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>(
"functionDecl");
86 const size_t Index = std::find(Function->parameters().begin(),
87 Function->parameters().end(), Param) -
88 Function->parameters().begin();
89 bool IsConstQualified =
90 Param->getType().getCanonicalType().isConstQualified();
93 *Param, *Function, *Result.Context);
95 *Param, *Function, *Result.Context);
99 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
107 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
108 auto CanonicalType = Param->getType().getCanonicalType();
109 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
111 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
114 DeclRefExpr, *Function, *Result.Context)) ||
117 DeclRefExpr, *Function, *Result.Context)))) {
118 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
124 diag(Param->getLocation(),
125 IsConstQualified ?
"the const qualified parameter %0 is "
126 "copied for each invocation; consider "
127 "making it a reference"
128 :
"the parameter %0 is copied for each "
129 "invocation but only used as a const reference; "
130 "consider making it a const reference")
131 << paramNameOrIndex(Param->getName(), Index);
137 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
138 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
139 isReferencedOutsideOfCallExpr(*Function, *Result.Context))
141 for (
const auto *FunctionDecl = Function; FunctionDecl !=
nullptr;
142 FunctionDecl = FunctionDecl->getPreviousDecl()) {
143 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
149 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
155 CompilerInstance &Compiler) {
157 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
158 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
167 void UnnecessaryValueParamCheck::handleMoveFix(
const ParmVarDecl &Var,
168 const DeclRefExpr &CopyArgument,
169 const ASTContext &Context) {
170 auto Diag =
diag(CopyArgument.getLocStart(),
171 "parameter %0 is passed by value and only copied once; "
172 "consider moving it to avoid unnecessary copies")
175 if (CopyArgument.getLocStart().isMacroID())
177 const auto &
SM = Context.getSourceManager();
178 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0,
SM,
179 Context.getLangOpts());
180 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(),
"std::move(")
181 << FixItHint::CreateInsertion(EndLoc,
")");
182 if (
auto IncludeFixit = Inserter->CreateIncludeInsertion(
183 SM.getFileID(CopyArgument.getLocStart()),
"utility",
185 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 &.