blob: 0dc47d5db93ddb74f7df85fe156f0f30c3fea6dd [file] [log] [blame]
Felix Berger3c8edde2016-03-29 02:42:38 +00001//===--- 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"
Felix Berger7f882752016-07-01 20:12:15 +000015#include "../utils/TypeTraits.h"
16#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Lex/Lexer.h"
18#include "clang/Lex/Preprocessor.h"
Felix Berger3c8edde2016-03-29 02:42:38 +000019
20using namespace clang::ast_matchers;
21
22namespace clang {
23namespace tidy {
24namespace performance {
25
26namespace {
27
28std::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
Felix Berger7f882752016-07-01 20:12:15 +000034template <typename S>
35bool 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
Felix Berger85f9e8b32016-11-10 01:28:22 +000042bool 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
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000050bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
Felix Berger519de4b2016-12-16 02:47:56 +000051 ASTContext &Context) {
52 auto Matches =
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000053 match(decl(forEachDescendant(declRefExpr(
Felix Berger519de4b2016-12-16 02:47:56 +000054 equalsNode(&DeclRef),
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000056 whileStmt(), doStmt()))))))),
57 Decl, Context);
Felix Berger519de4b2016-12-16 02:47:56 +000058 return Matches.empty();
59}
60
Felix Berger603ea2d2017-07-26 00:45:41 +000061bool 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
Felix Berger3c8edde2016-03-29 02:42:38 +000073} // namespace
74
Felix Berger7f882752016-07-01 20:12:15 +000075UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
76 StringRef Name, ClangTidyContext *Context)
77 : ClangTidyCheck(Name, Context),
78 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
Alexander Kornienkob1c74322017-07-20 12:02:03 +000079 Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
Felix Berger7f882752016-07-01 20:12:15 +000080
Felix Berger3c8edde2016-03-29 02:42:38 +000081void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
82 const auto ExpensiveValueParamDecl =
Alexander Kornienkob215d472017-05-16 17:28:17 +000083 parmVarDecl(hasType(hasCanonicalType(allOf(
84 unless(referenceType()), matchers::isExpensiveToCopy()))),
Felix Berger3c8edde2016-03-29 02:42:38 +000085 decl().bind("param"));
86 Finder->addMatcher(
Alexander Kornienkob215d472017-05-16 17:28:17 +000087 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
Felix Bergere4ab0602016-12-02 14:44:16 +000088 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
Felix Berger3c8edde2016-03-29 02:42:38 +000089 has(typeLoc(forEach(ExpensiveValueParamDecl))),
Alexander Kornienkob215d472017-05-16 17:28:17 +000090 unless(isInstantiated()), decl().bind("functionDecl")),
Felix Berger3c8edde2016-03-29 02:42:38 +000091 this);
92}
93
94void 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
Felix Berger7f882752016-07-01 20:12:15 +0000103 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000104 *Param, *Function, *Result.Context);
Felix Berger7f882752016-07-01 20:12:15 +0000105 auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000106 *Param, *Function, *Result.Context);
107
108 // Do not trigger on non-const value parameters when they are not only used as
109 // const.
Felix Berger7f882752016-07-01 20:12:15 +0000110 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.
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000118 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
Felix Berger7f882752016-07-01 20:12:15 +0000119 auto CanonicalType = Param->getType().getCanonicalType();
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000120 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
121
122 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
Felix Berger7f882752016-07-01 20:12:15 +0000123 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
124 utils::decl_ref_expr::isCopyConstructorArgument(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000125 DeclRefExpr, *Function, *Result.Context)) ||
Felix Berger7f882752016-07-01 20:12:15 +0000126 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
127 utils::decl_ref_expr::isCopyAssignmentArgument(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000128 DeclRefExpr, *Function, *Result.Context)))) {
129 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
Felix Berger7f882752016-07-01 20:12:15 +0000130 return;
131 }
132 }
133
Felix Berger3c8edde2016-03-29 02:42:38 +0000134 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);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000143 // 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.
Felix Berger603ea2d2017-07-26 00:45:41 +0000148 // 4. the function is an explicit template specialization.
Felix Berger17934da2016-07-05 14:40:44 +0000149 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000150 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
Felix Berger603ea2d2017-07-26 00:45:41 +0000151 isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
152 isExplicitTemplateSpecialization(*Function))
Felix Berger3c8edde2016-03-29 02:42:38 +0000153 return;
154 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
155 FunctionDecl = FunctionDecl->getPreviousDecl()) {
156 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000157 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000158 *Result.Context);
Felix Berger7c6d2892016-11-04 20:51:31 +0000159 // 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())
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000163 Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
Felix Berger3c8edde2016-03-29 02:42:38 +0000164 }
165}
166
Felix Berger7f882752016-07-01 20:12:15 +0000167void 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
174void UnnecessaryValueParamCheck::storeOptions(
175 ClangTidyOptions::OptionMap &Opts) {
176 Options.store(Opts, "IncludeStyle",
177 utils::IncludeSorter::toString(IncludeStyle));
178}
179
180void 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();
Kirill Bobyrev11cea452016-08-01 12:06:18 +0000191 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
192 Context.getLangOpts());
Felix Berger7f882752016-07-01 20:12:15 +0000193 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
Felix Berger3c8edde2016-03-29 02:42:38 +0000201} // namespace performance
202} // namespace tidy
203} // namespace clang