clang-tools 6.0.0

UnnecessaryValueParamCheck.cpp
Go to the documentation of this file.
1 //===--- UnnecessaryValueParamCheck.cpp - clang-tidy-----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "UnnecessaryValueParamCheck.h"
11
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"
19
20 using namespace clang::ast_matchers;
21
22 namespace clang {
23 namespace tidy {
24 namespace performance {
25
26 namespace {
27
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('\''))
31 .str();
32 }
33
34 template <typename S>
35 bool isSubset(const S &SubsetCandidate, const S &SupersetCandidate) {
36 for (const auto &E : SubsetCandidate)
37 if (SupersetCandidate.count(E) == 0)
38 return false;
39 return true;
40 }
41
42 bool isReferencedOutsideOfCallExpr(const FunctionDecl &Function,
43 ASTContext &Context) {
44 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
45 unless(hasAncestor(callExpr()))),
46 Context);
47 return !Matches.empty();
48 }
49
50 bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
51 ASTContext &Context) {
52 auto Matches =
53 match(decl(forEachDescendant(declRefExpr(
54 equalsNode(&DeclRef),
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
56 whileStmt(), doStmt()))))))),
57 Decl, Context);
58 return Matches.empty();
59 }
60
61 bool isExplicitTemplateSpecialization(const FunctionDecl &Function) {
62 if (const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
63 if (SpecializationInfo->getTemplateSpecializationKind() ==
64 TSK_ExplicitSpecialization)
65 return true;
66 if (const auto *Method = llvm::dyn_cast<CXXMethodDecl>(&Function))
67 if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
68 Method->getMemberSpecializationInfo()->isExplicitSpecialization())
69 return true;
70 return false;
71 }
72
73 } // namespace
74
75 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
76 StringRef Name, ClangTidyContext *Context)
77 : ClangTidyCheck(Name, Context),
78 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
79 Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
80
81 void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
82 const auto ExpensiveValueParamDecl =
83 parmVarDecl(hasType(hasCanonicalType(allOf(
84 unless(referenceType()), matchers::isExpensiveToCopy()))),
85 decl().bind("param"));
86 Finder->addMatcher(
87 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
88 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
89 has(typeLoc(forEach(ExpensiveValueParamDecl))),
90 unless(isInstantiated()), decl().bind("functionDecl")),
91 this);
92 }
93
94 void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
95 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
96 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("functionDecl");
97 const size_t Index = std::find(Function->parameters().begin(),
98 Function->parameters().end(), Param) -
99 Function->parameters().begin();
100 bool IsConstQualified =
101 Param->getType().getCanonicalType().isConstQualified();
102
103 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
104 *Param, *Function, *Result.Context);
105 auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
106 *Param, *Function, *Result.Context);
107
108 // Do not trigger on non-const value parameters when they are not only used as
109 // const.
110 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
111 return;
112
113 // If the parameter is non-const, check if it has a move constructor and is
114 // only referenced once to copy-construct another object or whether it has a
115 // move assignment operator and is only referenced once when copy-assigned.
116 // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
117 // copy.
118 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
119 auto CanonicalType = Param->getType().getCanonicalType();
120 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
121
122 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
123 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
124 utils::decl_ref_expr::isCopyConstructorArgument(
125 DeclRefExpr, *Function, *Result.Context)) ||
126 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
127 utils::decl_ref_expr::isCopyAssignmentArgument(
128 DeclRefExpr, *Function, *Result.Context)))) {
129 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
130 return;
131 }
132 }
133
134 auto Diag =
135 diag(Param->getLocation(),
136 IsConstQualified ? "the const qualified parameter %0 is "
137 "copied for each invocation; consider "
138 "making it a reference"
139 : "the parameter %0 is copied for each "
140 "invocation but only used as a const reference; "
141 "consider making it a const reference")
142 << paramNameOrIndex(Param->getName(), Index);
143 // Do not propose fixes when:
144 // 1. the ParmVarDecl is in a macro, since we cannot place them correctly
145 // 2. the function is virtual as it might break overrides
146 // 3. the function is referenced outside of a call expression within the
147 // compilation unit as the signature change could introduce build errors.
148 // 4. the function is an explicit template specialization.
149 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
150 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
151 isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
152 isExplicitTemplateSpecialization(*Function))
153 return;
154 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
155 FunctionDecl = FunctionDecl->getPreviousDecl()) {
156 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
157 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
158 *Result.Context);
159 // The parameter of each declaration needs to be checked individually as to
160 // whether it is const or not as constness can differ between definition and
161 // declaration.
162 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
163 Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
164 }
165 }
166
167 void UnnecessaryValueParamCheck::registerPPCallbacks(
168 CompilerInstance &Compiler) {
169 Inserter.reset(new utils::IncludeInserter(
170 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
171 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
172 }
173
174 void UnnecessaryValueParamCheck::storeOptions(
175 ClangTidyOptions::OptionMap &Opts) {
176 Options.store(Opts, "IncludeStyle",
177 utils::IncludeSorter::toString(IncludeStyle));
178 }
179
180 void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
181 const DeclRefExpr &CopyArgument,
182 const ASTContext &Context) {
183 auto Diag = diag(CopyArgument.getLocStart(),
184 "parameter %0 is passed by value and only copied once; "
185 "consider moving it to avoid unnecessary copies")
186 << &Var;
187 // Do not propose fixes in macros since we cannot place them correctly.
188 if (CopyArgument.getLocStart().isMacroID())
189 return;
190 const auto &SM = Context.getSourceManager();
191 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
192 Context.getLangOpts());
193 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(), "std::move(")
194 << FixItHint::CreateInsertion(EndLoc, ")");
195 if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
196 SM.getFileID(CopyArgument.getLocStart()), "utility",
197 /*IsAngled=*/true))
198 Diag << *IncludeFixit;
199 }
200
201 } // namespace performance
202 } // namespace tidy
203 } // namespace clang
clang::ast_matchers
Definition: ClangTidyDiagnosticConsumer.h:27
clang::tidy::OptionsView::store
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.
Definition: ClangTidy.cpp:449
llvm
Definition: ClangTidyOptions.cpp:31
clang::tidy::utils::decl_ref_expr::allDeclRefExprs
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
Definition: DeclRefExprUtils.cpp:121
Name
StringHandle Name
Definition: PreprocessorTracker.cpp:525
clang::tidy::utils::decl_ref_expr::isCopyConstructorArgument
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...
Definition: DeclRefExprUtils.cpp:141
clang::tidy::utils::IncludeSorter::toString
static StringRef toString(IncludeStyle Style)
Converts IncludeStyle to string representation.
Definition: IncludeSorter.cpp:284
clang::tidy::performance::UnnecessaryValueParamCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: UnnecessaryValueParamCheck.cpp:174
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
clang::tidy::utils::type_traits::hasNonTrivialMoveConstructor
bool hasNonTrivialMoveConstructor(QualType Type)
Returns true if Type has a non-trivial move constructor.
Definition: TypeTraits.cpp:134
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidy.h:183
clang::tidy::utils::type_traits::isExpensiveToCopy
llvm::Optional< bool > isExpensiveToCopy(QualType Type, const ASTContext &Context)
Returns true if Type is expensive to copy.
Definition: TypeTraits.cpp:42
clang::tidy::utils::decl_ref_expr::constReferenceDeclRefExprs
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 ...
Definition: DeclRefExprUtils.cpp:46
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:99
clang
Definition: AndroidTidyModule.cpp:28
clang::tidy::performance::UnnecessaryValueParamCheck::registerPPCallbacks
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
Definition: UnnecessaryValueParamCheck.cpp:167
UnnecessaryValueParamCheck.h
clang::tidy::utils::IncludeInserter
Produces fixes to insert specified includes to source files, if not yet present.
Definition: IncludeInserter.h:55
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:104
clang::tidy::performance::UnnecessaryValueParamCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: UnnecessaryValueParamCheck.cpp:94
clang::tidy::utils::decl_ref_expr::isCopyAssignmentArgument
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...
Definition: DeclRefExprUtils.cpp:155
DeclRef
const DeclRefExpr * DeclRef
Definition: UseAfterMoveCheck.cpp:30
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:416
clang::tidy::utils::type_traits::hasNonTrivialMoveAssignment
bool hasNonTrivialMoveAssignment(QualType Type)
Return true if Type has a non-trivial move assignment operator.
Definition: TypeTraits.cpp:140
clang::tidy::utils::fixit::changeVarDeclToConst
FixItHint changeVarDeclToConst(const VarDecl &Var)
Creates fix to make VarDecl const qualified.
Definition: FixItHintUtils.cpp:29
clang::tidy::performance::UnnecessaryValueParamCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: UnnecessaryValueParamCheck.cpp:81
clang::tidy::utils::fixit::changeVarDeclToReference
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.
Definition: FixItHintUtils.cpp:19