blob: de72de4264d81630ae746c753fca76cf9d3fd54d [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 Care3f0ce9c2010-09-02 17:49:20 +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 Care3f0ce9c2010-09-02 17:49:20 +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);
Tom Caredf4ca422010-07-16 20:41:41 +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 Care3f0ce9c2010-09-02 17:49:20 +000092 // Hash table and related data structures
93 typedef struct {
94 Assumption Assumption;
95 AnalysisContext *AnalysisContext;
96 ExplodedNodeSet ExplodedNodes; // Set of ExplodedNodes that refer to a
97 // BinaryOperator
98 } BinaryOperatorData;
99 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
100 AssumptionMap;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000101 AssumptionMap hash;
102};
103}
104
105void *IdempotentOperationChecker::getTag() {
106 static int x = 0;
107 return &x;
108}
109
110void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
111 Eng.registerCheck(new IdempotentOperationChecker());
112}
113
114void IdempotentOperationChecker::PreVisitBinaryOperator(
115 CheckerContext &C,
116 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000117 // Find or create an entry in the hash for this BinaryOperator instance.
118 // If we haven't done a lookup before, it will get default initialized to
Tom Care3f0ce9c2010-09-02 17:49:20 +0000119 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
120 // been created yet.
121 BinaryOperatorData &Data = hash[B];
122 Assumption &A = Data.Assumption;
Tom Care245adab2010-08-18 21:17:24 +0000123 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care3f0ce9c2010-09-02 17:49:20 +0000124 Data.AnalysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000125
126 // If we already have visited this node on a path that does not contain an
127 // idempotent operation, return immediately.
128 if (A == Impossible)
129 return;
130
Tom Carea7a8a452010-08-12 22:45:47 +0000131 // Retrieve both sides of the operator and determine if they can vary (which
132 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000133 const Expr *LHS = B->getLHS();
134 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000135
Tom Caredb34ab72010-08-23 19:51:57 +0000136 // At this stage we can calculate whether each side contains a false positive
137 // that applies to all operators. We only need to calculate this the first
138 // time.
139 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000140 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000141 // An expression contains a false positive if it can't vary, or if it
142 // contains a known false positive VarDecl.
143 LHSContainsFalsePositive = !CanVary(LHS, AC)
144 || containsNonLocalVarDecl(LHS);
145 RHSContainsFalsePositive = !CanVary(RHS, AC)
146 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000147 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000148
149 const GRState *state = C.getState();
150
151 SVal LHSVal = state->getSVal(LHS);
152 SVal RHSVal = state->getSVal(RHS);
153
154 // If either value is unknown, we can't be 100% sure of all paths.
155 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
156 A = Impossible;
157 return;
158 }
159 BinaryOperator::Opcode Op = B->getOpcode();
160
161 // Dereference the LHS SVal if this is an assign operation
162 switch (Op) {
163 default:
164 break;
165
166 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000167 case BO_AddAssign:
168 case BO_SubAssign:
169 case BO_MulAssign:
170 case BO_DivAssign:
171 case BO_AndAssign:
172 case BO_OrAssign:
173 case BO_XorAssign:
174 case BO_ShlAssign:
175 case BO_ShrAssign:
176 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000177 // Assign statements have one extra level of indirection
178 if (!isa<Loc>(LHSVal)) {
179 A = Impossible;
180 return;
181 }
182 LHSVal = state->getSVal(cast<Loc>(LHSVal));
183 }
184
185
186 // We now check for various cases which result in an idempotent operation.
187
188 // x op x
189 switch (Op) {
190 default:
191 break; // We don't care about any other operators.
192
193 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000194 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000195 // x Assign x can be used to silence unused variable warnings intentionally.
196 // If this is a self assignment and the variable is referenced elsewhere,
197 // then it is a false positive.
198 if (isSelfAssign(LHS, RHS)) {
199 if (!isUnused(LHS, AC)) {
200 UpdateAssumption(A, Equal);
201 return;
202 }
203 else {
204 A = Impossible;
205 return;
206 }
Tom Caredf4ca422010-07-16 20:41:41 +0000207 }
208
John McCall2de56d12010-08-25 11:45:40 +0000209 case BO_SubAssign:
210 case BO_DivAssign:
211 case BO_AndAssign:
212 case BO_OrAssign:
213 case BO_XorAssign:
214 case BO_Sub:
215 case BO_Div:
216 case BO_And:
217 case BO_Or:
218 case BO_Xor:
219 case BO_LOr:
220 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000221 case BO_EQ:
222 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000223 if (LHSVal != RHSVal || LHSContainsFalsePositive
224 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000225 break;
226 UpdateAssumption(A, Equal);
227 return;
228 }
229
230 // x op 1
231 switch (Op) {
232 default:
233 break; // We don't care about any other operators.
234
235 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000236 case BO_MulAssign:
237 case BO_DivAssign:
238 case BO_Mul:
239 case BO_Div:
240 case BO_LOr:
241 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000242 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000243 break;
244 UpdateAssumption(A, RHSis1);
245 return;
246 }
247
248 // 1 op x
249 switch (Op) {
250 default:
251 break; // We don't care about any other operators.
252
253 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000254 case BO_MulAssign:
255 case BO_Mul:
256 case BO_LOr:
257 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000258 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000259 break;
260 UpdateAssumption(A, LHSis1);
261 return;
262 }
263
264 // x op 0
265 switch (Op) {
266 default:
267 break; // We don't care about any other operators.
268
269 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000270 case BO_AddAssign:
271 case BO_SubAssign:
272 case BO_MulAssign:
273 case BO_AndAssign:
274 case BO_OrAssign:
275 case BO_XorAssign:
276 case BO_Add:
277 case BO_Sub:
278 case BO_Mul:
279 case BO_And:
280 case BO_Or:
281 case BO_Xor:
282 case BO_Shl:
283 case BO_Shr:
284 case BO_LOr:
285 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000286 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000287 break;
288 UpdateAssumption(A, RHSis0);
289 return;
290 }
291
292 // 0 op x
293 switch (Op) {
294 default:
295 break; // We don't care about any other operators.
296
297 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000298 //case BO_AddAssign: // Common false positive
299 case BO_SubAssign: // Check only if unsigned
300 case BO_MulAssign:
301 case BO_DivAssign:
302 case BO_AndAssign:
303 //case BO_OrAssign: // Common false positive
304 //case BO_XorAssign: // Common false positive
305 case BO_ShlAssign:
306 case BO_ShrAssign:
307 case BO_Add:
308 case BO_Sub:
309 case BO_Mul:
310 case BO_Div:
311 case BO_And:
312 case BO_Or:
313 case BO_Xor:
314 case BO_Shl:
315 case BO_Shr:
316 case BO_LOr:
317 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000318 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000319 break;
320 UpdateAssumption(A, LHSis0);
321 return;
322 }
323
324 // If we get to this point, there has been a valid use of this operation.
325 A = Impossible;
326}
327
Tom Care3f0ce9c2010-09-02 17:49:20 +0000328// At the post visit stage, the predecessor ExplodedNode will be the
329// BinaryOperator that was just created. We use this hook to collect the
330// ExplodedNode.
331void IdempotentOperationChecker::PostVisitBinaryOperator(
332 CheckerContext &C,
333 const BinaryOperator *B) {
334 // Add the ExplodedNode we just visited
335 BinaryOperatorData &Data = hash[B];
336 Data.ExplodedNodes.Add(C.getPredecessor());
337}
338
Tom Caredb2fa8a2010-07-06 21:43:29 +0000339void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000340 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000341 GRExprEngine &Eng) {
Tom Care3f0ce9c2010-09-02 17:49:20 +0000342 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000343 // Iterate over the hash to see if we have any paths with definite
344 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000345 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
346 // Unpack the hash contents
Tom Care3f0ce9c2010-09-02 17:49:20 +0000347 const BinaryOperatorData &Data = i->second;
348 const Assumption &A = Data.Assumption;
349 AnalysisContext *AC = Data.AnalysisContext;
350 const ExplodedNodeSet &ES = Data.ExplodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000351
Tom Carea7a8a452010-08-12 22:45:47 +0000352 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000353
Tom Carea7a8a452010-08-12 22:45:47 +0000354 if (A == Impossible)
355 continue;
356
357 // If the analyzer did not finish, check to see if we can still emit this
358 // warning
359 if (Eng.hasWorkRemaining()) {
360 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
361 &AC->getParentMap());
362
363 // If we can trace back
364 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
365 CBM->getBlock(B),
366 Eng.getCoreEngine()))
367 continue;
368
369 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000370 }
Tom Carea7a8a452010-08-12 22:45:47 +0000371
Tom Care3f0ce9c2010-09-02 17:49:20 +0000372 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000373 llvm::SmallString<128> buf;
374 llvm::raw_svector_ostream os(buf);
Tom Care3f0ce9c2010-09-02 17:49:20 +0000375 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000376 switch (A) {
377 case Equal:
Tom Care3f0ce9c2010-09-02 17:49:20 +0000378 LHSRelevant = true;
379 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000380 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000381 os << "Assigned value is always the same as the existing value";
382 else
383 os << "Both operands to '" << B->getOpcodeStr()
384 << "' always have the same value";
385 break;
386 case LHSis1:
Tom Care3f0ce9c2010-09-02 17:49:20 +0000387 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000388 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
389 break;
390 case RHSis1:
Tom Care3f0ce9c2010-09-02 17:49:20 +0000391 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000392 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
393 break;
394 case LHSis0:
Tom Care3f0ce9c2010-09-02 17:49:20 +0000395 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000396 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
397 break;
398 case RHSis0:
Tom Care3f0ce9c2010-09-02 17:49:20 +0000399 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000400 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
401 break;
402 case Possible:
403 llvm_unreachable("Operation was never marked with an assumption");
404 case Impossible:
405 llvm_unreachable(0);
406 }
407
Tom Care3f0ce9c2010-09-02 17:49:20 +0000408 // Add a report for each ExplodedNode
409 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
410 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
411
412 // Add source ranges and visitor hooks
413 if (LHSRelevant) {
414 const Expr *LHS = i->first->getLHS();
415 report->addRange(LHS->getSourceRange());
416 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
417 }
418 if (RHSRelevant) {
419 const Expr *RHS = i->first->getRHS();
420 report->addRange(i->first->getRHS()->getSourceRange());
421 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
422 }
423
424 BR.EmitReport(report);
425 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000426 }
427}
428
429// Updates the current assumption given the new assumption
430inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
431 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000432// If the assumption is the same, there is nothing to do
433 if (A == New)
434 return;
435
Tom Caredb2fa8a2010-07-06 21:43:29 +0000436 switch (A) {
437 // If we don't currently have an assumption, set it
438 case Possible:
439 A = New;
440 return;
441
442 // If we have determined that a valid state happened, ignore the new
443 // assumption.
444 case Impossible:
445 return;
446
447 // Any other case means that we had a different assumption last time. We don't
448 // currently support mixing assumptions for diagnostic reasons, so we set
449 // our assumption to be impossible.
450 default:
451 A = Impossible;
452 return;
453 }
454}
455
Tom Care6216dc02010-08-30 19:25:43 +0000456// Check for a statement where a variable is self assigned to possibly avoid an
457// unused variable warning.
458bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000459 LHS = LHS->IgnoreParenCasts();
460 RHS = RHS->IgnoreParenCasts();
461
462 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
463 if (!LHS_DR)
464 return false;
465
Tom Careef52bcb2010-08-24 21:09:07 +0000466 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
467 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000468 return false;
469
470 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
471 if (!RHS_DR)
472 return false;
473
Tom Careef52bcb2010-08-24 21:09:07 +0000474 if (VD != RHS_DR->getDecl())
475 return false;
476
Tom Care6216dc02010-08-30 19:25:43 +0000477 return true;
478}
479
480// Returns true if the Expr points to a VarDecl that is not read anywhere
481// outside of self-assignments.
482bool IdempotentOperationChecker::isUnused(const Expr *E,
483 AnalysisContext *AC) {
484 if (!E)
485 return false;
486
487 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
488 if (!DR)
489 return false;
490
491 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
492 if (!VD)
493 return false;
494
Tom Careef52bcb2010-08-24 21:09:07 +0000495 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
496 return false;
497
498 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000499}
500
501// Check for self casts truncating/extending a variable
502bool IdempotentOperationChecker::isTruncationExtensionAssignment(
503 const Expr *LHS,
504 const Expr *RHS) {
505
506 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
507 if (!LHS_DR)
508 return false;
509
510 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
511 if (!VD)
512 return false;
513
514 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
515 if (!RHS_DR)
516 return false;
517
518 if (VD != RHS_DR->getDecl())
519 return false;
520
521 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
522}
523
Tom Carea7a8a452010-08-12 22:45:47 +0000524// Returns false if a path to this block was not completely analyzed, or true
525// otherwise.
526bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
527 const CFG *C,
528 const CFGBlock *CB,
529 const GRCoreEngine &CE) {
530 std::deque<const CFGBlock *> WorkList;
531 llvm::SmallSet<unsigned, 8> Aborted;
532 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000533
Tom Carea7a8a452010-08-12 22:45:47 +0000534 // Create a set of all aborted blocks
535 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
536 for (AbortedIterator I = CE.blocks_aborted_begin(),
537 E = CE.blocks_aborted_end(); I != E; ++I) {
538 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000539
Tom Carea7a8a452010-08-12 22:45:47 +0000540 // The destination block on the BlockEdge is the first block that was not
541 // analyzed.
542 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000543 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000544
Tom Carea7a8a452010-08-12 22:45:47 +0000545 // Save the entry block ID for early exiting
546 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000547
Tom Carea7a8a452010-08-12 22:45:47 +0000548 // Create initial node
549 WorkList.push_back(CB);
550
551 while (!WorkList.empty()) {
552 const CFGBlock *Head = WorkList.front();
553 WorkList.pop_front();
554 Visited.insert(Head->getBlockID());
555
556 // If we found the entry block, then there exists a path from the target
557 // node to the entry point of this function -> the path was completely
558 // analyzed.
559 if (Head->getBlockID() == EntryBlockID)
560 return true;
561
562 // If any of the aborted blocks are on the path to the beginning, then all
563 // paths to this block were not analyzed.
564 if (Aborted.count(Head->getBlockID()))
565 return false;
566
567 // Add the predecessors to the worklist unless we have already visited them
568 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
569 I != Head->pred_end(); ++I)
570 if (!Visited.count((*I)->getBlockID()))
571 WorkList.push_back(*I);
572 }
573
574 // If we get to this point, there is no connection to the entry block or an
575 // aborted block. This path is unreachable and we can report the error.
576 return true;
577}
578
579// Recursive function that determines whether an expression contains any element
580// that varies. This could be due to a compile-time constant like sizeof. An
581// expression may also involve a variable that behaves like a constant. The
582// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000583bool IdempotentOperationChecker::CanVary(const Expr *Ex,
584 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000585 // Parentheses and casts are irrelevant here
586 Ex = Ex->IgnoreParenCasts();
587
588 if (Ex->getLocStart().isMacroID())
589 return false;
590
591 switch (Ex->getStmtClass()) {
592 // Trivially true cases
593 case Stmt::ArraySubscriptExprClass:
594 case Stmt::MemberExprClass:
595 case Stmt::StmtExprClass:
596 case Stmt::CallExprClass:
597 case Stmt::VAArgExprClass:
598 case Stmt::ShuffleVectorExprClass:
599 return true;
600 default:
601 return true;
602
603 // Trivially false cases
604 case Stmt::IntegerLiteralClass:
605 case Stmt::CharacterLiteralClass:
606 case Stmt::FloatingLiteralClass:
607 case Stmt::PredefinedExprClass:
608 case Stmt::ImaginaryLiteralClass:
609 case Stmt::StringLiteralClass:
610 case Stmt::OffsetOfExprClass:
611 case Stmt::CompoundLiteralExprClass:
612 case Stmt::AddrLabelExprClass:
613 case Stmt::TypesCompatibleExprClass:
614 case Stmt::GNUNullExprClass:
615 case Stmt::InitListExprClass:
616 case Stmt::DesignatedInitExprClass:
617 case Stmt::BlockExprClass:
618 case Stmt::BlockDeclRefExprClass:
619 return false;
620
621 // Cases requiring custom logic
622 case Stmt::SizeOfAlignOfExprClass: {
623 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
624 if (!SE->isSizeOf())
625 return false;
626 return SE->getTypeOfArgument()->isVariableArrayType();
627 }
628 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000629 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000630 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000631
632 // The next cases require recursion for subexpressions
633 case Stmt::BinaryOperatorClass: {
634 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000635 return CanVary(B->getRHS(), AC)
636 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000637 }
638 case Stmt::UnaryOperatorClass: {
639 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000640 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000641 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000642 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000643 return false;
644 default:
Tom Care245adab2010-08-18 21:17:24 +0000645 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000646 }
647 }
648 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000649 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
650 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000651 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000652 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000653 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000654}
655
Tom Care245adab2010-08-18 21:17:24 +0000656// Returns true if a DeclRefExpr is or behaves like a constant.
657bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000658 const DeclRefExpr *DR,
659 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000660 // Check if the type of the Decl is const-qualified
661 if (DR->getType().isConstQualified())
662 return true;
663
Tom Care50e8ac22010-08-16 21:43:52 +0000664 // Check for an enum
665 if (isa<EnumConstantDecl>(DR->getDecl()))
666 return true;
667
Tom Caredb34ab72010-08-23 19:51:57 +0000668 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
669 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000670 return true;
671
Tom Caredb34ab72010-08-23 19:51:57 +0000672 // Check if the Decl behaves like a constant. This check also takes care of
673 // static variables, which can only change between function calls if they are
674 // modified in the AST.
675 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
676 if (PCA->isPseudoConstant(VD))
677 return true;
678
679 return false;
680}
681
682// Recursively find any substatements containing VarDecl's with storage other
683// than local
684bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
685 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
686
687 if (DR)
688 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
689 if (!VD->hasLocalStorage())
690 return true;
691
692 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
693 ++I)
694 if (const Stmt *child = *I)
695 if (containsNonLocalVarDecl(child))
696 return true;
697
Tom Care50e8ac22010-08-16 21:43:52 +0000698 return false;
699}