Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp

raw
1 //===--- TooSmallLoopVariableCheck.cpp - clang-tidy -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "TooSmallLoopVariableCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12
13 using namespace clang::ast_matchers;
14
15 namespace clang::tidy::bugprone {
16
17 static constexpr llvm::StringLiteral LoopName =
18 llvm::StringLiteral("forLoopName");
19 static constexpr llvm::StringLiteral LoopVarName =
20 llvm::StringLiteral("loopVar");
21 static constexpr llvm::StringLiteral LoopVarCastName =
22 llvm::StringLiteral("loopVarCast");
23 static constexpr llvm::StringLiteral LoopUpperBoundName =
24 llvm::StringLiteral("loopUpperBound");
25 static constexpr llvm::StringLiteral LoopIncrementName =
26 llvm::StringLiteral("loopIncrement");
27
28 TooSmallLoopVariableCheck::TooSmallLoopVariableCheck(StringRef Name,
29 ClangTidyContext *Context)
30 : ClangTidyCheck(Name, Context),
31 MagnitudeBitsUpperLimit(Options.get("MagnitudeBitsUpperLimit", 16U)) {}
32
33 void TooSmallLoopVariableCheck::storeOptions(
34 ClangTidyOptions::OptionMap &Opts) {
35 Options.store(Opts, "MagnitudeBitsUpperLimit", MagnitudeBitsUpperLimit);
36 }
37
38 /// The matcher for loops with suspicious integer loop variable.
39 ///
40 /// In this general example, assuming 'j' and 'k' are of integral type:
41 /// \code
42 /// for (...; j < 3 + 2; ++k) { ... }
43 /// \endcode
44 /// The following string identifiers are bound to these parts of the AST:
45 /// LoopVarName: 'j' (as a VarDecl)
46 /// LoopVarCastName: 'j' (after implicit conversion)
47 /// LoopUpperBoundName: '3 + 2' (as an Expr)
48 /// LoopIncrementName: 'k' (as an Expr)
49 /// LoopName: The entire for loop (as a ForStmt)
50 ///
51 void TooSmallLoopVariableCheck::registerMatchers(MatchFinder *Finder) {
52 StatementMatcher LoopVarMatcher =
53 expr(
54 ignoringParenImpCasts(declRefExpr(to(varDecl(hasType(isInteger()))))))
55 .bind(LoopVarName);
56
57 // We need to catch only those comparisons which contain any integer cast.
58 StatementMatcher LoopVarConversionMatcher = traverse(
59 TK_AsIs, implicitCastExpr(hasImplicitDestinationType(isInteger()),
60 has(ignoringParenImpCasts(LoopVarMatcher)))
61 .bind(LoopVarCastName));
62
63 // We are interested in only those cases when the loop bound is a variable
64 // value (not const, enum, etc.).
65 StatementMatcher LoopBoundMatcher =
66 expr(ignoringParenImpCasts(allOf(hasType(isInteger()),
67 unless(integerLiteral()),
68 unless(hasType(isConstQualified())),
69 unless(hasType(enumType())))))
70 .bind(LoopUpperBoundName);
71
72 // We use the loop increment expression only to make sure we found the right
73 // loop variable.
74 StatementMatcher IncrementMatcher =
75 expr(ignoringParenImpCasts(hasType(isInteger()))).bind(LoopIncrementName);
76
77 Finder->addMatcher(
78 forStmt(
79 hasCondition(anyOf(
80 binaryOperator(hasOperatorName("<"),
81 hasLHS(LoopVarConversionMatcher),
82 hasRHS(LoopBoundMatcher)),
83 binaryOperator(hasOperatorName("<="),
84 hasLHS(LoopVarConversionMatcher),
85 hasRHS(LoopBoundMatcher)),
86 binaryOperator(hasOperatorName(">"), hasLHS(LoopBoundMatcher),
87 hasRHS(LoopVarConversionMatcher)),
88 binaryOperator(hasOperatorName(">="), hasLHS(LoopBoundMatcher),
89 hasRHS(LoopVarConversionMatcher)))),
90 hasIncrement(IncrementMatcher))
91 .bind(LoopName),
92 this);
93 }
94
95 /// Returns the magnitude bits of an integer type.
96 static unsigned calcMagnitudeBits(const ASTContext &Context,
97 const QualType &IntExprType) {
98 assert(IntExprType->isIntegerType());
99
100 return IntExprType->isUnsignedIntegerType()
101 ? Context.getIntWidth(IntExprType)
102 : Context.getIntWidth(IntExprType) - 1;
103 }
104
105 /// Calculate the upper bound expression's magnitude bits, but ignore
106 /// constant like values to reduce false positives.
107 static unsigned calcUpperBoundMagnitudeBits(const ASTContext &Context,
108 const Expr *UpperBound,
109 const QualType &UpperBoundType) {
110 // Ignore casting caused by constant values inside a binary operator.
111 // We are interested in variable values' magnitude bits.
112 if (const auto *BinOperator = dyn_cast<BinaryOperator>(UpperBound)) {
113 const Expr *RHSE = BinOperator->getRHS()->IgnoreParenImpCasts();
114 const Expr *LHSE = BinOperator->getLHS()->IgnoreParenImpCasts();
115
116 QualType RHSEType = RHSE->getType();
117 QualType LHSEType = LHSE->getType();
118
119 if (!RHSEType->isIntegerType() || !LHSEType->isIntegerType())
120 return 0;
121
122 bool RHSEIsConstantValue = RHSEType->isEnumeralType() ||
123 RHSEType.isConstQualified() ||
124 isa<IntegerLiteral>(RHSE);
125 bool LHSEIsConstantValue = LHSEType->isEnumeralType() ||
126 LHSEType.isConstQualified() ||
127 isa<IntegerLiteral>(LHSE);
128
129 // Avoid false positives produced by two constant values.
130 if (RHSEIsConstantValue && LHSEIsConstantValue)
131 return 0;
132 if (RHSEIsConstantValue)
133 return calcMagnitudeBits(Context, LHSEType);
134 if (LHSEIsConstantValue)
135 return calcMagnitudeBits(Context, RHSEType);
136
137 return std::max(calcMagnitudeBits(Context, LHSEType),
138 calcMagnitudeBits(Context, RHSEType));
139 }
140
141 return calcMagnitudeBits(Context, UpperBoundType);
142 }
143
144 void TooSmallLoopVariableCheck::check(const MatchFinder::MatchResult &Result) {
145 const auto *LoopVar = Result.Nodes.getNodeAs<Expr>(LoopVarName);
146 const auto *UpperBound =
147 Result.Nodes.getNodeAs<Expr>(LoopUpperBoundName)->IgnoreParenImpCasts();
148 const auto *LoopIncrement =
149 Result.Nodes.getNodeAs<Expr>(LoopIncrementName)->IgnoreParenImpCasts();
150
151 // We matched the loop variable incorrectly.
152 if (LoopVar->getType() != LoopIncrement->getType())
153 return;
154
155 QualType LoopVarType = LoopVar->getType();
156 QualType UpperBoundType = UpperBound->getType();
157
158 ASTContext &Context = *Result.Context;
159
160 unsigned LoopVarMagnitudeBits = calcMagnitudeBits(Context, LoopVarType);
161 unsigned UpperBoundMagnitudeBits =
162 calcUpperBoundMagnitudeBits(Context, UpperBound, UpperBoundType);
163
164 if (UpperBoundMagnitudeBits == 0)
165 return;
166
167 if (LoopVarMagnitudeBits > MagnitudeBitsUpperLimit)
168 return;
169
170 if (LoopVarMagnitudeBits < UpperBoundMagnitudeBits)
171 diag(LoopVar->getBeginLoc(), "loop variable has narrower type %0 than "
172 "iteration's upper bound %1")
173 << LoopVarType << UpperBoundType;
174 }
175
176 } // namespace clang::tidy::bugprone