blob: a3ebf0b750aacf13a1d643171d80bc2716cdbb4c [file] [log] [blame]
Tom Caredb2fa8a2010-07-06 21:43:29 +00001//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
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// This file defines a set of path-sensitive checks for idempotent and/or
11// tautological operations. Each potential operation is checked along all paths
12// to see if every path results in a pointless operation.
13// +-------------------------------------------+
14// |Table of idempotent/tautological operations|
15// +-------------------------------------------+
16//+--------------------------------------------------------------------------+
17//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
18//+--------------------------------------------------------------------------+
19// +, += | | | | x | x | |
20// -, -= | | | | x | -x | |
21// *, *= | | x | x | 0 | 0 | |
22// /, /= | 1 | x | | N/A | 0 | |
23// &, &= | x | | | 0 | 0 | x | x
24// |, |= | x | | | x | x | ~0 | ~0
25// ^, ^= | 0 | | | x | x | |
26// <<, <<= | | | | x | 0 | |
27// >>, >>= | | | | x | 0 | |
28// || | 1 | 1 | 1 | x | x | 1 | 1
29// && | 1 | x | x | 0 | 0 | x | x
30// = | x | | | | | |
31// == | 1 | | | | | |
32// >= | 1 | | | | | |
33// <= | 1 | | | | | |
34// > | 0 | | | | | |
35// < | 0 | | | | | |
36// != | 0 | | | | | |
37//===----------------------------------------------------------------------===//
38//
Tom Carea7a8a452010-08-12 22:45:47 +000039// Things TODO:
Tom Caredb2fa8a2010-07-06 21:43:29 +000040// - Improved error messages
41// - Handle mixed assumptions (which assumptions can belong together?)
42// - Finer grained false positive control (levels)
Tom Carea7a8a452010-08-12 22:45:47 +000043// - Handling ~0 values
Tom Caredb2fa8a2010-07-06 21:43:29 +000044
Argyrios Kyrtzidisc9f2e0f2011-02-15 22:55:14 +000045#include "ClangSACheckers.h"
Tom Carea7a8a452010-08-12 22:45:47 +000046#include "clang/Analysis/CFGStmtMap.h"
Tom Caredb34ab72010-08-23 19:51:57 +000047#include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
Ted Kremenek42461ee2011-02-23 01:51:59 +000048#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000049#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000050#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +000051#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000052#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
53#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
54#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000055#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
56#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000057#include "clang/AST/Stmt.h"
58#include "llvm/ADT/DenseMap.h"
Tom Carea7a8a452010-08-12 22:45:47 +000059#include "llvm/ADT/SmallSet.h"
Ted Kremenek8e376772011-02-14 17:59:20 +000060#include "llvm/ADT/BitVector.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000061#include "llvm/Support/ErrorHandling.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000062
63using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000064using namespace ento;
Tom Caredb2fa8a2010-07-06 21:43:29 +000065
66namespace {
67class IdempotentOperationChecker
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000068 : public Checker<check::PreStmt<BinaryOperator>,
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +000069 check::PostStmt<BinaryOperator>,
70 check::EndAnalysis> {
Tom Careb0627952010-09-09 02:04:52 +000071public:
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +000072 void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
73 void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const;
74 void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,ExprEngine &Eng) const;
Tom Careb0627952010-09-09 02:04:52 +000075
76private:
77 // Our assumption about a particular operation.
78 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
79 RHSis0 };
80
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +000081 static void UpdateAssumption(Assumption &A, const Assumption &New);
Tom Careb0627952010-09-09 02:04:52 +000082
83 // False positive reduction methods
84 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
Ted Kremenek1d26f482011-10-24 01:32:45 +000085 static bool isUnused(const Expr *E, AnalysisDeclContext *AC);
Tom Careb0627952010-09-09 02:04:52 +000086 static bool isTruncationExtensionAssignment(const Expr *LHS,
87 const Expr *RHS);
Ted Kremenek1d26f482011-10-24 01:32:45 +000088 static bool pathWasCompletelyAnalyzed(AnalysisDeclContext *AC,
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +000089 const CFGBlock *CB,
90 const CoreEngine &CE);
Tom Careb0627952010-09-09 02:04:52 +000091 static bool CanVary(const Expr *Ex,
Ted Kremenek1d26f482011-10-24 01:32:45 +000092 AnalysisDeclContext *AC);
Tom Careb0627952010-09-09 02:04:52 +000093 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
Ted Kremenek1d26f482011-10-24 01:32:45 +000094 AnalysisDeclContext *AC);
Tom Careb0627952010-09-09 02:04:52 +000095 static bool containsNonLocalVarDecl(const Stmt *S);
Tom Careb0627952010-09-09 02:04:52 +000096
97 // Hash table and related data structures
98 struct BinaryOperatorData {
Anna Zaks3381a732011-10-03 23:07:13 +000099 BinaryOperatorData() : assumption(Possible) {}
Tom Careb0627952010-09-09 02:04:52 +0000100
101 Assumption assumption;
Tom Careb0627952010-09-09 02:04:52 +0000102 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
103 // BinaryOperator
104 };
105 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
106 AssumptionMap;
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000107 mutable AssumptionMap hash;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000108};
109}
110
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000111void IdempotentOperationChecker::checkPreStmt(const BinaryOperator *B,
112 CheckerContext &C) const {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000113 // Find or create an entry in the hash for this BinaryOperator instance.
114 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000115 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
116 // been created yet.
117 BinaryOperatorData &Data = hash[B];
118 Assumption &A = Data.assumption;
Ted Kremenek1d26f482011-10-24 01:32:45 +0000119 AnalysisDeclContext *AC = C.getCurrentAnalysisDeclContext();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000120
121 // If we already have visited this node on a path that does not contain an
122 // idempotent operation, return immediately.
123 if (A == Impossible)
124 return;
125
Tom Carea7a8a452010-08-12 22:45:47 +0000126 // Retrieve both sides of the operator and determine if they can vary (which
127 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000128 const Expr *LHS = B->getLHS();
129 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000130
Tom Caredb34ab72010-08-23 19:51:57 +0000131 // At this stage we can calculate whether each side contains a false positive
132 // that applies to all operators. We only need to calculate this the first
133 // time.
134 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000135 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000136 // An expression contains a false positive if it can't vary, or if it
137 // contains a known false positive VarDecl.
138 LHSContainsFalsePositive = !CanVary(LHS, AC)
139 || containsNonLocalVarDecl(LHS);
140 RHSContainsFalsePositive = !CanVary(RHS, AC)
141 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000142 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000143
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000144 const ProgramState *state = C.getState();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000145
146 SVal LHSVal = state->getSVal(LHS);
147 SVal RHSVal = state->getSVal(RHS);
148
149 // If either value is unknown, we can't be 100% sure of all paths.
150 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
151 A = Impossible;
152 return;
153 }
154 BinaryOperator::Opcode Op = B->getOpcode();
155
156 // Dereference the LHS SVal if this is an assign operation
157 switch (Op) {
158 default:
159 break;
160
161 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000162 case BO_AddAssign:
163 case BO_SubAssign:
164 case BO_MulAssign:
165 case BO_DivAssign:
166 case BO_AndAssign:
167 case BO_OrAssign:
168 case BO_XorAssign:
169 case BO_ShlAssign:
170 case BO_ShrAssign:
171 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000172 // Assign statements have one extra level of indirection
173 if (!isa<Loc>(LHSVal)) {
174 A = Impossible;
175 return;
176 }
Ted Kremenek96ebad62010-09-09 07:13:00 +0000177 LHSVal = state->getSVal(cast<Loc>(LHSVal), LHS->getType());
Tom Caredb2fa8a2010-07-06 21:43:29 +0000178 }
179
180
181 // We now check for various cases which result in an idempotent operation.
182
183 // x op x
184 switch (Op) {
185 default:
186 break; // We don't care about any other operators.
187
188 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000189 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000190 // x Assign x can be used to silence unused variable warnings intentionally.
191 // If this is a self assignment and the variable is referenced elsewhere,
Tom Care84c24ed2010-09-07 20:27:56 +0000192 // and the assignment is not a truncation or extension, then it is a false
193 // positive.
Tom Care6216dc02010-08-30 19:25:43 +0000194 if (isSelfAssign(LHS, RHS)) {
Tom Care84c24ed2010-09-07 20:27:56 +0000195 if (!isUnused(LHS, AC) && !isTruncationExtensionAssignment(LHS, RHS)) {
Tom Care6216dc02010-08-30 19:25:43 +0000196 UpdateAssumption(A, Equal);
197 return;
198 }
199 else {
200 A = Impossible;
201 return;
202 }
Tom Caredf4ca422010-07-16 20:41:41 +0000203 }
204
John McCall2de56d12010-08-25 11:45:40 +0000205 case BO_SubAssign:
206 case BO_DivAssign:
207 case BO_AndAssign:
208 case BO_OrAssign:
209 case BO_XorAssign:
210 case BO_Sub:
211 case BO_Div:
212 case BO_And:
213 case BO_Or:
214 case BO_Xor:
215 case BO_LOr:
216 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000217 case BO_EQ:
218 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000219 if (LHSVal != RHSVal || LHSContainsFalsePositive
220 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000221 break;
222 UpdateAssumption(A, Equal);
223 return;
224 }
225
226 // x op 1
227 switch (Op) {
228 default:
229 break; // We don't care about any other operators.
230
231 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000232 case BO_MulAssign:
233 case BO_DivAssign:
234 case BO_Mul:
235 case BO_Div:
236 case BO_LOr:
237 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000238 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000239 break;
240 UpdateAssumption(A, RHSis1);
241 return;
242 }
243
244 // 1 op x
245 switch (Op) {
246 default:
247 break; // We don't care about any other operators.
248
249 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000250 case BO_MulAssign:
251 case BO_Mul:
252 case BO_LOr:
253 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000254 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000255 break;
256 UpdateAssumption(A, LHSis1);
257 return;
258 }
259
260 // x op 0
261 switch (Op) {
262 default:
263 break; // We don't care about any other operators.
264
265 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000266 case BO_AddAssign:
267 case BO_SubAssign:
268 case BO_MulAssign:
269 case BO_AndAssign:
270 case BO_OrAssign:
271 case BO_XorAssign:
272 case BO_Add:
273 case BO_Sub:
274 case BO_Mul:
275 case BO_And:
276 case BO_Or:
277 case BO_Xor:
278 case BO_Shl:
279 case BO_Shr:
280 case BO_LOr:
281 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000282 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000283 break;
284 UpdateAssumption(A, RHSis0);
285 return;
286 }
287
288 // 0 op x
289 switch (Op) {
290 default:
291 break; // We don't care about any other operators.
292
293 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000294 //case BO_AddAssign: // Common false positive
295 case BO_SubAssign: // Check only if unsigned
296 case BO_MulAssign:
297 case BO_DivAssign:
298 case BO_AndAssign:
299 //case BO_OrAssign: // Common false positive
300 //case BO_XorAssign: // Common false positive
301 case BO_ShlAssign:
302 case BO_ShrAssign:
303 case BO_Add:
304 case BO_Sub:
305 case BO_Mul:
306 case BO_Div:
307 case BO_And:
308 case BO_Or:
309 case BO_Xor:
310 case BO_Shl:
311 case BO_Shr:
312 case BO_LOr:
313 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000314 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000315 break;
316 UpdateAssumption(A, LHSis0);
317 return;
318 }
319
320 // If we get to this point, there has been a valid use of this operation.
321 A = Impossible;
322}
323
Tom Care2bbbe502010-09-02 23:30:22 +0000324// At the post visit stage, the predecessor ExplodedNode will be the
325// BinaryOperator that was just created. We use this hook to collect the
326// ExplodedNode.
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000327void IdempotentOperationChecker::checkPostStmt(const BinaryOperator *B,
328 CheckerContext &C) const {
Tom Care2bbbe502010-09-02 23:30:22 +0000329 // Add the ExplodedNode we just visited
330 BinaryOperatorData &Data = hash[B];
Ted Kremenek020c3742011-02-12 18:50:03 +0000331
332 const Stmt *predStmt
333 = cast<StmtPoint>(C.getPredecessor()->getLocation()).getStmt();
334
335 // Ignore implicit calls to setters.
Ted Kremenekcf995d32011-03-15 19:27:57 +0000336 if (!isa<BinaryOperator>(predStmt))
Ted Kremenek020c3742011-02-12 18:50:03 +0000337 return;
Ted Kremenekcf995d32011-03-15 19:27:57 +0000338
Tom Care2bbbe502010-09-02 23:30:22 +0000339 Data.explodedNodes.Add(C.getPredecessor());
340}
341
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000342void IdempotentOperationChecker::checkEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000343 BugReporter &BR,
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000344 ExprEngine &Eng) const {
Tom Care2bbbe502010-09-02 23:30:22 +0000345 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000346 // Iterate over the hash to see if we have any paths with definite
347 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000348 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
349 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000350 const BinaryOperatorData &Data = i->second;
351 const Assumption &A = Data.assumption;
Tom Care2bbbe502010-09-02 23:30:22 +0000352 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000353
Anna Zaks3381a732011-10-03 23:07:13 +0000354 // If there are no nodes accosted with the expression, nothing to report.
355 // FIXME: This is possible because the checker does part of processing in
356 // checkPreStmt and part in checkPostStmt.
357 if (ES.begin() == ES.end())
358 continue;
359
Tom Carea7a8a452010-08-12 22:45:47 +0000360 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000361
Tom Carea7a8a452010-08-12 22:45:47 +0000362 if (A == Impossible)
363 continue;
364
365 // If the analyzer did not finish, check to see if we can still emit this
366 // warning
367 if (Eng.hasWorkRemaining()) {
Tom Carea7a8a452010-08-12 22:45:47 +0000368 // If we can trace back
Ted Kremenek1d26f482011-10-24 01:32:45 +0000369 AnalysisDeclContext *AC = (*ES.begin())->getLocationContext()
370 ->getAnalysisDeclContext();
Ted Kremenek42461ee2011-02-23 01:51:59 +0000371 if (!pathWasCompletelyAnalyzed(AC,
372 AC->getCFGStmtMap()->getBlock(B),
Tom Carea7a8a452010-08-12 22:45:47 +0000373 Eng.getCoreEngine()))
374 continue;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000375 }
Tom Carea7a8a452010-08-12 22:45:47 +0000376
Tom Care2bbbe502010-09-02 23:30:22 +0000377 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000378 llvm::SmallString<128> buf;
379 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000380 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000381 switch (A) {
382 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000383 LHSRelevant = true;
384 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000385 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000386 os << "Assigned value is always the same as the existing value";
387 else
388 os << "Both operands to '" << B->getOpcodeStr()
389 << "' always have the same value";
390 break;
391 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000392 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000393 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
394 break;
395 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000396 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000397 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
398 break;
399 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000400 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000401 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
402 break;
403 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000404 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000405 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
406 break;
407 case Possible:
408 llvm_unreachable("Operation was never marked with an assumption");
409 case Impossible:
410 llvm_unreachable(0);
411 }
412
Tom Care2bbbe502010-09-02 23:30:22 +0000413 // Add a report for each ExplodedNode
414 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000415 BugReport *report = new BugReport(*BT, os.str(), *I);
Tom Care2bbbe502010-09-02 23:30:22 +0000416
417 // Add source ranges and visitor hooks
418 if (LHSRelevant) {
419 const Expr *LHS = i->first->getLHS();
420 report->addRange(LHS->getSourceRange());
Anna Zaks50bbc162011-08-19 22:33:38 +0000421 FindLastStoreBRVisitor::registerStatementVarDecls(*report, LHS);
Tom Care2bbbe502010-09-02 23:30:22 +0000422 }
423 if (RHSRelevant) {
424 const Expr *RHS = i->first->getRHS();
425 report->addRange(i->first->getRHS()->getSourceRange());
Anna Zaks50bbc162011-08-19 22:33:38 +0000426 FindLastStoreBRVisitor::registerStatementVarDecls(*report, RHS);
Tom Care2bbbe502010-09-02 23:30:22 +0000427 }
428
429 BR.EmitReport(report);
430 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000431 }
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000432
433 hash.clear();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000434}
435
436// Updates the current assumption given the new assumption
437inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
438 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000439// If the assumption is the same, there is nothing to do
440 if (A == New)
441 return;
442
Tom Caredb2fa8a2010-07-06 21:43:29 +0000443 switch (A) {
444 // If we don't currently have an assumption, set it
445 case Possible:
446 A = New;
447 return;
448
449 // If we have determined that a valid state happened, ignore the new
450 // assumption.
451 case Impossible:
452 return;
453
454 // Any other case means that we had a different assumption last time. We don't
455 // currently support mixing assumptions for diagnostic reasons, so we set
456 // our assumption to be impossible.
457 default:
458 A = Impossible;
459 return;
460 }
461}
462
Tom Care6216dc02010-08-30 19:25:43 +0000463// Check for a statement where a variable is self assigned to possibly avoid an
464// unused variable warning.
465bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000466 LHS = LHS->IgnoreParenCasts();
467 RHS = RHS->IgnoreParenCasts();
468
469 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
470 if (!LHS_DR)
471 return false;
472
Tom Careef52bcb2010-08-24 21:09:07 +0000473 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
474 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000475 return false;
476
477 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
478 if (!RHS_DR)
479 return false;
480
Tom Careef52bcb2010-08-24 21:09:07 +0000481 if (VD != RHS_DR->getDecl())
482 return false;
483
Tom Care6216dc02010-08-30 19:25:43 +0000484 return true;
485}
486
487// Returns true if the Expr points to a VarDecl that is not read anywhere
488// outside of self-assignments.
489bool IdempotentOperationChecker::isUnused(const Expr *E,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000490 AnalysisDeclContext *AC) {
Tom Care6216dc02010-08-30 19:25:43 +0000491 if (!E)
492 return false;
493
494 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
495 if (!DR)
496 return false;
497
498 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
499 if (!VD)
500 return false;
501
Tom Careef52bcb2010-08-24 21:09:07 +0000502 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
503 return false;
504
505 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000506}
507
508// Check for self casts truncating/extending a variable
509bool IdempotentOperationChecker::isTruncationExtensionAssignment(
510 const Expr *LHS,
511 const Expr *RHS) {
512
513 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
514 if (!LHS_DR)
515 return false;
516
517 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
518 if (!VD)
519 return false;
520
521 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
522 if (!RHS_DR)
523 return false;
524
525 if (VD != RHS_DR->getDecl())
526 return false;
527
John McCallf6a16482010-12-04 03:47:34 +0000528 return dyn_cast<DeclRefExpr>(RHS->IgnoreParenLValueCasts()) == NULL;
Tom Caredf4ca422010-07-16 20:41:41 +0000529}
530
Tom Carea7a8a452010-08-12 22:45:47 +0000531// Returns false if a path to this block was not completely analyzed, or true
532// otherwise.
Ted Kremenek8e376772011-02-14 17:59:20 +0000533bool
Ted Kremenek1d26f482011-10-24 01:32:45 +0000534IdempotentOperationChecker::pathWasCompletelyAnalyzed(AnalysisDeclContext *AC,
Ted Kremenek8e376772011-02-14 17:59:20 +0000535 const CFGBlock *CB,
Ted Kremenek8e376772011-02-14 17:59:20 +0000536 const CoreEngine &CE) {
Ted Kremenekb5318912011-02-15 02:20:03 +0000537
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000538 CFGReverseBlockReachabilityAnalysis *CRA = AC->getCFGReachablityAnalysis();
Ted Kremenek8e376772011-02-14 17:59:20 +0000539
Tom Careb0627952010-09-09 02:04:52 +0000540 // Test for reachability from any aborted blocks to this block
Ted Kremenek422ab7a2011-04-02 02:56:23 +0000541 typedef CoreEngine::BlocksExhausted::const_iterator ExhaustedIterator;
542 for (ExhaustedIterator I = CE.blocks_exhausted_begin(),
543 E = CE.blocks_exhausted_end(); I != E; ++I) {
Tom Carea7a8a452010-08-12 22:45:47 +0000544 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000545
Tom Carea7a8a452010-08-12 22:45:47 +0000546 // The destination block on the BlockEdge is the first block that was not
Tom Careb0627952010-09-09 02:04:52 +0000547 // analyzed. If we can reach this block from the aborted block, then this
548 // block was not completely analyzed.
Ted Kremeneke8350c62011-02-14 17:59:23 +0000549 //
550 // Also explicitly check if the current block is the destination block.
551 // While technically reachable, it means we aborted the analysis on
552 // a path that included that block.
553 const CFGBlock *destBlock = BE.getDst();
554 if (destBlock == CB || CRA->isReachable(destBlock, CB))
Tom Carea7a8a452010-08-12 22:45:47 +0000555 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000556 }
Ted Kremenek422ab7a2011-04-02 02:56:23 +0000557
558 // Test for reachability from blocks we just gave up on.
559 typedef CoreEngine::BlocksAborted::const_iterator AbortedIterator;
560 for (AbortedIterator I = CE.blocks_aborted_begin(),
561 E = CE.blocks_aborted_end(); I != E; ++I) {
562 const CFGBlock *destBlock = I->first;
563 if (destBlock == CB || CRA->isReachable(destBlock, CB))
564 return false;
565 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000566
567 // For the items still on the worklist, see if they are in blocks that
568 // can eventually reach 'CB'.
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000569 class VisitWL : public WorkList::Visitor {
Ted Kremenek33d46262010-11-13 05:04:52 +0000570 const CFGStmtMap *CBM;
571 const CFGBlock *TargetBlock;
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000572 CFGReverseBlockReachabilityAnalysis &CRA;
Ted Kremenek33d46262010-11-13 05:04:52 +0000573 public:
574 VisitWL(const CFGStmtMap *cbm, const CFGBlock *targetBlock,
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000575 CFGReverseBlockReachabilityAnalysis &cra)
Ted Kremenek33d46262010-11-13 05:04:52 +0000576 : CBM(cbm), TargetBlock(targetBlock), CRA(cra) {}
Ted Kremenek55825aa2011-01-11 02:34:50 +0000577 virtual bool visit(const WorkListUnit &U) {
Ted Kremenek33d46262010-11-13 05:04:52 +0000578 ProgramPoint P = U.getNode()->getLocation();
579 const CFGBlock *B = 0;
580 if (StmtPoint *SP = dyn_cast<StmtPoint>(&P)) {
581 B = CBM->getBlock(SP->getStmt());
582 }
Ted Kremeneked023662010-11-13 05:12:26 +0000583 else if (BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
584 B = BE->getDst();
585 }
586 else if (BlockEntrance *BEnt = dyn_cast<BlockEntrance>(&P)) {
587 B = BEnt->getBlock();
588 }
589 else if (BlockExit *BExit = dyn_cast<BlockExit>(&P)) {
590 B = BExit->getBlock();
591 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000592 if (!B)
593 return true;
594
Ted Kremenek1212f802011-04-12 21:47:02 +0000595 return B == TargetBlock || CRA.isReachable(B, TargetBlock);
Ted Kremenek33d46262010-11-13 05:04:52 +0000596 }
597 };
Ted Kremenek42461ee2011-02-23 01:51:59 +0000598 VisitWL visitWL(AC->getCFGStmtMap(), CB, *CRA);
Ted Kremenek33d46262010-11-13 05:04:52 +0000599 // Were there any items in the worklist that could potentially reach
600 // this block?
Ted Kremenek55825aa2011-01-11 02:34:50 +0000601 if (CE.getWorkList()->visitItemsInWorkList(visitWL))
Ted Kremenek33d46262010-11-13 05:04:52 +0000602 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000603
Tom Careb0627952010-09-09 02:04:52 +0000604 // Verify that this block is reachable from the entry block
Ted Kremenek42461ee2011-02-23 01:51:59 +0000605 if (!CRA->isReachable(&AC->getCFG()->getEntry(), CB))
Tom Careb0627952010-09-09 02:04:52 +0000606 return false;
607
Tom Carea7a8a452010-08-12 22:45:47 +0000608 // If we get to this point, there is no connection to the entry block or an
609 // aborted block. This path is unreachable and we can report the error.
610 return true;
611}
612
613// Recursive function that determines whether an expression contains any element
614// that varies. This could be due to a compile-time constant like sizeof. An
615// expression may also involve a variable that behaves like a constant. The
616// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000617bool IdempotentOperationChecker::CanVary(const Expr *Ex,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000618 AnalysisDeclContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000619 // Parentheses and casts are irrelevant here
620 Ex = Ex->IgnoreParenCasts();
621
622 if (Ex->getLocStart().isMacroID())
623 return false;
624
625 switch (Ex->getStmtClass()) {
626 // Trivially true cases
627 case Stmt::ArraySubscriptExprClass:
628 case Stmt::MemberExprClass:
629 case Stmt::StmtExprClass:
630 case Stmt::CallExprClass:
631 case Stmt::VAArgExprClass:
632 case Stmt::ShuffleVectorExprClass:
633 return true;
634 default:
635 return true;
636
637 // Trivially false cases
638 case Stmt::IntegerLiteralClass:
639 case Stmt::CharacterLiteralClass:
640 case Stmt::FloatingLiteralClass:
641 case Stmt::PredefinedExprClass:
642 case Stmt::ImaginaryLiteralClass:
643 case Stmt::StringLiteralClass:
644 case Stmt::OffsetOfExprClass:
645 case Stmt::CompoundLiteralExprClass:
646 case Stmt::AddrLabelExprClass:
Francois Pichetf1872372010-12-08 22:35:30 +0000647 case Stmt::BinaryTypeTraitExprClass:
Tom Carea7a8a452010-08-12 22:45:47 +0000648 case Stmt::GNUNullExprClass:
649 case Stmt::InitListExprClass:
650 case Stmt::DesignatedInitExprClass:
651 case Stmt::BlockExprClass:
652 case Stmt::BlockDeclRefExprClass:
653 return false;
654
655 // Cases requiring custom logic
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000656 case Stmt::UnaryExprOrTypeTraitExprClass: {
657 const UnaryExprOrTypeTraitExpr *SE =
658 cast<const UnaryExprOrTypeTraitExpr>(Ex);
659 if (SE->getKind() != UETT_SizeOf)
Tom Carea7a8a452010-08-12 22:45:47 +0000660 return false;
661 return SE->getTypeOfArgument()->isVariableArrayType();
662 }
663 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000664 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000665 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000666
667 // The next cases require recursion for subexpressions
668 case Stmt::BinaryOperatorClass: {
669 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Ted Kremenek74faec22010-10-29 01:06:54 +0000670
671 // Exclude cases involving pointer arithmetic. These are usually
672 // false positives.
673 if (B->getOpcode() == BO_Sub || B->getOpcode() == BO_Add)
674 if (B->getLHS()->getType()->getAs<PointerType>())
675 return false;
676
Tom Care245adab2010-08-18 21:17:24 +0000677 return CanVary(B->getRHS(), AC)
678 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000679 }
680 case Stmt::UnaryOperatorClass: {
681 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000682 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000683 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000684 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000685 return false;
686 default:
Tom Care245adab2010-08-18 21:17:24 +0000687 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000688 }
689 }
690 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000691 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
692 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000693 case Stmt::ConditionalOperatorClass:
John McCall56ca35d2011-02-17 10:25:35 +0000694 case Stmt::BinaryConditionalOperatorClass:
695 return CanVary(cast<AbstractConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000696 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000697}
698
Tom Care245adab2010-08-18 21:17:24 +0000699// Returns true if a DeclRefExpr is or behaves like a constant.
700bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000701 const DeclRefExpr *DR,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000702 AnalysisDeclContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000703 // Check if the type of the Decl is const-qualified
704 if (DR->getType().isConstQualified())
705 return true;
706
Tom Care50e8ac22010-08-16 21:43:52 +0000707 // Check for an enum
708 if (isa<EnumConstantDecl>(DR->getDecl()))
709 return true;
710
Tom Caredb34ab72010-08-23 19:51:57 +0000711 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
712 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000713 return true;
714
Tom Caredb34ab72010-08-23 19:51:57 +0000715 // Check if the Decl behaves like a constant. This check also takes care of
716 // static variables, which can only change between function calls if they are
717 // modified in the AST.
718 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
719 if (PCA->isPseudoConstant(VD))
720 return true;
721
722 return false;
723}
724
725// Recursively find any substatements containing VarDecl's with storage other
726// than local
727bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
728 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
729
730 if (DR)
731 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
732 if (!VD->hasLocalStorage())
733 return true;
734
735 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
736 ++I)
737 if (const Stmt *child = *I)
738 if (containsNonLocalVarDecl(child))
739 return true;
740
Tom Care50e8ac22010-08-16 21:43:52 +0000741 return false;
742}
Tom Careb0627952010-09-09 02:04:52 +0000743
Tom Careb0627952010-09-09 02:04:52 +0000744
Argyrios Kyrtzidisecc4d332011-02-23 21:04:44 +0000745void ento::registerIdempotentOperationChecker(CheckerManager &mgr) {
746 mgr.registerChecker<IdempotentOperationChecker>();
747}