blob: d585590128f0f9309d5e2679d41978bdbe958209 [file] [log] [blame]
Gabor Horvath3880bee2015-02-07 19:54:19 +00001//===--- InefficientAlgorithmCheck.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 "InefficientAlgorithmCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/Lexer.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang {
18namespace tidy {
Alexander Kornienko2b3124202015-03-02 12:25:03 +000019namespace misc {
Gabor Horvath3880bee2015-02-07 19:54:19 +000020
Gabor Horvath21b76ba2015-02-17 21:45:38 +000021static bool areTypesCompatible(QualType Left, QualType Right) {
22 if (const auto *LeftRefType = Left->getAs<ReferenceType>())
23 Left = LeftRefType->getPointeeType();
24 if (const auto *RightRefType = Right->getAs<ReferenceType>())
25 Right = RightRefType->getPointeeType();
26 return Left->getCanonicalTypeUnqualified() ==
27 Right->getCanonicalTypeUnqualified();
28}
29
Gabor Horvath3880bee2015-02-07 19:54:19 +000030void InefficientAlgorithmCheck::registerMatchers(MatchFinder *Finder) {
Aaron Ballman327e97b2015-08-28 19:27:19 +000031 // Only register the matchers for C++; the functionality currently does not
32 // provide any benefit to other languages, despite being benign.
Aaron Ballmanbf891092015-08-31 15:28:57 +000033 if (!getLangOpts().CPlusPlus)
34 return;
Gabor Horvath3880bee2015-02-07 19:54:19 +000035
Samuel Benzaquend7f2e342016-03-18 20:14:35 +000036 const auto Algorithms =
37 hasAnyName("::std::find", "::std::count", "::std::equal_range",
38 "::std::lower_bound", "::std::upper_bound");
39 const auto ContainerMatcher = classTemplateSpecializationDecl(hasAnyName(
40 "::std::set", "::std::map", "::std::multiset", "::std::multimap",
41 "::std::unordered_set", "::std::unordered_map"));
42
Aaron Ballmanbf891092015-08-31 15:28:57 +000043 const auto Matcher =
44 callExpr(
Samuel Benzaquend7f2e342016-03-18 20:14:35 +000045 callee(functionDecl(Algorithms)),
Aaron Ballmanbf891092015-08-31 15:28:57 +000046 hasArgument(
Aaron Ballmanb9ea09c2015-09-17 13:31:25 +000047 0, cxxConstructExpr(has(cxxMemberCallExpr(
48 callee(cxxMethodDecl(hasName("begin"))),
Aaron Ballmanbf891092015-08-31 15:28:57 +000049 on(declRefExpr(
50 hasDeclaration(decl().bind("IneffContObj")),
51 anyOf(hasType(ContainerMatcher.bind("IneffCont")),
52 hasType(pointsTo(
53 ContainerMatcher.bind("IneffContPtr")))))
54 .bind("IneffContExpr")))))),
Aaron Ballmanb9ea09c2015-09-17 13:31:25 +000055 hasArgument(1, cxxConstructExpr(has(cxxMemberCallExpr(
56 callee(cxxMethodDecl(hasName("end"))),
Aaron Ballmanbf891092015-08-31 15:28:57 +000057 on(declRefExpr(hasDeclaration(
58 equalsBoundNode("IneffContObj")))))))),
59 hasArgument(2, expr().bind("AlgParam")),
60 unless(isInTemplateInstantiation()))
61 .bind("IneffAlg");
62
63 Finder->addMatcher(Matcher, this);
Gabor Horvath3880bee2015-02-07 19:54:19 +000064}
65
66void InefficientAlgorithmCheck::check(const MatchFinder::MatchResult &Result) {
67 const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("IneffAlg");
68 const auto *IneffCont =
69 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffCont");
70 bool PtrToContainer = false;
71 if (!IneffCont) {
72 IneffCont =
73 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffContPtr");
74 PtrToContainer = true;
75 }
76 const llvm::StringRef IneffContName = IneffCont->getName();
77 const bool Unordered =
78 IneffContName.find("unordered") != llvm::StringRef::npos;
Gabor Horvath21b76ba2015-02-17 21:45:38 +000079 const bool Maplike = IneffContName.find("map") != llvm::StringRef::npos;
80
81 // Store if the key type of the container is compatible with the value
82 // that is searched for.
83 QualType ValueType = AlgCall->getArg(2)->getType();
84 QualType KeyType =
85 IneffCont->getTemplateArgs()[0].getAsType().getCanonicalType();
86 const bool CompatibleTypes = areTypesCompatible(KeyType, ValueType);
Gabor Horvath3880bee2015-02-07 19:54:19 +000087
88 // Check if the comparison type for the algorithm and the container matches.
89 if (AlgCall->getNumArgs() == 4 && !Unordered) {
90 const Expr *Arg = AlgCall->getArg(3);
91 const QualType AlgCmp =
92 Arg->getType().getUnqualifiedType().getCanonicalType();
93 const unsigned CmpPosition =
94 (IneffContName.find("map") == llvm::StringRef::npos) ? 1 : 2;
95 const QualType ContainerCmp = IneffCont->getTemplateArgs()[CmpPosition]
96 .getAsType()
97 .getUnqualifiedType()
98 .getCanonicalType();
99 if (AlgCmp != ContainerCmp) {
100 diag(Arg->getLocStart(),
101 "different comparers used in the algorithm and the container");
102 return;
103 }
104 }
105
106 const auto *AlgDecl = AlgCall->getDirectCallee();
107 if (!AlgDecl)
108 return;
109
110 if (Unordered && AlgDecl->getName().find("bound") != llvm::StringRef::npos)
111 return;
112
113 const auto *AlgParam = Result.Nodes.getNodeAs<Expr>("AlgParam");
114 const auto *IneffContExpr = Result.Nodes.getNodeAs<Expr>("IneffContExpr");
115 FixItHint Hint;
116
Alexander Kornienkob4fbb172015-07-31 13:34:58 +0000117 SourceManager &SM = *Result.SourceManager;
118 LangOptions LangOpts = Result.Context->getLangOpts();
119
120 CharSourceRange CallRange =
121 CharSourceRange::getTokenRange(AlgCall->getSourceRange());
122
123 // FIXME: Create a common utility to extract a file range that the given token
124 // sequence is exactly spelled at (without macro argument expansions etc.).
125 // We can't use Lexer::makeFileCharRange here, because for
126 //
127 // #define F(x) x
128 // x(a b c);
129 //
130 // it will return "x(a b c)", when given the range "a"-"c". It makes sense for
131 // removals, but not for replacements.
132 //
133 // This code is over-simplified, but works for many real cases.
134 if (SM.isMacroArgExpansion(CallRange.getBegin()) &&
135 SM.isMacroArgExpansion(CallRange.getEnd())) {
136 CallRange.setBegin(SM.getSpellingLoc(CallRange.getBegin()));
137 CallRange.setEnd(SM.getSpellingLoc(CallRange.getEnd()));
138 }
139
140 if (!CallRange.getBegin().isMacroID() && !Maplike && CompatibleTypes) {
141 StringRef ContainerText = Lexer::getSourceText(
142 CharSourceRange::getTokenRange(IneffContExpr->getSourceRange()), SM,
143 LangOpts);
144 StringRef ParamText = Lexer::getSourceText(
145 CharSourceRange::getTokenRange(AlgParam->getSourceRange()), SM,
146 LangOpts);
Gabor Horvath3880bee2015-02-07 19:54:19 +0000147 std::string ReplacementText =
Alexander Kornienkob4fbb172015-07-31 13:34:58 +0000148 (llvm::Twine(ContainerText) + (PtrToContainer ? "->" : ".") +
149 AlgDecl->getName() + "(" + ParamText + ")")
150 .str();
151 Hint = FixItHint::CreateReplacement(CallRange, ReplacementText);
Gabor Horvath3880bee2015-02-07 19:54:19 +0000152 }
153
154 diag(AlgCall->getLocStart(),
155 "this STL algorithm call should be replaced with a container method")
156 << Hint;
157}
158
Alexander Kornienko2b3124202015-03-02 12:25:03 +0000159} // namespace misc
Gabor Horvath3880bee2015-02-07 19:54:19 +0000160} // namespace tidy
161} // namespace clang