blob: 6411c790ef7c8f47127be37f9759f519b6b953ba [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
Tom Care1fafd1d2010-08-06 22:23:07 +000045#include "GRExprEngineExperimentalChecks.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"
Tom Care2bbbe502010-09-02 23:30:22 +000048#include "clang/Checker/BugReporter/BugReporter.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000049#include "clang/Checker/BugReporter/BugType.h"
Tom Carea9fbf5b2010-07-27 23:26:07 +000050#include "clang/Checker/PathSensitive/CheckerHelpers.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000051#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Tom Carea7a8a452010-08-12 22:45:47 +000052#include "clang/Checker/PathSensitive/GRCoreEngine.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000053#include "clang/Checker/PathSensitive/SVals.h"
54#include "clang/AST/Stmt.h"
55#include "llvm/ADT/DenseMap.h"
Tom Carea7a8a452010-08-12 22:45:47 +000056#include "llvm/ADT/SmallSet.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000057#include "llvm/Support/ErrorHandling.h"
Tom Carea7a8a452010-08-12 22:45:47 +000058#include <deque>
Tom Caredb2fa8a2010-07-06 21:43:29 +000059
60using namespace clang;
61
62namespace {
63class IdempotentOperationChecker
64 : public CheckerVisitor<IdempotentOperationChecker> {
65 public:
66 static void *getTag();
67 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Tom Care2bbbe502010-09-02 23:30:22 +000068 void PostVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Tom Carebc42c532010-08-03 01:55:07 +000069 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, GRExprEngine &Eng);
Tom Caredb2fa8a2010-07-06 21:43:29 +000070
71 private:
72 // Our assumption about a particular operation.
Ted Kremenekfe97fa12010-08-02 20:33:02 +000073 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
Tom Caredb2fa8a2010-07-06 21:43:29 +000074 RHSis0 };
75
76 void UpdateAssumption(Assumption &A, const Assumption &New);
77
Tom Care245adab2010-08-18 21:17:24 +000078 // False positive reduction methods
Tom Care6216dc02010-08-30 19:25:43 +000079 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
80 static bool isUnused(const Expr *E, AnalysisContext *AC);
Chris Lattnerfae96222010-09-03 04:34:38 +000081 //static bool isTruncationExtensionAssignment(const Expr *LHS,
82 // const Expr *RHS);
Tom Carea7a8a452010-08-12 22:45:47 +000083 static bool PathWasCompletelyAnalyzed(const CFG *C,
84 const CFGBlock *CB,
85 const GRCoreEngine &CE);
Tom Care6216dc02010-08-30 19:25:43 +000086 static bool CanVary(const Expr *Ex,
87 AnalysisContext *AC);
Tom Care245adab2010-08-18 21:17:24 +000088 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
89 AnalysisContext *AC);
Tom Caredb34ab72010-08-23 19:51:57 +000090 static bool containsNonLocalVarDecl(const Stmt *S);
Tom Caredb2fa8a2010-07-06 21:43:29 +000091
Tom Care2bbbe502010-09-02 23:30:22 +000092 // Hash table and related data structures
93 struct BinaryOperatorData {
94 BinaryOperatorData() : assumption(Possible), analysisContext(0) {}
95
96 Assumption assumption;
97 AnalysisContext *analysisContext;
98 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
99 // BinaryOperator
100 };
101 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
102 AssumptionMap;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000103 AssumptionMap hash;
104};
105}
106
107void *IdempotentOperationChecker::getTag() {
108 static int x = 0;
109 return &x;
110}
111
112void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
113 Eng.registerCheck(new IdempotentOperationChecker());
114}
115
116void IdempotentOperationChecker::PreVisitBinaryOperator(
117 CheckerContext &C,
118 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000119 // Find or create an entry in the hash for this BinaryOperator instance.
120 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000121 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
122 // been created yet.
123 BinaryOperatorData &Data = hash[B];
124 Assumption &A = Data.assumption;
Tom Care245adab2010-08-18 21:17:24 +0000125 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care2bbbe502010-09-02 23:30:22 +0000126 Data.analysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000127
128 // If we already have visited this node on a path that does not contain an
129 // idempotent operation, return immediately.
130 if (A == Impossible)
131 return;
132
Tom Carea7a8a452010-08-12 22:45:47 +0000133 // Retrieve both sides of the operator and determine if they can vary (which
134 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000135 const Expr *LHS = B->getLHS();
136 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000137
Tom Caredb34ab72010-08-23 19:51:57 +0000138 // At this stage we can calculate whether each side contains a false positive
139 // that applies to all operators. We only need to calculate this the first
140 // time.
141 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000142 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000143 // An expression contains a false positive if it can't vary, or if it
144 // contains a known false positive VarDecl.
145 LHSContainsFalsePositive = !CanVary(LHS, AC)
146 || containsNonLocalVarDecl(LHS);
147 RHSContainsFalsePositive = !CanVary(RHS, AC)
148 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000149 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000150
151 const GRState *state = C.getState();
152
153 SVal LHSVal = state->getSVal(LHS);
154 SVal RHSVal = state->getSVal(RHS);
155
156 // If either value is unknown, we can't be 100% sure of all paths.
157 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
158 A = Impossible;
159 return;
160 }
161 BinaryOperator::Opcode Op = B->getOpcode();
162
163 // Dereference the LHS SVal if this is an assign operation
164 switch (Op) {
165 default:
166 break;
167
168 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000169 case BO_AddAssign:
170 case BO_SubAssign:
171 case BO_MulAssign:
172 case BO_DivAssign:
173 case BO_AndAssign:
174 case BO_OrAssign:
175 case BO_XorAssign:
176 case BO_ShlAssign:
177 case BO_ShrAssign:
178 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000179 // Assign statements have one extra level of indirection
180 if (!isa<Loc>(LHSVal)) {
181 A = Impossible;
182 return;
183 }
184 LHSVal = state->getSVal(cast<Loc>(LHSVal));
185 }
186
187
188 // We now check for various cases which result in an idempotent operation.
189
190 // x op x
191 switch (Op) {
192 default:
193 break; // We don't care about any other operators.
194
195 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000196 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000197 // x Assign x can be used to silence unused variable warnings intentionally.
198 // If this is a self assignment and the variable is referenced elsewhere,
199 // then it is a false positive.
200 if (isSelfAssign(LHS, RHS)) {
201 if (!isUnused(LHS, AC)) {
202 UpdateAssumption(A, Equal);
203 return;
204 }
205 else {
206 A = Impossible;
207 return;
208 }
Tom Caredf4ca422010-07-16 20:41:41 +0000209 }
210
John McCall2de56d12010-08-25 11:45:40 +0000211 case BO_SubAssign:
212 case BO_DivAssign:
213 case BO_AndAssign:
214 case BO_OrAssign:
215 case BO_XorAssign:
216 case BO_Sub:
217 case BO_Div:
218 case BO_And:
219 case BO_Or:
220 case BO_Xor:
221 case BO_LOr:
222 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000223 case BO_EQ:
224 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000225 if (LHSVal != RHSVal || LHSContainsFalsePositive
226 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000227 break;
228 UpdateAssumption(A, Equal);
229 return;
230 }
231
232 // x op 1
233 switch (Op) {
234 default:
235 break; // We don't care about any other operators.
236
237 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000238 case BO_MulAssign:
239 case BO_DivAssign:
240 case BO_Mul:
241 case BO_Div:
242 case BO_LOr:
243 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000244 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000245 break;
246 UpdateAssumption(A, RHSis1);
247 return;
248 }
249
250 // 1 op x
251 switch (Op) {
252 default:
253 break; // We don't care about any other operators.
254
255 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000256 case BO_MulAssign:
257 case BO_Mul:
258 case BO_LOr:
259 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000260 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000261 break;
262 UpdateAssumption(A, LHSis1);
263 return;
264 }
265
266 // x op 0
267 switch (Op) {
268 default:
269 break; // We don't care about any other operators.
270
271 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000272 case BO_AddAssign:
273 case BO_SubAssign:
274 case BO_MulAssign:
275 case BO_AndAssign:
276 case BO_OrAssign:
277 case BO_XorAssign:
278 case BO_Add:
279 case BO_Sub:
280 case BO_Mul:
281 case BO_And:
282 case BO_Or:
283 case BO_Xor:
284 case BO_Shl:
285 case BO_Shr:
286 case BO_LOr:
287 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000288 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000289 break;
290 UpdateAssumption(A, RHSis0);
291 return;
292 }
293
294 // 0 op x
295 switch (Op) {
296 default:
297 break; // We don't care about any other operators.
298
299 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000300 //case BO_AddAssign: // Common false positive
301 case BO_SubAssign: // Check only if unsigned
302 case BO_MulAssign:
303 case BO_DivAssign:
304 case BO_AndAssign:
305 //case BO_OrAssign: // Common false positive
306 //case BO_XorAssign: // Common false positive
307 case BO_ShlAssign:
308 case BO_ShrAssign:
309 case BO_Add:
310 case BO_Sub:
311 case BO_Mul:
312 case BO_Div:
313 case BO_And:
314 case BO_Or:
315 case BO_Xor:
316 case BO_Shl:
317 case BO_Shr:
318 case BO_LOr:
319 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000320 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000321 break;
322 UpdateAssumption(A, LHSis0);
323 return;
324 }
325
326 // If we get to this point, there has been a valid use of this operation.
327 A = Impossible;
328}
329
Tom Care2bbbe502010-09-02 23:30:22 +0000330// At the post visit stage, the predecessor ExplodedNode will be the
331// BinaryOperator that was just created. We use this hook to collect the
332// ExplodedNode.
333void IdempotentOperationChecker::PostVisitBinaryOperator(
334 CheckerContext &C,
335 const BinaryOperator *B) {
336 // Add the ExplodedNode we just visited
337 BinaryOperatorData &Data = hash[B];
338 Data.explodedNodes.Add(C.getPredecessor());
339}
340
Tom Caredb2fa8a2010-07-06 21:43:29 +0000341void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000342 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000343 GRExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000344 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000345 // Iterate over the hash to see if we have any paths with definite
346 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000347 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
348 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000349 const BinaryOperatorData &Data = i->second;
350 const Assumption &A = Data.assumption;
351 AnalysisContext *AC = Data.analysisContext;
352 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000353
Tom Carea7a8a452010-08-12 22:45:47 +0000354 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000355
Tom Carea7a8a452010-08-12 22:45:47 +0000356 if (A == Impossible)
357 continue;
358
359 // If the analyzer did not finish, check to see if we can still emit this
360 // warning
361 if (Eng.hasWorkRemaining()) {
362 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
363 &AC->getParentMap());
364
365 // If we can trace back
366 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
367 CBM->getBlock(B),
368 Eng.getCoreEngine()))
369 continue;
370
371 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000372 }
Tom Carea7a8a452010-08-12 22:45:47 +0000373
Tom Care2bbbe502010-09-02 23:30:22 +0000374 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000375 llvm::SmallString<128> buf;
376 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000377 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000378 switch (A) {
379 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000380 LHSRelevant = true;
381 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000382 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000383 os << "Assigned value is always the same as the existing value";
384 else
385 os << "Both operands to '" << B->getOpcodeStr()
386 << "' always have the same value";
387 break;
388 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000389 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000390 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
391 break;
392 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000393 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000394 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
395 break;
396 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000397 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000398 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
399 break;
400 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000401 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000402 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
403 break;
404 case Possible:
405 llvm_unreachable("Operation was never marked with an assumption");
406 case Impossible:
407 llvm_unreachable(0);
408 }
409
Tom Care2bbbe502010-09-02 23:30:22 +0000410 // Add a report for each ExplodedNode
411 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
412 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
413
414 // Add source ranges and visitor hooks
415 if (LHSRelevant) {
416 const Expr *LHS = i->first->getLHS();
417 report->addRange(LHS->getSourceRange());
418 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
419 }
420 if (RHSRelevant) {
421 const Expr *RHS = i->first->getRHS();
422 report->addRange(i->first->getRHS()->getSourceRange());
423 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
424 }
425
426 BR.EmitReport(report);
427 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000428 }
429}
430
431// Updates the current assumption given the new assumption
432inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
433 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000434// If the assumption is the same, there is nothing to do
435 if (A == New)
436 return;
437
Tom Caredb2fa8a2010-07-06 21:43:29 +0000438 switch (A) {
439 // If we don't currently have an assumption, set it
440 case Possible:
441 A = New;
442 return;
443
444 // If we have determined that a valid state happened, ignore the new
445 // assumption.
446 case Impossible:
447 return;
448
449 // Any other case means that we had a different assumption last time. We don't
450 // currently support mixing assumptions for diagnostic reasons, so we set
451 // our assumption to be impossible.
452 default:
453 A = Impossible;
454 return;
455 }
456}
457
Tom Care6216dc02010-08-30 19:25:43 +0000458// Check for a statement where a variable is self assigned to possibly avoid an
459// unused variable warning.
460bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000461 LHS = LHS->IgnoreParenCasts();
462 RHS = RHS->IgnoreParenCasts();
463
464 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
465 if (!LHS_DR)
466 return false;
467
Tom Careef52bcb2010-08-24 21:09:07 +0000468 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
469 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000470 return false;
471
472 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
473 if (!RHS_DR)
474 return false;
475
Tom Careef52bcb2010-08-24 21:09:07 +0000476 if (VD != RHS_DR->getDecl())
477 return false;
478
Tom Care6216dc02010-08-30 19:25:43 +0000479 return true;
480}
481
482// Returns true if the Expr points to a VarDecl that is not read anywhere
483// outside of self-assignments.
484bool IdempotentOperationChecker::isUnused(const Expr *E,
485 AnalysisContext *AC) {
486 if (!E)
487 return false;
488
489 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
490 if (!DR)
491 return false;
492
493 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
494 if (!VD)
495 return false;
496
Tom Careef52bcb2010-08-24 21:09:07 +0000497 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
498 return false;
499
500 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000501}
502
Chris Lattnerfae96222010-09-03 04:34:38 +0000503#if 0
Tom Caredf4ca422010-07-16 20:41:41 +0000504// Check for self casts truncating/extending a variable
505bool IdempotentOperationChecker::isTruncationExtensionAssignment(
506 const Expr *LHS,
507 const Expr *RHS) {
508
509 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
510 if (!LHS_DR)
511 return false;
512
513 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
514 if (!VD)
515 return false;
516
517 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
518 if (!RHS_DR)
519 return false;
520
521 if (VD != RHS_DR->getDecl())
522 return false;
523
524 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
525}
Chris Lattnerfae96222010-09-03 04:34:38 +0000526#endif
Tom Caredf4ca422010-07-16 20:41:41 +0000527
Tom Carea7a8a452010-08-12 22:45:47 +0000528// Returns false if a path to this block was not completely analyzed, or true
529// otherwise.
530bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
531 const CFG *C,
532 const CFGBlock *CB,
533 const GRCoreEngine &CE) {
534 std::deque<const CFGBlock *> WorkList;
535 llvm::SmallSet<unsigned, 8> Aborted;
536 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000537
Tom Carea7a8a452010-08-12 22:45:47 +0000538 // Create a set of all aborted blocks
539 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
540 for (AbortedIterator I = CE.blocks_aborted_begin(),
541 E = CE.blocks_aborted_end(); I != E; ++I) {
542 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000543
Tom Carea7a8a452010-08-12 22:45:47 +0000544 // The destination block on the BlockEdge is the first block that was not
545 // analyzed.
546 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000547 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000548
Tom Carea7a8a452010-08-12 22:45:47 +0000549 // Save the entry block ID for early exiting
550 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000551
Tom Carea7a8a452010-08-12 22:45:47 +0000552 // Create initial node
553 WorkList.push_back(CB);
554
555 while (!WorkList.empty()) {
556 const CFGBlock *Head = WorkList.front();
557 WorkList.pop_front();
558 Visited.insert(Head->getBlockID());
559
560 // If we found the entry block, then there exists a path from the target
561 // node to the entry point of this function -> the path was completely
562 // analyzed.
563 if (Head->getBlockID() == EntryBlockID)
564 return true;
565
566 // If any of the aborted blocks are on the path to the beginning, then all
567 // paths to this block were not analyzed.
568 if (Aborted.count(Head->getBlockID()))
569 return false;
570
571 // Add the predecessors to the worklist unless we have already visited them
572 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
573 I != Head->pred_end(); ++I)
574 if (!Visited.count((*I)->getBlockID()))
575 WorkList.push_back(*I);
576 }
577
578 // If we get to this point, there is no connection to the entry block or an
579 // aborted block. This path is unreachable and we can report the error.
580 return true;
581}
582
583// Recursive function that determines whether an expression contains any element
584// that varies. This could be due to a compile-time constant like sizeof. An
585// expression may also involve a variable that behaves like a constant. The
586// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000587bool IdempotentOperationChecker::CanVary(const Expr *Ex,
588 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000589 // Parentheses and casts are irrelevant here
590 Ex = Ex->IgnoreParenCasts();
591
592 if (Ex->getLocStart().isMacroID())
593 return false;
594
595 switch (Ex->getStmtClass()) {
596 // Trivially true cases
597 case Stmt::ArraySubscriptExprClass:
598 case Stmt::MemberExprClass:
599 case Stmt::StmtExprClass:
600 case Stmt::CallExprClass:
601 case Stmt::VAArgExprClass:
602 case Stmt::ShuffleVectorExprClass:
603 return true;
604 default:
605 return true;
606
607 // Trivially false cases
608 case Stmt::IntegerLiteralClass:
609 case Stmt::CharacterLiteralClass:
610 case Stmt::FloatingLiteralClass:
611 case Stmt::PredefinedExprClass:
612 case Stmt::ImaginaryLiteralClass:
613 case Stmt::StringLiteralClass:
614 case Stmt::OffsetOfExprClass:
615 case Stmt::CompoundLiteralExprClass:
616 case Stmt::AddrLabelExprClass:
617 case Stmt::TypesCompatibleExprClass:
618 case Stmt::GNUNullExprClass:
619 case Stmt::InitListExprClass:
620 case Stmt::DesignatedInitExprClass:
621 case Stmt::BlockExprClass:
622 case Stmt::BlockDeclRefExprClass:
623 return false;
624
625 // Cases requiring custom logic
626 case Stmt::SizeOfAlignOfExprClass: {
627 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
628 if (!SE->isSizeOf())
629 return false;
630 return SE->getTypeOfArgument()->isVariableArrayType();
631 }
632 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000633 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000634 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000635
636 // The next cases require recursion for subexpressions
637 case Stmt::BinaryOperatorClass: {
638 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000639 return CanVary(B->getRHS(), AC)
640 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000641 }
642 case Stmt::UnaryOperatorClass: {
643 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000644 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000645 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000646 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000647 return false;
648 default:
Tom Care245adab2010-08-18 21:17:24 +0000649 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000650 }
651 }
652 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000653 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
654 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000655 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000656 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000657 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000658}
659
Tom Care245adab2010-08-18 21:17:24 +0000660// Returns true if a DeclRefExpr is or behaves like a constant.
661bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000662 const DeclRefExpr *DR,
663 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000664 // Check if the type of the Decl is const-qualified
665 if (DR->getType().isConstQualified())
666 return true;
667
Tom Care50e8ac22010-08-16 21:43:52 +0000668 // Check for an enum
669 if (isa<EnumConstantDecl>(DR->getDecl()))
670 return true;
671
Tom Caredb34ab72010-08-23 19:51:57 +0000672 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
673 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000674 return true;
675
Tom Caredb34ab72010-08-23 19:51:57 +0000676 // Check if the Decl behaves like a constant. This check also takes care of
677 // static variables, which can only change between function calls if they are
678 // modified in the AST.
679 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
680 if (PCA->isPseudoConstant(VD))
681 return true;
682
683 return false;
684}
685
686// Recursively find any substatements containing VarDecl's with storage other
687// than local
688bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
689 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
690
691 if (DR)
692 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
693 if (!VD->hasLocalStorage())
694 return true;
695
696 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
697 ++I)
698 if (const Stmt *child = *I)
699 if (containsNonLocalVarDecl(child))
700 return true;
701
Tom Care50e8ac22010-08-16 21:43:52 +0000702 return false;
703}