blob: d8936203ea16f4d1f1ad3703a964373b349ca444 [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
159 case BinaryOperator::AddAssign:
160 case BinaryOperator::SubAssign:
161 case BinaryOperator::MulAssign:
162 case BinaryOperator::DivAssign:
163 case BinaryOperator::AndAssign:
164 case BinaryOperator::OrAssign:
165 case BinaryOperator::XorAssign:
166 case BinaryOperator::ShlAssign:
167 case BinaryOperator::ShrAssign:
168 case BinaryOperator::Assign:
169 // 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
Tom Caredf4ca422010-07-16 20:41:41 +0000186 case BinaryOperator::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
Tom Caredb2fa8a2010-07-06 21:43:29 +0000201 case BinaryOperator::SubAssign:
202 case BinaryOperator::DivAssign:
203 case BinaryOperator::AndAssign:
204 case BinaryOperator::OrAssign:
205 case BinaryOperator::XorAssign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000206 case BinaryOperator::Sub:
207 case BinaryOperator::Div:
208 case BinaryOperator::And:
209 case BinaryOperator::Or:
210 case BinaryOperator::Xor:
211 case BinaryOperator::LOr:
212 case BinaryOperator::LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000213 if (LHSVal != RHSVal || LHSContainsFalsePositive
214 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000215 break;
216 UpdateAssumption(A, Equal);
217 return;
218 }
219
220 // x op 1
221 switch (Op) {
222 default:
223 break; // We don't care about any other operators.
224
225 // Fall through intentional
226 case BinaryOperator::MulAssign:
227 case BinaryOperator::DivAssign:
228 case BinaryOperator::Mul:
229 case BinaryOperator::Div:
230 case BinaryOperator::LOr:
231 case BinaryOperator::LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000232 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000233 break;
234 UpdateAssumption(A, RHSis1);
235 return;
236 }
237
238 // 1 op x
239 switch (Op) {
240 default:
241 break; // We don't care about any other operators.
242
243 // Fall through intentional
244 case BinaryOperator::MulAssign:
245 case BinaryOperator::Mul:
246 case BinaryOperator::LOr:
247 case BinaryOperator::LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000248 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000249 break;
250 UpdateAssumption(A, LHSis1);
251 return;
252 }
253
254 // x op 0
255 switch (Op) {
256 default:
257 break; // We don't care about any other operators.
258
259 // Fall through intentional
260 case BinaryOperator::AddAssign:
261 case BinaryOperator::SubAssign:
262 case BinaryOperator::MulAssign:
263 case BinaryOperator::AndAssign:
264 case BinaryOperator::OrAssign:
265 case BinaryOperator::XorAssign:
266 case BinaryOperator::Add:
267 case BinaryOperator::Sub:
268 case BinaryOperator::Mul:
269 case BinaryOperator::And:
270 case BinaryOperator::Or:
271 case BinaryOperator::Xor:
272 case BinaryOperator::Shl:
273 case BinaryOperator::Shr:
274 case BinaryOperator::LOr:
275 case BinaryOperator::LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000276 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000277 break;
278 UpdateAssumption(A, RHSis0);
279 return;
280 }
281
282 // 0 op x
283 switch (Op) {
284 default:
285 break; // We don't care about any other operators.
286
287 // Fall through intentional
288 //case BinaryOperator::AddAssign: // Common false positive
289 case BinaryOperator::SubAssign: // Check only if unsigned
290 case BinaryOperator::MulAssign:
291 case BinaryOperator::DivAssign:
292 case BinaryOperator::AndAssign:
293 //case BinaryOperator::OrAssign: // Common false positive
294 //case BinaryOperator::XorAssign: // Common false positive
295 case BinaryOperator::ShlAssign:
296 case BinaryOperator::ShrAssign:
297 case BinaryOperator::Add:
298 case BinaryOperator::Sub:
299 case BinaryOperator::Mul:
300 case BinaryOperator::Div:
301 case BinaryOperator::And:
302 case BinaryOperator::Or:
303 case BinaryOperator::Xor:
304 case BinaryOperator::Shl:
305 case BinaryOperator::Shr:
306 case BinaryOperator::LOr:
307 case BinaryOperator::LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000308 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000309 break;
310 UpdateAssumption(A, LHSis0);
311 return;
312 }
313
314 // If we get to this point, there has been a valid use of this operation.
315 A = Impossible;
316}
317
318void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000319 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000320 GRExprEngine &Eng) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000321 // Iterate over the hash to see if we have any paths with definite
322 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000323 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
324 // Unpack the hash contents
325 const std::pair<Assumption, AnalysisContext *> &Data = i->second;
326 const Assumption &A = Data.first;
327 AnalysisContext *AC = Data.second;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000328
Tom Carea7a8a452010-08-12 22:45:47 +0000329 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000330
Tom Carea7a8a452010-08-12 22:45:47 +0000331 if (A == Impossible)
332 continue;
333
334 // If the analyzer did not finish, check to see if we can still emit this
335 // warning
336 if (Eng.hasWorkRemaining()) {
337 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
338 &AC->getParentMap());
339
340 // If we can trace back
341 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
342 CBM->getBlock(B),
343 Eng.getCoreEngine()))
344 continue;
345
346 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000347 }
Tom Carea7a8a452010-08-12 22:45:47 +0000348
349 // Select the error message.
350 llvm::SmallString<128> buf;
351 llvm::raw_svector_ostream os(buf);
352 switch (A) {
353 case Equal:
354 if (B->getOpcode() == BinaryOperator::Assign)
355 os << "Assigned value is always the same as the existing value";
356 else
357 os << "Both operands to '" << B->getOpcodeStr()
358 << "' always have the same value";
359 break;
360 case LHSis1:
361 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
362 break;
363 case RHSis1:
364 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
365 break;
366 case LHSis0:
367 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
368 break;
369 case RHSis0:
370 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
371 break;
372 case Possible:
373 llvm_unreachable("Operation was never marked with an assumption");
374 case Impossible:
375 llvm_unreachable(0);
376 }
377
378 // Create the SourceRange Arrays
379 SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
380 i->first->getRHS()->getSourceRange() };
381 BR.EmitBasicReport("Idempotent operation", "Dead code",
382 os.str(), i->first->getOperatorLoc(), S, 2);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000383 }
384}
385
386// Updates the current assumption given the new assumption
387inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
388 const Assumption &New) {
389 switch (A) {
390 // If we don't currently have an assumption, set it
391 case Possible:
392 A = New;
393 return;
394
395 // If we have determined that a valid state happened, ignore the new
396 // assumption.
397 case Impossible:
398 return;
399
400 // Any other case means that we had a different assumption last time. We don't
401 // currently support mixing assumptions for diagnostic reasons, so we set
402 // our assumption to be impossible.
403 default:
404 A = Impossible;
405 return;
406 }
407}
408
Tom Careef52bcb2010-08-24 21:09:07 +0000409// Check for a statement where a variable is self assigned to avoid an unused
410// variable warning. We still report if the variable is used after the self
411// assignment.
412bool IdempotentOperationChecker::isUnusedSelfAssign(const Expr *LHS,
413 const Expr *RHS,
414 AnalysisContext *AC) {
Tom Caredf4ca422010-07-16 20:41:41 +0000415 LHS = LHS->IgnoreParenCasts();
416 RHS = RHS->IgnoreParenCasts();
417
418 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
419 if (!LHS_DR)
420 return false;
421
Tom Careef52bcb2010-08-24 21:09:07 +0000422 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
423 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000424 return false;
425
426 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
427 if (!RHS_DR)
428 return false;
429
Tom Careef52bcb2010-08-24 21:09:07 +0000430 if (VD != RHS_DR->getDecl())
431 return false;
432
433 // If the var was used outside of a selfassign, then we should still report
434 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
435 return false;
436
437 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000438}
439
440// Check for self casts truncating/extending a variable
441bool IdempotentOperationChecker::isTruncationExtensionAssignment(
442 const Expr *LHS,
443 const Expr *RHS) {
444
445 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
446 if (!LHS_DR)
447 return false;
448
449 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
450 if (!VD)
451 return false;
452
453 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
454 if (!RHS_DR)
455 return false;
456
457 if (VD != RHS_DR->getDecl())
458 return false;
459
460 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
461}
462
Tom Carea7a8a452010-08-12 22:45:47 +0000463// Returns false if a path to this block was not completely analyzed, or true
464// otherwise.
465bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
466 const CFG *C,
467 const CFGBlock *CB,
468 const GRCoreEngine &CE) {
469 std::deque<const CFGBlock *> WorkList;
470 llvm::SmallSet<unsigned, 8> Aborted;
471 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000472
Tom Carea7a8a452010-08-12 22:45:47 +0000473 // Create a set of all aborted blocks
474 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
475 for (AbortedIterator I = CE.blocks_aborted_begin(),
476 E = CE.blocks_aborted_end(); I != E; ++I) {
477 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000478
Tom Carea7a8a452010-08-12 22:45:47 +0000479 // The destination block on the BlockEdge is the first block that was not
480 // analyzed.
481 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000482 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000483
Tom Carea7a8a452010-08-12 22:45:47 +0000484 // Save the entry block ID for early exiting
485 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000486
Tom Carea7a8a452010-08-12 22:45:47 +0000487 // Create initial node
488 WorkList.push_back(CB);
489
490 while (!WorkList.empty()) {
491 const CFGBlock *Head = WorkList.front();
492 WorkList.pop_front();
493 Visited.insert(Head->getBlockID());
494
495 // If we found the entry block, then there exists a path from the target
496 // node to the entry point of this function -> the path was completely
497 // analyzed.
498 if (Head->getBlockID() == EntryBlockID)
499 return true;
500
501 // If any of the aborted blocks are on the path to the beginning, then all
502 // paths to this block were not analyzed.
503 if (Aborted.count(Head->getBlockID()))
504 return false;
505
506 // Add the predecessors to the worklist unless we have already visited them
507 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
508 I != Head->pred_end(); ++I)
509 if (!Visited.count((*I)->getBlockID()))
510 WorkList.push_back(*I);
511 }
512
513 // If we get to this point, there is no connection to the entry block or an
514 // aborted block. This path is unreachable and we can report the error.
515 return true;
516}
517
518// Recursive function that determines whether an expression contains any element
519// that varies. This could be due to a compile-time constant like sizeof. An
520// expression may also involve a variable that behaves like a constant. The
521// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000522bool IdempotentOperationChecker::CanVary(const Expr *Ex,
523 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000524 // Parentheses and casts are irrelevant here
525 Ex = Ex->IgnoreParenCasts();
526
527 if (Ex->getLocStart().isMacroID())
528 return false;
529
530 switch (Ex->getStmtClass()) {
531 // Trivially true cases
532 case Stmt::ArraySubscriptExprClass:
533 case Stmt::MemberExprClass:
534 case Stmt::StmtExprClass:
535 case Stmt::CallExprClass:
536 case Stmt::VAArgExprClass:
537 case Stmt::ShuffleVectorExprClass:
538 return true;
539 default:
540 return true;
541
542 // Trivially false cases
543 case Stmt::IntegerLiteralClass:
544 case Stmt::CharacterLiteralClass:
545 case Stmt::FloatingLiteralClass:
546 case Stmt::PredefinedExprClass:
547 case Stmt::ImaginaryLiteralClass:
548 case Stmt::StringLiteralClass:
549 case Stmt::OffsetOfExprClass:
550 case Stmt::CompoundLiteralExprClass:
551 case Stmt::AddrLabelExprClass:
552 case Stmt::TypesCompatibleExprClass:
553 case Stmt::GNUNullExprClass:
554 case Stmt::InitListExprClass:
555 case Stmt::DesignatedInitExprClass:
556 case Stmt::BlockExprClass:
557 case Stmt::BlockDeclRefExprClass:
558 return false;
559
560 // Cases requiring custom logic
561 case Stmt::SizeOfAlignOfExprClass: {
562 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
563 if (!SE->isSizeOf())
564 return false;
565 return SE->getTypeOfArgument()->isVariableArrayType();
566 }
567 case Stmt::DeclRefExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000568 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000569
570 // The next cases require recursion for subexpressions
571 case Stmt::BinaryOperatorClass: {
572 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000573 return CanVary(B->getRHS(), AC)
574 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000575 }
576 case Stmt::UnaryOperatorClass: {
577 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000578 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000579 switch (U->getOpcode()) {
580 case UnaryOperator::Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000581 return false;
582 default:
Tom Care245adab2010-08-18 21:17:24 +0000583 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000584 }
585 }
586 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000587 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
588 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000589 case Stmt::ConditionalOperatorClass:
Tom Care245adab2010-08-18 21:17:24 +0000590 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000591 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000592}
593
Tom Care245adab2010-08-18 21:17:24 +0000594// Returns true if a DeclRefExpr is or behaves like a constant.
595bool IdempotentOperationChecker::isConstantOrPseudoConstant(
596 const DeclRefExpr *DR,
597 AnalysisContext *AC) {
598 // Check if the type of the Decl is const-qualified
599 if (DR->getType().isConstQualified())
600 return true;
601
Tom Care50e8ac22010-08-16 21:43:52 +0000602 // Check for an enum
603 if (isa<EnumConstantDecl>(DR->getDecl()))
604 return true;
605
Tom Caredb34ab72010-08-23 19:51:57 +0000606 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
607 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000608 return true;
609
Tom Caredb34ab72010-08-23 19:51:57 +0000610 // Check if the Decl behaves like a constant. This check also takes care of
611 // static variables, which can only change between function calls if they are
612 // modified in the AST.
613 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
614 if (PCA->isPseudoConstant(VD))
615 return true;
616
617 return false;
618}
619
620// Recursively find any substatements containing VarDecl's with storage other
621// than local
622bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
623 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
624
625 if (DR)
626 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
627 if (!VD->hasLocalStorage())
628 return true;
629
630 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
631 ++I)
632 if (const Stmt *child = *I)
633 if (containsNonLocalVarDecl(child))
634 return true;
635
Tom Care50e8ac22010-08-16 21:43:52 +0000636 return false;
637}