blob: 171b39efe255ea406f5d99f4be0b4ec62eabbcc6 [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 Kyrtzidis695fb502011-02-17 21:39:17 +000049#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000050#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
51#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
52#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
53#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h"
54#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
55#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000056#include "clang/AST/Stmt.h"
57#include "llvm/ADT/DenseMap.h"
Tom Carea7a8a452010-08-12 22:45:47 +000058#include "llvm/ADT/SmallSet.h"
Ted Kremenek8e376772011-02-14 17:59:20 +000059#include "llvm/ADT/BitVector.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000060#include "llvm/Support/ErrorHandling.h"
Tom Carea7a8a452010-08-12 22:45:47 +000061#include <deque>
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
68 : public CheckerVisitor<IdempotentOperationChecker> {
Tom Careb0627952010-09-09 02:04:52 +000069public:
70 static void *getTag();
71 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
72 void PostVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000073 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, ExprEngine &Eng);
Tom Careb0627952010-09-09 02:04:52 +000074
75private:
76 // Our assumption about a particular operation.
77 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
78 RHSis0 };
79
80 void UpdateAssumption(Assumption &A, const Assumption &New);
81
82 // False positive reduction methods
83 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
84 static bool isUnused(const Expr *E, AnalysisContext *AC);
85 static bool isTruncationExtensionAssignment(const Expr *LHS,
86 const Expr *RHS);
Ted Kremenek42461ee2011-02-23 01:51:59 +000087 bool pathWasCompletelyAnalyzed(AnalysisContext *AC,
Tom Careb0627952010-09-09 02:04:52 +000088 const CFGBlock *CB,
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000089 const CoreEngine &CE);
Tom Careb0627952010-09-09 02:04:52 +000090 static bool CanVary(const Expr *Ex,
91 AnalysisContext *AC);
92 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
93 AnalysisContext *AC);
94 static bool containsNonLocalVarDecl(const Stmt *S);
Tom Careb0627952010-09-09 02:04:52 +000095
96 // Hash table and related data structures
97 struct BinaryOperatorData {
98 BinaryOperatorData() : assumption(Possible), analysisContext(0) {}
99
100 Assumption assumption;
101 AnalysisContext *analysisContext;
102 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
103 // BinaryOperator
104 };
105 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
106 AssumptionMap;
107 AssumptionMap hash;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000108};
109}
110
111void *IdempotentOperationChecker::getTag() {
112 static int x = 0;
113 return &x;
114}
115
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +0000116static void RegisterIdempotentOperationChecker(ExprEngine &Eng) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000117 Eng.registerCheck(new IdempotentOperationChecker());
118}
119
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +0000120void ento::registerIdempotentOperationChecker(CheckerManager &mgr) {
121 mgr.addCheckerRegisterFunction(RegisterIdempotentOperationChecker);
122}
123
Tom Caredb2fa8a2010-07-06 21:43:29 +0000124void IdempotentOperationChecker::PreVisitBinaryOperator(
125 CheckerContext &C,
126 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000127 // Find or create an entry in the hash for this BinaryOperator instance.
128 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000129 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
130 // been created yet.
131 BinaryOperatorData &Data = hash[B];
132 Assumption &A = Data.assumption;
Tom Care245adab2010-08-18 21:17:24 +0000133 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care2bbbe502010-09-02 23:30:22 +0000134 Data.analysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000135
136 // If we already have visited this node on a path that does not contain an
137 // idempotent operation, return immediately.
138 if (A == Impossible)
139 return;
140
Tom Carea7a8a452010-08-12 22:45:47 +0000141 // Retrieve both sides of the operator and determine if they can vary (which
142 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000143 const Expr *LHS = B->getLHS();
144 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000145
Tom Caredb34ab72010-08-23 19:51:57 +0000146 // At this stage we can calculate whether each side contains a false positive
147 // that applies to all operators. We only need to calculate this the first
148 // time.
149 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000150 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000151 // An expression contains a false positive if it can't vary, or if it
152 // contains a known false positive VarDecl.
153 LHSContainsFalsePositive = !CanVary(LHS, AC)
154 || containsNonLocalVarDecl(LHS);
155 RHSContainsFalsePositive = !CanVary(RHS, AC)
156 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000157 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000158
159 const GRState *state = C.getState();
160
161 SVal LHSVal = state->getSVal(LHS);
162 SVal RHSVal = state->getSVal(RHS);
163
164 // If either value is unknown, we can't be 100% sure of all paths.
165 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
166 A = Impossible;
167 return;
168 }
169 BinaryOperator::Opcode Op = B->getOpcode();
170
171 // Dereference the LHS SVal if this is an assign operation
172 switch (Op) {
173 default:
174 break;
175
176 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000177 case BO_AddAssign:
178 case BO_SubAssign:
179 case BO_MulAssign:
180 case BO_DivAssign:
181 case BO_AndAssign:
182 case BO_OrAssign:
183 case BO_XorAssign:
184 case BO_ShlAssign:
185 case BO_ShrAssign:
186 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000187 // Assign statements have one extra level of indirection
188 if (!isa<Loc>(LHSVal)) {
189 A = Impossible;
190 return;
191 }
Ted Kremenek96ebad62010-09-09 07:13:00 +0000192 LHSVal = state->getSVal(cast<Loc>(LHSVal), LHS->getType());
Tom Caredb2fa8a2010-07-06 21:43:29 +0000193 }
194
195
196 // We now check for various cases which result in an idempotent operation.
197
198 // x op x
199 switch (Op) {
200 default:
201 break; // We don't care about any other operators.
202
203 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000204 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000205 // x Assign x can be used to silence unused variable warnings intentionally.
206 // If this is a self assignment and the variable is referenced elsewhere,
Tom Care84c24ed2010-09-07 20:27:56 +0000207 // and the assignment is not a truncation or extension, then it is a false
208 // positive.
Tom Care6216dc02010-08-30 19:25:43 +0000209 if (isSelfAssign(LHS, RHS)) {
Tom Care84c24ed2010-09-07 20:27:56 +0000210 if (!isUnused(LHS, AC) && !isTruncationExtensionAssignment(LHS, RHS)) {
Tom Care6216dc02010-08-30 19:25:43 +0000211 UpdateAssumption(A, Equal);
212 return;
213 }
214 else {
215 A = Impossible;
216 return;
217 }
Tom Caredf4ca422010-07-16 20:41:41 +0000218 }
219
John McCall2de56d12010-08-25 11:45:40 +0000220 case BO_SubAssign:
221 case BO_DivAssign:
222 case BO_AndAssign:
223 case BO_OrAssign:
224 case BO_XorAssign:
225 case BO_Sub:
226 case BO_Div:
227 case BO_And:
228 case BO_Or:
229 case BO_Xor:
230 case BO_LOr:
231 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000232 case BO_EQ:
233 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000234 if (LHSVal != RHSVal || LHSContainsFalsePositive
235 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000236 break;
237 UpdateAssumption(A, Equal);
238 return;
239 }
240
241 // x op 1
242 switch (Op) {
243 default:
244 break; // We don't care about any other operators.
245
246 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000247 case BO_MulAssign:
248 case BO_DivAssign:
249 case BO_Mul:
250 case BO_Div:
251 case BO_LOr:
252 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000253 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000254 break;
255 UpdateAssumption(A, RHSis1);
256 return;
257 }
258
259 // 1 op x
260 switch (Op) {
261 default:
262 break; // We don't care about any other operators.
263
264 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000265 case BO_MulAssign:
266 case BO_Mul:
267 case BO_LOr:
268 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000269 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000270 break;
271 UpdateAssumption(A, LHSis1);
272 return;
273 }
274
275 // x op 0
276 switch (Op) {
277 default:
278 break; // We don't care about any other operators.
279
280 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000281 case BO_AddAssign:
282 case BO_SubAssign:
283 case BO_MulAssign:
284 case BO_AndAssign:
285 case BO_OrAssign:
286 case BO_XorAssign:
287 case BO_Add:
288 case BO_Sub:
289 case BO_Mul:
290 case BO_And:
291 case BO_Or:
292 case BO_Xor:
293 case BO_Shl:
294 case BO_Shr:
295 case BO_LOr:
296 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000297 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000298 break;
299 UpdateAssumption(A, RHSis0);
300 return;
301 }
302
303 // 0 op x
304 switch (Op) {
305 default:
306 break; // We don't care about any other operators.
307
308 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000309 //case BO_AddAssign: // Common false positive
310 case BO_SubAssign: // Check only if unsigned
311 case BO_MulAssign:
312 case BO_DivAssign:
313 case BO_AndAssign:
314 //case BO_OrAssign: // Common false positive
315 //case BO_XorAssign: // Common false positive
316 case BO_ShlAssign:
317 case BO_ShrAssign:
318 case BO_Add:
319 case BO_Sub:
320 case BO_Mul:
321 case BO_Div:
322 case BO_And:
323 case BO_Or:
324 case BO_Xor:
325 case BO_Shl:
326 case BO_Shr:
327 case BO_LOr:
328 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000329 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000330 break;
331 UpdateAssumption(A, LHSis0);
332 return;
333 }
334
335 // If we get to this point, there has been a valid use of this operation.
336 A = Impossible;
337}
338
Tom Care2bbbe502010-09-02 23:30:22 +0000339// At the post visit stage, the predecessor ExplodedNode will be the
340// BinaryOperator that was just created. We use this hook to collect the
341// ExplodedNode.
342void IdempotentOperationChecker::PostVisitBinaryOperator(
343 CheckerContext &C,
344 const BinaryOperator *B) {
345 // Add the ExplodedNode we just visited
346 BinaryOperatorData &Data = hash[B];
Ted Kremenek020c3742011-02-12 18:50:03 +0000347
348 const Stmt *predStmt
349 = cast<StmtPoint>(C.getPredecessor()->getLocation()).getStmt();
350
351 // Ignore implicit calls to setters.
352 if (isa<ObjCPropertyRefExpr>(predStmt))
353 return;
354
355 assert(isa<BinaryOperator>(predStmt));
Tom Care2bbbe502010-09-02 23:30:22 +0000356 Data.explodedNodes.Add(C.getPredecessor());
357}
358
Tom Caredb2fa8a2010-07-06 21:43:29 +0000359void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000360 BugReporter &BR,
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000361 ExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000362 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000363 // Iterate over the hash to see if we have any paths with definite
364 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000365 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
366 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000367 const BinaryOperatorData &Data = i->second;
368 const Assumption &A = Data.assumption;
369 AnalysisContext *AC = Data.analysisContext;
370 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000371
Tom Carea7a8a452010-08-12 22:45:47 +0000372 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000373
Tom Carea7a8a452010-08-12 22:45:47 +0000374 if (A == Impossible)
375 continue;
376
377 // If the analyzer did not finish, check to see if we can still emit this
378 // warning
379 if (Eng.hasWorkRemaining()) {
Tom Carea7a8a452010-08-12 22:45:47 +0000380 // If we can trace back
Ted Kremenek42461ee2011-02-23 01:51:59 +0000381 if (!pathWasCompletelyAnalyzed(AC,
382 AC->getCFGStmtMap()->getBlock(B),
Tom Carea7a8a452010-08-12 22:45:47 +0000383 Eng.getCoreEngine()))
384 continue;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000385 }
Tom Carea7a8a452010-08-12 22:45:47 +0000386
Tom Care2bbbe502010-09-02 23:30:22 +0000387 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000388 llvm::SmallString<128> buf;
389 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000390 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000391 switch (A) {
392 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000393 LHSRelevant = true;
394 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000395 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000396 os << "Assigned value is always the same as the existing value";
397 else
398 os << "Both operands to '" << B->getOpcodeStr()
399 << "' always have the same value";
400 break;
401 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000402 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000403 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
404 break;
405 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000406 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000407 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
408 break;
409 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000410 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000411 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
412 break;
413 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000414 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000415 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
416 break;
417 case Possible:
418 llvm_unreachable("Operation was never marked with an assumption");
419 case Impossible:
420 llvm_unreachable(0);
421 }
422
Tom Care2bbbe502010-09-02 23:30:22 +0000423 // Add a report for each ExplodedNode
424 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
425 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
426
427 // Add source ranges and visitor hooks
428 if (LHSRelevant) {
429 const Expr *LHS = i->first->getLHS();
430 report->addRange(LHS->getSourceRange());
431 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
432 }
433 if (RHSRelevant) {
434 const Expr *RHS = i->first->getRHS();
435 report->addRange(i->first->getRHS()->getSourceRange());
436 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
437 }
438
439 BR.EmitReport(report);
440 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000441 }
442}
443
444// Updates the current assumption given the new assumption
445inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
446 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000447// If the assumption is the same, there is nothing to do
448 if (A == New)
449 return;
450
Tom Caredb2fa8a2010-07-06 21:43:29 +0000451 switch (A) {
452 // If we don't currently have an assumption, set it
453 case Possible:
454 A = New;
455 return;
456
457 // If we have determined that a valid state happened, ignore the new
458 // assumption.
459 case Impossible:
460 return;
461
462 // Any other case means that we had a different assumption last time. We don't
463 // currently support mixing assumptions for diagnostic reasons, so we set
464 // our assumption to be impossible.
465 default:
466 A = Impossible;
467 return;
468 }
469}
470
Tom Care6216dc02010-08-30 19:25:43 +0000471// Check for a statement where a variable is self assigned to possibly avoid an
472// unused variable warning.
473bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000474 LHS = LHS->IgnoreParenCasts();
475 RHS = RHS->IgnoreParenCasts();
476
477 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
478 if (!LHS_DR)
479 return false;
480
Tom Careef52bcb2010-08-24 21:09:07 +0000481 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
482 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000483 return false;
484
485 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
486 if (!RHS_DR)
487 return false;
488
Tom Careef52bcb2010-08-24 21:09:07 +0000489 if (VD != RHS_DR->getDecl())
490 return false;
491
Tom Care6216dc02010-08-30 19:25:43 +0000492 return true;
493}
494
495// Returns true if the Expr points to a VarDecl that is not read anywhere
496// outside of self-assignments.
497bool IdempotentOperationChecker::isUnused(const Expr *E,
498 AnalysisContext *AC) {
499 if (!E)
500 return false;
501
502 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
503 if (!DR)
504 return false;
505
506 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
507 if (!VD)
508 return false;
509
Tom Careef52bcb2010-08-24 21:09:07 +0000510 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
511 return false;
512
513 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000514}
515
516// Check for self casts truncating/extending a variable
517bool IdempotentOperationChecker::isTruncationExtensionAssignment(
518 const Expr *LHS,
519 const Expr *RHS) {
520
521 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
522 if (!LHS_DR)
523 return false;
524
525 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
526 if (!VD)
527 return false;
528
529 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
530 if (!RHS_DR)
531 return false;
532
533 if (VD != RHS_DR->getDecl())
534 return false;
535
John McCallf6a16482010-12-04 03:47:34 +0000536 return dyn_cast<DeclRefExpr>(RHS->IgnoreParenLValueCasts()) == NULL;
Tom Caredf4ca422010-07-16 20:41:41 +0000537}
538
Tom Carea7a8a452010-08-12 22:45:47 +0000539// Returns false if a path to this block was not completely analyzed, or true
540// otherwise.
Ted Kremenek8e376772011-02-14 17:59:20 +0000541bool
Ted Kremenek42461ee2011-02-23 01:51:59 +0000542IdempotentOperationChecker::pathWasCompletelyAnalyzed(AnalysisContext *AC,
Ted Kremenek8e376772011-02-14 17:59:20 +0000543 const CFGBlock *CB,
Ted Kremenek8e376772011-02-14 17:59:20 +0000544 const CoreEngine &CE) {
Ted Kremenekb5318912011-02-15 02:20:03 +0000545
Ted Kremenek42461ee2011-02-23 01:51:59 +0000546 CFGReachabilityAnalysis *CRA = AC->getCFGReachablityAnalysis();
Ted Kremenek8e376772011-02-14 17:59:20 +0000547
Tom Careb0627952010-09-09 02:04:52 +0000548 // Test for reachability from any aborted blocks to this block
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000549 typedef CoreEngine::BlocksAborted::const_iterator AbortedIterator;
Tom Carea7a8a452010-08-12 22:45:47 +0000550 for (AbortedIterator I = CE.blocks_aborted_begin(),
551 E = CE.blocks_aborted_end(); I != E; ++I) {
552 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000553
Tom Carea7a8a452010-08-12 22:45:47 +0000554 // The destination block on the BlockEdge is the first block that was not
Tom Careb0627952010-09-09 02:04:52 +0000555 // analyzed. If we can reach this block from the aborted block, then this
556 // block was not completely analyzed.
Ted Kremeneke8350c62011-02-14 17:59:23 +0000557 //
558 // Also explicitly check if the current block is the destination block.
559 // While technically reachable, it means we aborted the analysis on
560 // a path that included that block.
561 const CFGBlock *destBlock = BE.getDst();
562 if (destBlock == CB || CRA->isReachable(destBlock, CB))
Tom Carea7a8a452010-08-12 22:45:47 +0000563 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000564 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000565
566 // For the items still on the worklist, see if they are in blocks that
567 // can eventually reach 'CB'.
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000568 class VisitWL : public WorkList::Visitor {
Ted Kremenek33d46262010-11-13 05:04:52 +0000569 const CFGStmtMap *CBM;
570 const CFGBlock *TargetBlock;
571 CFGReachabilityAnalysis &CRA;
572 public:
573 VisitWL(const CFGStmtMap *cbm, const CFGBlock *targetBlock,
574 CFGReachabilityAnalysis &cra)
575 : CBM(cbm), TargetBlock(targetBlock), CRA(cra) {}
Ted Kremenek55825aa2011-01-11 02:34:50 +0000576 virtual bool visit(const WorkListUnit &U) {
Ted Kremenek33d46262010-11-13 05:04:52 +0000577 ProgramPoint P = U.getNode()->getLocation();
578 const CFGBlock *B = 0;
579 if (StmtPoint *SP = dyn_cast<StmtPoint>(&P)) {
580 B = CBM->getBlock(SP->getStmt());
581 }
Ted Kremeneked023662010-11-13 05:12:26 +0000582 else if (BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
583 B = BE->getDst();
584 }
585 else if (BlockEntrance *BEnt = dyn_cast<BlockEntrance>(&P)) {
586 B = BEnt->getBlock();
587 }
588 else if (BlockExit *BExit = dyn_cast<BlockExit>(&P)) {
589 B = BExit->getBlock();
590 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000591 if (!B)
592 return true;
593
594 return CRA.isReachable(B, TargetBlock);
595 }
596 };
Ted Kremenek42461ee2011-02-23 01:51:59 +0000597 VisitWL visitWL(AC->getCFGStmtMap(), CB, *CRA);
Ted Kremenek33d46262010-11-13 05:04:52 +0000598 // Were there any items in the worklist that could potentially reach
599 // this block?
Ted Kremenek55825aa2011-01-11 02:34:50 +0000600 if (CE.getWorkList()->visitItemsInWorkList(visitWL))
Ted Kremenek33d46262010-11-13 05:04:52 +0000601 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000602
Tom Careb0627952010-09-09 02:04:52 +0000603 // Verify that this block is reachable from the entry block
Ted Kremenek42461ee2011-02-23 01:51:59 +0000604 if (!CRA->isReachable(&AC->getCFG()->getEntry(), CB))
Tom Careb0627952010-09-09 02:04:52 +0000605 return false;
606
Tom Carea7a8a452010-08-12 22:45:47 +0000607 // If we get to this point, there is no connection to the entry block or an
608 // aborted block. This path is unreachable and we can report the error.
609 return true;
610}
611
612// Recursive function that determines whether an expression contains any element
613// that varies. This could be due to a compile-time constant like sizeof. An
614// expression may also involve a variable that behaves like a constant. The
615// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000616bool IdempotentOperationChecker::CanVary(const Expr *Ex,
617 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000618 // Parentheses and casts are irrelevant here
619 Ex = Ex->IgnoreParenCasts();
620
621 if (Ex->getLocStart().isMacroID())
622 return false;
623
624 switch (Ex->getStmtClass()) {
625 // Trivially true cases
626 case Stmt::ArraySubscriptExprClass:
627 case Stmt::MemberExprClass:
628 case Stmt::StmtExprClass:
629 case Stmt::CallExprClass:
630 case Stmt::VAArgExprClass:
631 case Stmt::ShuffleVectorExprClass:
632 return true;
633 default:
634 return true;
635
636 // Trivially false cases
637 case Stmt::IntegerLiteralClass:
638 case Stmt::CharacterLiteralClass:
639 case Stmt::FloatingLiteralClass:
640 case Stmt::PredefinedExprClass:
641 case Stmt::ImaginaryLiteralClass:
642 case Stmt::StringLiteralClass:
643 case Stmt::OffsetOfExprClass:
644 case Stmt::CompoundLiteralExprClass:
645 case Stmt::AddrLabelExprClass:
Francois Pichetf1872372010-12-08 22:35:30 +0000646 case Stmt::BinaryTypeTraitExprClass:
Tom Carea7a8a452010-08-12 22:45:47 +0000647 case Stmt::GNUNullExprClass:
648 case Stmt::InitListExprClass:
649 case Stmt::DesignatedInitExprClass:
650 case Stmt::BlockExprClass:
651 case Stmt::BlockDeclRefExprClass:
652 return false;
653
654 // Cases requiring custom logic
655 case Stmt::SizeOfAlignOfExprClass: {
656 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
657 if (!SE->isSizeOf())
658 return false;
659 return SE->getTypeOfArgument()->isVariableArrayType();
660 }
661 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000662 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000663 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000664
665 // The next cases require recursion for subexpressions
666 case Stmt::BinaryOperatorClass: {
667 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Ted Kremenek74faec22010-10-29 01:06:54 +0000668
669 // Exclude cases involving pointer arithmetic. These are usually
670 // false positives.
671 if (B->getOpcode() == BO_Sub || B->getOpcode() == BO_Add)
672 if (B->getLHS()->getType()->getAs<PointerType>())
673 return false;
674
Tom Care245adab2010-08-18 21:17:24 +0000675 return CanVary(B->getRHS(), AC)
676 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000677 }
678 case Stmt::UnaryOperatorClass: {
679 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000680 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000681 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000682 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000683 return false;
684 default:
Tom Care245adab2010-08-18 21:17:24 +0000685 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000686 }
687 }
688 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000689 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
690 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000691 case Stmt::ConditionalOperatorClass:
John McCall56ca35d2011-02-17 10:25:35 +0000692 case Stmt::BinaryConditionalOperatorClass:
693 return CanVary(cast<AbstractConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000694 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000695}
696
Tom Care245adab2010-08-18 21:17:24 +0000697// Returns true if a DeclRefExpr is or behaves like a constant.
698bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000699 const DeclRefExpr *DR,
700 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000701 // Check if the type of the Decl is const-qualified
702 if (DR->getType().isConstQualified())
703 return true;
704
Tom Care50e8ac22010-08-16 21:43:52 +0000705 // Check for an enum
706 if (isa<EnumConstantDecl>(DR->getDecl()))
707 return true;
708
Tom Caredb34ab72010-08-23 19:51:57 +0000709 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
710 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000711 return true;
712
Tom Caredb34ab72010-08-23 19:51:57 +0000713 // Check if the Decl behaves like a constant. This check also takes care of
714 // static variables, which can only change between function calls if they are
715 // modified in the AST.
716 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
717 if (PCA->isPseudoConstant(VD))
718 return true;
719
720 return false;
721}
722
723// Recursively find any substatements containing VarDecl's with storage other
724// than local
725bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
726 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
727
728 if (DR)
729 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
730 if (!VD->hasLocalStorage())
731 return true;
732
733 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
734 ++I)
735 if (const Stmt *child = *I)
736 if (containsNonLocalVarDecl(child))
737 return true;
738
Tom Care50e8ac22010-08-16 21:43:52 +0000739 return false;
740}
Tom Careb0627952010-09-09 02:04:52 +0000741
Tom Careb0627952010-09-09 02:04:52 +0000742
Tom Careb0627952010-09-09 02:04:52 +0000743
Tom Careb0627952010-09-09 02:04:52 +0000744