blob: 8a9e333ce5c5b5aa1298991698e9163496c147b2 [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 Caredb2fa8a2010-07-06 21:43:29 +000048#include "clang/Checker/BugReporter/BugType.h"
Tom Carea9fbf5b2010-07-27 23:26:07 +000049#include "clang/Checker/PathSensitive/CheckerHelpers.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000050#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Tom Carea7a8a452010-08-12 22:45:47 +000051#include "clang/Checker/PathSensitive/GRCoreEngine.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000052#include "clang/Checker/PathSensitive/SVals.h"
53#include "clang/AST/Stmt.h"
54#include "llvm/ADT/DenseMap.h"
Tom Carea7a8a452010-08-12 22:45:47 +000055#include "llvm/ADT/SmallSet.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000056#include "llvm/Support/ErrorHandling.h"
Tom Carea7a8a452010-08-12 22:45:47 +000057#include <deque>
Tom Caredb2fa8a2010-07-06 21:43:29 +000058
59using namespace clang;
60
61namespace {
62class IdempotentOperationChecker
63 : public CheckerVisitor<IdempotentOperationChecker> {
64 public:
65 static void *getTag();
66 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Tom Carebc42c532010-08-03 01:55:07 +000067 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, GRExprEngine &Eng);
Tom Caredb2fa8a2010-07-06 21:43:29 +000068
69 private:
70 // Our assumption about a particular operation.
Ted Kremenekfe97fa12010-08-02 20:33:02 +000071 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
Tom Caredb2fa8a2010-07-06 21:43:29 +000072 RHSis0 };
73
74 void UpdateAssumption(Assumption &A, const Assumption &New);
75
Tom Care245adab2010-08-18 21:17:24 +000076 // False positive reduction methods
Tom Careef52bcb2010-08-24 21:09:07 +000077 static bool isUnusedSelfAssign(const Expr *LHS,
78 const Expr *RHS,
79 AnalysisContext *AC);
Tom Caredf4ca422010-07-16 20:41:41 +000080 static bool isTruncationExtensionAssignment(const Expr *LHS,
81 const Expr *RHS);
Tom Carea7a8a452010-08-12 22:45:47 +000082 static bool PathWasCompletelyAnalyzed(const CFG *C,
83 const CFGBlock *CB,
84 const GRCoreEngine &CE);
Tom Care245adab2010-08-18 21:17:24 +000085 static bool CanVary(const Expr *Ex, AnalysisContext *AC);
86 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
87 AnalysisContext *AC);
Tom Caredb34ab72010-08-23 19:51:57 +000088 static bool containsNonLocalVarDecl(const Stmt *S);
Tom Caredb2fa8a2010-07-06 21:43:29 +000089
90 // Hash table
Tom Carea7a8a452010-08-12 22:45:47 +000091 typedef llvm::DenseMap<const BinaryOperator *,
92 std::pair<Assumption, AnalysisContext*> >
93 AssumptionMap;
Tom Caredb2fa8a2010-07-06 21:43:29 +000094 AssumptionMap hash;
95};
96}
97
98void *IdempotentOperationChecker::getTag() {
99 static int x = 0;
100 return &x;
101}
102
103void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
104 Eng.registerCheck(new IdempotentOperationChecker());
105}
106
107void IdempotentOperationChecker::PreVisitBinaryOperator(
108 CheckerContext &C,
109 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000110 // Find or create an entry in the hash for this BinaryOperator instance.
111 // If we haven't done a lookup before, it will get default initialized to
112 // 'Possible'.
Tom Carea7a8a452010-08-12 22:45:47 +0000113 std::pair<Assumption, AnalysisContext *> &Data = hash[B];
114 Assumption &A = Data.first;
Tom Care245adab2010-08-18 21:17:24 +0000115 AnalysisContext *AC = C.getCurrentAnalysisContext();
116 Data.second = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000117
118 // If we already have visited this node on a path that does not contain an
119 // idempotent operation, return immediately.
120 if (A == Impossible)
121 return;
122
Tom Carea7a8a452010-08-12 22:45:47 +0000123 // Retrieve both sides of the operator and determine if they can vary (which
124 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000125 const Expr *LHS = B->getLHS();
126 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000127
Tom Caredb34ab72010-08-23 19:51:57 +0000128 // At this stage we can calculate whether each side contains a false positive
129 // that applies to all operators. We only need to calculate this the first
130 // time.
131 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000132 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000133 // An expression contains a false positive if it can't vary, or if it
134 // contains a known false positive VarDecl.
135 LHSContainsFalsePositive = !CanVary(LHS, AC)
136 || containsNonLocalVarDecl(LHS);
137 RHSContainsFalsePositive = !CanVary(RHS, AC)
138 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000139 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000140
141 const GRState *state = C.getState();
142
143 SVal LHSVal = state->getSVal(LHS);
144 SVal RHSVal = state->getSVal(RHS);
145
146 // If either value is unknown, we can't be 100% sure of all paths.
147 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
148 A = Impossible;
149 return;
150 }
151 BinaryOperator::Opcode Op = B->getOpcode();
152
153 // Dereference the LHS SVal if this is an assign operation
154 switch (Op) {
155 default:
156 break;
157
158 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000159 case BO_AddAssign:
160 case BO_SubAssign:
161 case BO_MulAssign:
162 case BO_DivAssign:
163 case BO_AndAssign:
164 case BO_OrAssign:
165 case BO_XorAssign:
166 case BO_ShlAssign:
167 case BO_ShrAssign:
168 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000169 // Assign statements have one extra level of indirection
170 if (!isa<Loc>(LHSVal)) {
171 A = Impossible;
172 return;
173 }
174 LHSVal = state->getSVal(cast<Loc>(LHSVal));
175 }
176
177
178 // We now check for various cases which result in an idempotent operation.
179
180 // x op x
181 switch (Op) {
182 default:
183 break; // We don't care about any other operators.
184
185 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000186 case BO_Assign:
Tom Careef52bcb2010-08-24 21:09:07 +0000187 // x Assign x can be used to silence unused variable warnings intentionally,
188 // and has a slightly different definition for false positives.
189 if (isUnusedSelfAssign(RHS, LHS, AC)
190 || isTruncationExtensionAssignment(RHS, LHS)
191 || containsNonLocalVarDecl(RHS)
192 || containsNonLocalVarDecl(LHS)) {
Tom Caredf4ca422010-07-16 20:41:41 +0000193 A = Impossible;
194 return;
195 }
Tom Careef52bcb2010-08-24 21:09:07 +0000196 if (LHSVal != RHSVal)
197 break;
198 UpdateAssumption(A, Equal);
199 return;
Tom Caredf4ca422010-07-16 20:41:41 +0000200
John McCall2de56d12010-08-25 11:45:40 +0000201 case BO_SubAssign:
202 case BO_DivAssign:
203 case BO_AndAssign:
204 case BO_OrAssign:
205 case BO_XorAssign:
206 case BO_Sub:
207 case BO_Div:
208 case BO_And:
209 case BO_Or:
210 case BO_Xor:
211 case BO_LOr:
212 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000213 case BO_EQ:
214 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000215 if (LHSVal != RHSVal || LHSContainsFalsePositive
216 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000217 break;
218 UpdateAssumption(A, Equal);
219 return;
220 }
221
222 // x op 1
223 switch (Op) {
224 default:
225 break; // We don't care about any other operators.
226
227 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000228 case BO_MulAssign:
229 case BO_DivAssign:
230 case BO_Mul:
231 case BO_Div:
232 case BO_LOr:
233 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000234 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000235 break;
236 UpdateAssumption(A, RHSis1);
237 return;
238 }
239
240 // 1 op x
241 switch (Op) {
242 default:
243 break; // We don't care about any other operators.
244
245 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000246 case BO_MulAssign:
247 case BO_Mul:
248 case BO_LOr:
249 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000250 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000251 break;
252 UpdateAssumption(A, LHSis1);
253 return;
254 }
255
256 // x op 0
257 switch (Op) {
258 default:
259 break; // We don't care about any other operators.
260
261 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000262 case BO_AddAssign:
263 case BO_SubAssign:
264 case BO_MulAssign:
265 case BO_AndAssign:
266 case BO_OrAssign:
267 case BO_XorAssign:
268 case BO_Add:
269 case BO_Sub:
270 case BO_Mul:
271 case BO_And:
272 case BO_Or:
273 case BO_Xor:
274 case BO_Shl:
275 case BO_Shr:
276 case BO_LOr:
277 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000278 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000279 break;
280 UpdateAssumption(A, RHSis0);
281 return;
282 }
283
284 // 0 op x
285 switch (Op) {
286 default:
287 break; // We don't care about any other operators.
288
289 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000290 //case BO_AddAssign: // Common false positive
291 case BO_SubAssign: // Check only if unsigned
292 case BO_MulAssign:
293 case BO_DivAssign:
294 case BO_AndAssign:
295 //case BO_OrAssign: // Common false positive
296 //case BO_XorAssign: // Common false positive
297 case BO_ShlAssign:
298 case BO_ShrAssign:
299 case BO_Add:
300 case BO_Sub:
301 case BO_Mul:
302 case BO_Div:
303 case BO_And:
304 case BO_Or:
305 case BO_Xor:
306 case BO_Shl:
307 case BO_Shr:
308 case BO_LOr:
309 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000310 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000311 break;
312 UpdateAssumption(A, LHSis0);
313 return;
314 }
315
316 // If we get to this point, there has been a valid use of this operation.
317 A = Impossible;
318}
319
320void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000321 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000322 GRExprEngine &Eng) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000323 // Iterate over the hash to see if we have any paths with definite
324 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000325 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
326 // Unpack the hash contents
327 const std::pair<Assumption, AnalysisContext *> &Data = i->second;
328 const Assumption &A = Data.first;
329 AnalysisContext *AC = Data.second;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000330
Tom Carea7a8a452010-08-12 22:45:47 +0000331 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000332
Tom Carea7a8a452010-08-12 22:45:47 +0000333 if (A == Impossible)
334 continue;
335
336 // If the analyzer did not finish, check to see if we can still emit this
337 // warning
338 if (Eng.hasWorkRemaining()) {
339 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
340 &AC->getParentMap());
341
342 // If we can trace back
343 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
344 CBM->getBlock(B),
345 Eng.getCoreEngine()))
346 continue;
347
348 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000349 }
Tom Carea7a8a452010-08-12 22:45:47 +0000350
351 // Select the error message.
352 llvm::SmallString<128> buf;
353 llvm::raw_svector_ostream os(buf);
354 switch (A) {
355 case Equal:
John McCall2de56d12010-08-25 11:45:40 +0000356 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000357 os << "Assigned value is always the same as the existing value";
358 else
359 os << "Both operands to '" << B->getOpcodeStr()
360 << "' always have the same value";
361 break;
362 case LHSis1:
363 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
364 break;
365 case RHSis1:
366 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
367 break;
368 case LHSis0:
369 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
370 break;
371 case RHSis0:
372 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
373 break;
374 case Possible:
375 llvm_unreachable("Operation was never marked with an assumption");
376 case Impossible:
377 llvm_unreachable(0);
378 }
379
380 // Create the SourceRange Arrays
381 SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
382 i->first->getRHS()->getSourceRange() };
383 BR.EmitBasicReport("Idempotent operation", "Dead code",
384 os.str(), i->first->getOperatorLoc(), S, 2);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000385 }
386}
387
388// Updates the current assumption given the new assumption
389inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
390 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000391// If the assumption is the same, there is nothing to do
392 if (A == New)
393 return;
394
Tom Caredb2fa8a2010-07-06 21:43:29 +0000395 switch (A) {
396 // If we don't currently have an assumption, set it
397 case Possible:
398 A = New;
399 return;
400
401 // If we have determined that a valid state happened, ignore the new
402 // assumption.
403 case Impossible:
404 return;
405
406 // Any other case means that we had a different assumption last time. We don't
407 // currently support mixing assumptions for diagnostic reasons, so we set
408 // our assumption to be impossible.
409 default:
410 A = Impossible;
411 return;
412 }
413}
414
Tom Careef52bcb2010-08-24 21:09:07 +0000415// Check for a statement where a variable is self assigned to avoid an unused
416// variable warning. We still report if the variable is used after the self
417// assignment.
418bool IdempotentOperationChecker::isUnusedSelfAssign(const Expr *LHS,
419 const Expr *RHS,
420 AnalysisContext *AC) {
Tom Caredf4ca422010-07-16 20:41:41 +0000421 LHS = LHS->IgnoreParenCasts();
422 RHS = RHS->IgnoreParenCasts();
423
424 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
425 if (!LHS_DR)
426 return false;
427
Tom Careef52bcb2010-08-24 21:09:07 +0000428 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
429 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000430 return false;
431
432 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
433 if (!RHS_DR)
434 return false;
435
Tom Careef52bcb2010-08-24 21:09:07 +0000436 if (VD != RHS_DR->getDecl())
437 return false;
438
439 // If the var was used outside of a selfassign, then we should still report
440 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
441 return false;
442
443 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000444}
445
446// Check for self casts truncating/extending a variable
447bool IdempotentOperationChecker::isTruncationExtensionAssignment(
448 const Expr *LHS,
449 const Expr *RHS) {
450
451 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
452 if (!LHS_DR)
453 return false;
454
455 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
456 if (!VD)
457 return false;
458
459 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
460 if (!RHS_DR)
461 return false;
462
463 if (VD != RHS_DR->getDecl())
464 return false;
465
466 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
467}
468
Tom Carea7a8a452010-08-12 22:45:47 +0000469// Returns false if a path to this block was not completely analyzed, or true
470// otherwise.
471bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
472 const CFG *C,
473 const CFGBlock *CB,
474 const GRCoreEngine &CE) {
475 std::deque<const CFGBlock *> WorkList;
476 llvm::SmallSet<unsigned, 8> Aborted;
477 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000478
Tom Carea7a8a452010-08-12 22:45:47 +0000479 // Create a set of all aborted blocks
480 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
481 for (AbortedIterator I = CE.blocks_aborted_begin(),
482 E = CE.blocks_aborted_end(); I != E; ++I) {
483 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000484
Tom Carea7a8a452010-08-12 22:45:47 +0000485 // The destination block on the BlockEdge is the first block that was not
486 // analyzed.
487 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000488 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000489
Tom Carea7a8a452010-08-12 22:45:47 +0000490 // Save the entry block ID for early exiting
491 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000492
Tom Carea7a8a452010-08-12 22:45:47 +0000493 // Create initial node
494 WorkList.push_back(CB);
495
496 while (!WorkList.empty()) {
497 const CFGBlock *Head = WorkList.front();
498 WorkList.pop_front();
499 Visited.insert(Head->getBlockID());
500
501 // If we found the entry block, then there exists a path from the target
502 // node to the entry point of this function -> the path was completely
503 // analyzed.
504 if (Head->getBlockID() == EntryBlockID)
505 return true;
506
507 // If any of the aborted blocks are on the path to the beginning, then all
508 // paths to this block were not analyzed.
509 if (Aborted.count(Head->getBlockID()))
510 return false;
511
512 // Add the predecessors to the worklist unless we have already visited them
513 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
514 I != Head->pred_end(); ++I)
515 if (!Visited.count((*I)->getBlockID()))
516 WorkList.push_back(*I);
517 }
518
519 // If we get to this point, there is no connection to the entry block or an
520 // aborted block. This path is unreachable and we can report the error.
521 return true;
522}
523
524// Recursive function that determines whether an expression contains any element
525// that varies. This could be due to a compile-time constant like sizeof. An
526// expression may also involve a variable that behaves like a constant. The
527// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000528bool IdempotentOperationChecker::CanVary(const Expr *Ex,
529 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000530 // Parentheses and casts are irrelevant here
531 Ex = Ex->IgnoreParenCasts();
532
533 if (Ex->getLocStart().isMacroID())
534 return false;
535
536 switch (Ex->getStmtClass()) {
537 // Trivially true cases
538 case Stmt::ArraySubscriptExprClass:
539 case Stmt::MemberExprClass:
540 case Stmt::StmtExprClass:
541 case Stmt::CallExprClass:
542 case Stmt::VAArgExprClass:
543 case Stmt::ShuffleVectorExprClass:
544 return true;
545 default:
546 return true;
547
548 // Trivially false cases
549 case Stmt::IntegerLiteralClass:
550 case Stmt::CharacterLiteralClass:
551 case Stmt::FloatingLiteralClass:
552 case Stmt::PredefinedExprClass:
553 case Stmt::ImaginaryLiteralClass:
554 case Stmt::StringLiteralClass:
555 case Stmt::OffsetOfExprClass:
556 case Stmt::CompoundLiteralExprClass:
557 case Stmt::AddrLabelExprClass:
558 case Stmt::TypesCompatibleExprClass:
559 case Stmt::GNUNullExprClass:
560 case Stmt::InitListExprClass:
561 case Stmt::DesignatedInitExprClass:
562 case Stmt::BlockExprClass:
563 case Stmt::BlockDeclRefExprClass:
564 return false;
565
566 // Cases requiring custom logic
567 case Stmt::SizeOfAlignOfExprClass: {
568 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
569 if (!SE->isSizeOf())
570 return false;
571 return SE->getTypeOfArgument()->isVariableArrayType();
572 }
573 case Stmt::DeclRefExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000574 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000575
576 // The next cases require recursion for subexpressions
577 case Stmt::BinaryOperatorClass: {
578 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000579 return CanVary(B->getRHS(), AC)
580 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000581 }
582 case Stmt::UnaryOperatorClass: {
583 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000584 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000585 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000586 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000587 return false;
588 default:
Tom Care245adab2010-08-18 21:17:24 +0000589 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000590 }
591 }
592 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000593 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
594 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000595 case Stmt::ConditionalOperatorClass:
Tom Care245adab2010-08-18 21:17:24 +0000596 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000597 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000598}
599
Tom Care245adab2010-08-18 21:17:24 +0000600// Returns true if a DeclRefExpr is or behaves like a constant.
601bool IdempotentOperationChecker::isConstantOrPseudoConstant(
602 const DeclRefExpr *DR,
603 AnalysisContext *AC) {
604 // Check if the type of the Decl is const-qualified
605 if (DR->getType().isConstQualified())
606 return true;
607
Tom Care50e8ac22010-08-16 21:43:52 +0000608 // Check for an enum
609 if (isa<EnumConstantDecl>(DR->getDecl()))
610 return true;
611
Tom Caredb34ab72010-08-23 19:51:57 +0000612 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
613 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000614 return true;
615
Tom Caredb34ab72010-08-23 19:51:57 +0000616 // Check if the Decl behaves like a constant. This check also takes care of
617 // static variables, which can only change between function calls if they are
618 // modified in the AST.
619 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
620 if (PCA->isPseudoConstant(VD))
621 return true;
622
623 return false;
624}
625
626// Recursively find any substatements containing VarDecl's with storage other
627// than local
628bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
629 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
630
631 if (DR)
632 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
633 if (!VD->hasLocalStorage())
634 return true;
635
636 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
637 ++I)
638 if (const Stmt *child = *I)
639 if (containsNonLocalVarDecl(child))
640 return true;
641
Tom Care50e8ac22010-08-16 21:43:52 +0000642 return false;
643}