blob: 15e9be9580405dd60fc85fca3e7fbd85a06d4493 [file] [log] [blame]
Tom Caredb2fa8a2010-07-06 21:43:29 +00001//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a set of path-sensitive checks for idempotent and/or
11// tautological operations. Each potential operation is checked along all paths
12// to see if every path results in a pointless operation.
13// +-------------------------------------------+
14// |Table of idempotent/tautological operations|
15// +-------------------------------------------+
16//+--------------------------------------------------------------------------+
17//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
18//+--------------------------------------------------------------------------+
19// +, += | | | | x | x | |
20// -, -= | | | | x | -x | |
21// *, *= | | x | x | 0 | 0 | |
22// /, /= | 1 | x | | N/A | 0 | |
23// &, &= | x | | | 0 | 0 | x | x
24// |, |= | x | | | x | x | ~0 | ~0
25// ^, ^= | 0 | | | x | x | |
26// <<, <<= | | | | x | 0 | |
27// >>, >>= | | | | x | 0 | |
28// || | 1 | 1 | 1 | x | x | 1 | 1
29// && | 1 | x | x | 0 | 0 | x | x
30// = | x | | | | | |
31// == | 1 | | | | | |
32// >= | 1 | | | | | |
33// <= | 1 | | | | | |
34// > | 0 | | | | | |
35// < | 0 | | | | | |
36// != | 0 | | | | | |
37//===----------------------------------------------------------------------===//
38//
Tom Carea7a8a452010-08-12 22:45:47 +000039// Things TODO:
Tom Caredb2fa8a2010-07-06 21:43:29 +000040// - Improved error messages
41// - Handle mixed assumptions (which assumptions can belong together?)
42// - Finer grained false positive control (levels)
Tom Carea7a8a452010-08-12 22:45:47 +000043// - Handling ~0 values
Tom Caredb2fa8a2010-07-06 21:43:29 +000044
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000045#include "ExprEngineExperimentalChecks.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"
Argyrios Kyrtzidis98cabba2010-12-22 18:51:49 +000048#include "clang/GR/BugReporter/BugReporter.h"
49#include "clang/GR/BugReporter/BugType.h"
50#include "clang/GR/PathSensitive/CheckerHelpers.h"
51#include "clang/GR/PathSensitive/CheckerVisitor.h"
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000052#include "clang/GR/PathSensitive/CoreEngine.h"
Argyrios Kyrtzidis98cabba2010-12-22 18:51:49 +000053#include "clang/GR/PathSensitive/SVals.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000054#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;
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000061using namespace GR;
Tom Caredb2fa8a2010-07-06 21:43:29 +000062
63namespace {
64class IdempotentOperationChecker
65 : public CheckerVisitor<IdempotentOperationChecker> {
Tom Careb0627952010-09-09 02:04:52 +000066public:
67 static void *getTag();
68 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
69 void PostVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000070 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, ExprEngine &Eng);
Tom Careb0627952010-09-09 02:04:52 +000071
72private:
73 // Our assumption about a particular operation.
74 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
75 RHSis0 };
76
77 void UpdateAssumption(Assumption &A, const Assumption &New);
78
79 // False positive reduction methods
80 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
81 static bool isUnused(const Expr *E, AnalysisContext *AC);
82 static bool isTruncationExtensionAssignment(const Expr *LHS,
83 const Expr *RHS);
84 bool PathWasCompletelyAnalyzed(const CFG *C,
85 const CFGBlock *CB,
Ted Kremenek33d46262010-11-13 05:04:52 +000086 const CFGStmtMap *CBM,
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000087 const CoreEngine &CE);
Tom Careb0627952010-09-09 02:04:52 +000088 static bool CanVary(const Expr *Ex,
89 AnalysisContext *AC);
90 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
91 AnalysisContext *AC);
92 static bool containsNonLocalVarDecl(const Stmt *S);
93 const ExplodedNodeSet getLastRelevantNodes(const CFGBlock *Begin,
94 const ExplodedNode *N);
95
96 // Hash table and related data structures
97 struct BinaryOperatorData {
98 BinaryOperatorData() : assumption(Possible), analysisContext(0) {}
99
100 Assumption assumption;
101 AnalysisContext *analysisContext;
102 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
103 // BinaryOperator
104 };
105 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
106 AssumptionMap;
107 AssumptionMap hash;
108
109 // A class that performs reachability queries for CFGBlocks. Several internal
110 // checks in this checker require reachability information. The requests all
111 // tend to have a common destination, so we lazily do a predecessor search
112 // from the destination node and cache the results to prevent work
113 // duplication.
114 class CFGReachabilityAnalysis {
115 typedef llvm::SmallSet<unsigned, 32> ReachableSet;
116 typedef llvm::DenseMap<unsigned, ReachableSet> ReachableMap;
117 ReachableSet analyzed;
118 ReachableMap reachable;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000119 public:
Tom Careb0627952010-09-09 02:04:52 +0000120 inline bool isReachable(const CFGBlock *Src, const CFGBlock *Dst);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000121 private:
Tom Careb0627952010-09-09 02:04:52 +0000122 void MapReachability(const CFGBlock *Dst);
123 };
124 CFGReachabilityAnalysis CRA;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000125};
126}
127
128void *IdempotentOperationChecker::getTag() {
129 static int x = 0;
130 return &x;
131}
132
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000133void GR::RegisterIdempotentOperationChecker(ExprEngine &Eng) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000134 Eng.registerCheck(new IdempotentOperationChecker());
135}
136
137void IdempotentOperationChecker::PreVisitBinaryOperator(
138 CheckerContext &C,
139 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000140 // Find or create an entry in the hash for this BinaryOperator instance.
141 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000142 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
143 // been created yet.
144 BinaryOperatorData &Data = hash[B];
145 Assumption &A = Data.assumption;
Tom Care245adab2010-08-18 21:17:24 +0000146 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care2bbbe502010-09-02 23:30:22 +0000147 Data.analysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000148
149 // If we already have visited this node on a path that does not contain an
150 // idempotent operation, return immediately.
151 if (A == Impossible)
152 return;
153
Tom Carea7a8a452010-08-12 22:45:47 +0000154 // Retrieve both sides of the operator and determine if they can vary (which
155 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000156 const Expr *LHS = B->getLHS();
157 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000158
Tom Caredb34ab72010-08-23 19:51:57 +0000159 // At this stage we can calculate whether each side contains a false positive
160 // that applies to all operators. We only need to calculate this the first
161 // time.
162 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000163 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000164 // An expression contains a false positive if it can't vary, or if it
165 // contains a known false positive VarDecl.
166 LHSContainsFalsePositive = !CanVary(LHS, AC)
167 || containsNonLocalVarDecl(LHS);
168 RHSContainsFalsePositive = !CanVary(RHS, AC)
169 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000170 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000171
172 const GRState *state = C.getState();
173
174 SVal LHSVal = state->getSVal(LHS);
175 SVal RHSVal = state->getSVal(RHS);
176
177 // If either value is unknown, we can't be 100% sure of all paths.
178 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
179 A = Impossible;
180 return;
181 }
182 BinaryOperator::Opcode Op = B->getOpcode();
183
184 // Dereference the LHS SVal if this is an assign operation
185 switch (Op) {
186 default:
187 break;
188
189 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000190 case BO_AddAssign:
191 case BO_SubAssign:
192 case BO_MulAssign:
193 case BO_DivAssign:
194 case BO_AndAssign:
195 case BO_OrAssign:
196 case BO_XorAssign:
197 case BO_ShlAssign:
198 case BO_ShrAssign:
199 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000200 // Assign statements have one extra level of indirection
201 if (!isa<Loc>(LHSVal)) {
202 A = Impossible;
203 return;
204 }
Ted Kremenek96ebad62010-09-09 07:13:00 +0000205 LHSVal = state->getSVal(cast<Loc>(LHSVal), LHS->getType());
Tom Caredb2fa8a2010-07-06 21:43:29 +0000206 }
207
208
209 // We now check for various cases which result in an idempotent operation.
210
211 // x op x
212 switch (Op) {
213 default:
214 break; // We don't care about any other operators.
215
216 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000217 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000218 // x Assign x can be used to silence unused variable warnings intentionally.
219 // If this is a self assignment and the variable is referenced elsewhere,
Tom Care84c24ed2010-09-07 20:27:56 +0000220 // and the assignment is not a truncation or extension, then it is a false
221 // positive.
Tom Care6216dc02010-08-30 19:25:43 +0000222 if (isSelfAssign(LHS, RHS)) {
Tom Care84c24ed2010-09-07 20:27:56 +0000223 if (!isUnused(LHS, AC) && !isTruncationExtensionAssignment(LHS, RHS)) {
Tom Care6216dc02010-08-30 19:25:43 +0000224 UpdateAssumption(A, Equal);
225 return;
226 }
227 else {
228 A = Impossible;
229 return;
230 }
Tom Caredf4ca422010-07-16 20:41:41 +0000231 }
232
John McCall2de56d12010-08-25 11:45:40 +0000233 case BO_SubAssign:
234 case BO_DivAssign:
235 case BO_AndAssign:
236 case BO_OrAssign:
237 case BO_XorAssign:
238 case BO_Sub:
239 case BO_Div:
240 case BO_And:
241 case BO_Or:
242 case BO_Xor:
243 case BO_LOr:
244 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000245 case BO_EQ:
246 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000247 if (LHSVal != RHSVal || LHSContainsFalsePositive
248 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000249 break;
250 UpdateAssumption(A, Equal);
251 return;
252 }
253
254 // x op 1
255 switch (Op) {
256 default:
257 break; // We don't care about any other operators.
258
259 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000260 case BO_MulAssign:
261 case BO_DivAssign:
262 case BO_Mul:
263 case BO_Div:
264 case BO_LOr:
265 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000266 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000267 break;
268 UpdateAssumption(A, RHSis1);
269 return;
270 }
271
272 // 1 op x
273 switch (Op) {
274 default:
275 break; // We don't care about any other operators.
276
277 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000278 case BO_MulAssign:
279 case BO_Mul:
280 case BO_LOr:
281 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000282 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000283 break;
284 UpdateAssumption(A, LHSis1);
285 return;
286 }
287
288 // x op 0
289 switch (Op) {
290 default:
291 break; // We don't care about any other operators.
292
293 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000294 case BO_AddAssign:
295 case BO_SubAssign:
296 case BO_MulAssign:
297 case BO_AndAssign:
298 case BO_OrAssign:
299 case BO_XorAssign:
300 case BO_Add:
301 case BO_Sub:
302 case BO_Mul:
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 (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000311 break;
312 UpdateAssumption(A, RHSis0);
313 return;
314 }
315
316 // 0 op x
317 switch (Op) {
318 default:
319 break; // We don't care about any other operators.
320
321 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000322 //case BO_AddAssign: // Common false positive
323 case BO_SubAssign: // Check only if unsigned
324 case BO_MulAssign:
325 case BO_DivAssign:
326 case BO_AndAssign:
327 //case BO_OrAssign: // Common false positive
328 //case BO_XorAssign: // Common false positive
329 case BO_ShlAssign:
330 case BO_ShrAssign:
331 case BO_Add:
332 case BO_Sub:
333 case BO_Mul:
334 case BO_Div:
335 case BO_And:
336 case BO_Or:
337 case BO_Xor:
338 case BO_Shl:
339 case BO_Shr:
340 case BO_LOr:
341 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000342 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000343 break;
344 UpdateAssumption(A, LHSis0);
345 return;
346 }
347
348 // If we get to this point, there has been a valid use of this operation.
349 A = Impossible;
350}
351
Tom Care2bbbe502010-09-02 23:30:22 +0000352// At the post visit stage, the predecessor ExplodedNode will be the
353// BinaryOperator that was just created. We use this hook to collect the
354// ExplodedNode.
355void IdempotentOperationChecker::PostVisitBinaryOperator(
356 CheckerContext &C,
357 const BinaryOperator *B) {
358 // Add the ExplodedNode we just visited
359 BinaryOperatorData &Data = hash[B];
Ted Kremenek96ebad62010-09-09 07:13:00 +0000360 assert(isa<BinaryOperator>(cast<StmtPoint>(C.getPredecessor()
361 ->getLocation()).getStmt()));
Tom Care2bbbe502010-09-02 23:30:22 +0000362 Data.explodedNodes.Add(C.getPredecessor());
363}
364
Tom Caredb2fa8a2010-07-06 21:43:29 +0000365void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000366 BugReporter &BR,
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000367 ExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000368 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000369 // Iterate over the hash to see if we have any paths with definite
370 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000371 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
372 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000373 const BinaryOperatorData &Data = i->second;
374 const Assumption &A = Data.assumption;
375 AnalysisContext *AC = Data.analysisContext;
376 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000377
Tom Carea7a8a452010-08-12 22:45:47 +0000378 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000379
Tom Carea7a8a452010-08-12 22:45:47 +0000380 if (A == Impossible)
381 continue;
382
383 // If the analyzer did not finish, check to see if we can still emit this
384 // warning
385 if (Eng.hasWorkRemaining()) {
386 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
387 &AC->getParentMap());
388
389 // If we can trace back
390 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
Ted Kremenek33d46262010-11-13 05:04:52 +0000391 CBM->getBlock(B), CBM,
Tom Carea7a8a452010-08-12 22:45:47 +0000392 Eng.getCoreEngine()))
393 continue;
394
395 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000396 }
Tom Carea7a8a452010-08-12 22:45:47 +0000397
Tom Care2bbbe502010-09-02 23:30:22 +0000398 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000399 llvm::SmallString<128> buf;
400 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000401 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000402 switch (A) {
403 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000404 LHSRelevant = true;
405 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000406 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000407 os << "Assigned value is always the same as the existing value";
408 else
409 os << "Both operands to '" << B->getOpcodeStr()
410 << "' always have the same value";
411 break;
412 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000413 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000414 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
415 break;
416 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000417 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000418 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
419 break;
420 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000421 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000422 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
423 break;
424 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000425 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000426 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
427 break;
428 case Possible:
429 llvm_unreachable("Operation was never marked with an assumption");
430 case Impossible:
431 llvm_unreachable(0);
432 }
433
Tom Care2bbbe502010-09-02 23:30:22 +0000434 // Add a report for each ExplodedNode
435 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
436 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
437
438 // Add source ranges and visitor hooks
439 if (LHSRelevant) {
440 const Expr *LHS = i->first->getLHS();
441 report->addRange(LHS->getSourceRange());
442 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
443 }
444 if (RHSRelevant) {
445 const Expr *RHS = i->first->getRHS();
446 report->addRange(i->first->getRHS()->getSourceRange());
447 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
448 }
449
450 BR.EmitReport(report);
451 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000452 }
453}
454
455// Updates the current assumption given the new assumption
456inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
457 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000458// If the assumption is the same, there is nothing to do
459 if (A == New)
460 return;
461
Tom Caredb2fa8a2010-07-06 21:43:29 +0000462 switch (A) {
463 // If we don't currently have an assumption, set it
464 case Possible:
465 A = New;
466 return;
467
468 // If we have determined that a valid state happened, ignore the new
469 // assumption.
470 case Impossible:
471 return;
472
473 // Any other case means that we had a different assumption last time. We don't
474 // currently support mixing assumptions for diagnostic reasons, so we set
475 // our assumption to be impossible.
476 default:
477 A = Impossible;
478 return;
479 }
480}
481
Tom Care6216dc02010-08-30 19:25:43 +0000482// Check for a statement where a variable is self assigned to possibly avoid an
483// unused variable warning.
484bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000485 LHS = LHS->IgnoreParenCasts();
486 RHS = RHS->IgnoreParenCasts();
487
488 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
489 if (!LHS_DR)
490 return false;
491
Tom Careef52bcb2010-08-24 21:09:07 +0000492 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
493 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000494 return false;
495
496 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
497 if (!RHS_DR)
498 return false;
499
Tom Careef52bcb2010-08-24 21:09:07 +0000500 if (VD != RHS_DR->getDecl())
501 return false;
502
Tom Care6216dc02010-08-30 19:25:43 +0000503 return true;
504}
505
506// Returns true if the Expr points to a VarDecl that is not read anywhere
507// outside of self-assignments.
508bool IdempotentOperationChecker::isUnused(const Expr *E,
509 AnalysisContext *AC) {
510 if (!E)
511 return false;
512
513 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
514 if (!DR)
515 return false;
516
517 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
518 if (!VD)
519 return false;
520
Tom Careef52bcb2010-08-24 21:09:07 +0000521 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
522 return false;
523
524 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000525}
526
527// Check for self casts truncating/extending a variable
528bool IdempotentOperationChecker::isTruncationExtensionAssignment(
529 const Expr *LHS,
530 const Expr *RHS) {
531
532 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
533 if (!LHS_DR)
534 return false;
535
536 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
537 if (!VD)
538 return false;
539
540 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
541 if (!RHS_DR)
542 return false;
543
544 if (VD != RHS_DR->getDecl())
545 return false;
546
John McCallf6a16482010-12-04 03:47:34 +0000547 return dyn_cast<DeclRefExpr>(RHS->IgnoreParenLValueCasts()) == NULL;
Tom Caredf4ca422010-07-16 20:41:41 +0000548}
549
Tom Carea7a8a452010-08-12 22:45:47 +0000550// Returns false if a path to this block was not completely analyzed, or true
551// otherwise.
552bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
553 const CFG *C,
554 const CFGBlock *CB,
Ted Kremenek33d46262010-11-13 05:04:52 +0000555 const CFGStmtMap *CBM,
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000556 const CoreEngine &CE) {
Tom Careb0627952010-09-09 02:04:52 +0000557 // Test for reachability from any aborted blocks to this block
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000558 typedef CoreEngine::BlocksAborted::const_iterator AbortedIterator;
Tom Carea7a8a452010-08-12 22:45:47 +0000559 for (AbortedIterator I = CE.blocks_aborted_begin(),
560 E = CE.blocks_aborted_end(); I != E; ++I) {
561 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000562
Tom Carea7a8a452010-08-12 22:45:47 +0000563 // The destination block on the BlockEdge is the first block that was not
Tom Careb0627952010-09-09 02:04:52 +0000564 // analyzed. If we can reach this block from the aborted block, then this
565 // block was not completely analyzed.
566 if (CRA.isReachable(BE.getDst(), CB))
Tom Carea7a8a452010-08-12 22:45:47 +0000567 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000568 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000569
570 // For the items still on the worklist, see if they are in blocks that
571 // can eventually reach 'CB'.
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000572 class VisitWL : public WorkList::Visitor {
Ted Kremenek33d46262010-11-13 05:04:52 +0000573 const CFGStmtMap *CBM;
574 const CFGBlock *TargetBlock;
575 CFGReachabilityAnalysis &CRA;
576 public:
577 VisitWL(const CFGStmtMap *cbm, const CFGBlock *targetBlock,
578 CFGReachabilityAnalysis &cra)
579 : CBM(cbm), TargetBlock(targetBlock), CRA(cra) {}
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000580 virtual bool Visit(const WorkListUnit &U) {
Ted Kremenek33d46262010-11-13 05:04:52 +0000581 ProgramPoint P = U.getNode()->getLocation();
582 const CFGBlock *B = 0;
583 if (StmtPoint *SP = dyn_cast<StmtPoint>(&P)) {
584 B = CBM->getBlock(SP->getStmt());
585 }
Ted Kremeneked023662010-11-13 05:12:26 +0000586 else if (BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
587 B = BE->getDst();
588 }
589 else if (BlockEntrance *BEnt = dyn_cast<BlockEntrance>(&P)) {
590 B = BEnt->getBlock();
591 }
592 else if (BlockExit *BExit = dyn_cast<BlockExit>(&P)) {
593 B = BExit->getBlock();
594 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000595 if (!B)
596 return true;
597
598 return CRA.isReachable(B, TargetBlock);
599 }
600 };
601 VisitWL visitWL(CBM, CB, CRA);
602 // Were there any items in the worklist that could potentially reach
603 // this block?
604 if (CE.getWorkList()->VisitItemsInWorkList(visitWL))
605 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000606
Tom Careb0627952010-09-09 02:04:52 +0000607 // Verify that this block is reachable from the entry block
608 if (!CRA.isReachable(&C->getEntry(), CB))
609 return false;
610
Tom Carea7a8a452010-08-12 22:45:47 +0000611 // If we get to this point, there is no connection to the entry block or an
612 // aborted block. This path is unreachable and we can report the error.
613 return true;
614}
615
616// Recursive function that determines whether an expression contains any element
617// that varies. This could be due to a compile-time constant like sizeof. An
618// expression may also involve a variable that behaves like a constant. The
619// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000620bool IdempotentOperationChecker::CanVary(const Expr *Ex,
621 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000622 // Parentheses and casts are irrelevant here
623 Ex = Ex->IgnoreParenCasts();
624
625 if (Ex->getLocStart().isMacroID())
626 return false;
627
628 switch (Ex->getStmtClass()) {
629 // Trivially true cases
630 case Stmt::ArraySubscriptExprClass:
631 case Stmt::MemberExprClass:
632 case Stmt::StmtExprClass:
633 case Stmt::CallExprClass:
634 case Stmt::VAArgExprClass:
635 case Stmt::ShuffleVectorExprClass:
636 return true;
637 default:
638 return true;
639
640 // Trivially false cases
641 case Stmt::IntegerLiteralClass:
642 case Stmt::CharacterLiteralClass:
643 case Stmt::FloatingLiteralClass:
644 case Stmt::PredefinedExprClass:
645 case Stmt::ImaginaryLiteralClass:
646 case Stmt::StringLiteralClass:
647 case Stmt::OffsetOfExprClass:
648 case Stmt::CompoundLiteralExprClass:
649 case Stmt::AddrLabelExprClass:
Francois Pichetf1872372010-12-08 22:35:30 +0000650 case Stmt::BinaryTypeTraitExprClass:
Tom Carea7a8a452010-08-12 22:45:47 +0000651 case Stmt::GNUNullExprClass:
652 case Stmt::InitListExprClass:
653 case Stmt::DesignatedInitExprClass:
654 case Stmt::BlockExprClass:
655 case Stmt::BlockDeclRefExprClass:
656 return false;
657
658 // Cases requiring custom logic
659 case Stmt::SizeOfAlignOfExprClass: {
660 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
661 if (!SE->isSizeOf())
662 return false;
663 return SE->getTypeOfArgument()->isVariableArrayType();
664 }
665 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000666 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000667 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000668
669 // The next cases require recursion for subexpressions
670 case Stmt::BinaryOperatorClass: {
671 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Ted Kremenek74faec22010-10-29 01:06:54 +0000672
673 // Exclude cases involving pointer arithmetic. These are usually
674 // false positives.
675 if (B->getOpcode() == BO_Sub || B->getOpcode() == BO_Add)
676 if (B->getLHS()->getType()->getAs<PointerType>())
677 return false;
678
Tom Care245adab2010-08-18 21:17:24 +0000679 return CanVary(B->getRHS(), AC)
680 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000681 }
682 case Stmt::UnaryOperatorClass: {
683 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000684 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000685 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000686 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000687 return false;
688 default:
Tom Care245adab2010-08-18 21:17:24 +0000689 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000690 }
691 }
692 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000693 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
694 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000695 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000696 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000697 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000698}
699
Tom Care245adab2010-08-18 21:17:24 +0000700// Returns true if a DeclRefExpr is or behaves like a constant.
701bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000702 const DeclRefExpr *DR,
703 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000704 // Check if the type of the Decl is const-qualified
705 if (DR->getType().isConstQualified())
706 return true;
707
Tom Care50e8ac22010-08-16 21:43:52 +0000708 // Check for an enum
709 if (isa<EnumConstantDecl>(DR->getDecl()))
710 return true;
711
Tom Caredb34ab72010-08-23 19:51:57 +0000712 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
713 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000714 return true;
715
Tom Caredb34ab72010-08-23 19:51:57 +0000716 // Check if the Decl behaves like a constant. This check also takes care of
717 // static variables, which can only change between function calls if they are
718 // modified in the AST.
719 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
720 if (PCA->isPseudoConstant(VD))
721 return true;
722
723 return false;
724}
725
726// Recursively find any substatements containing VarDecl's with storage other
727// than local
728bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
729 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
730
731 if (DR)
732 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
733 if (!VD->hasLocalStorage())
734 return true;
735
736 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
737 ++I)
738 if (const Stmt *child = *I)
739 if (containsNonLocalVarDecl(child))
740 return true;
741
Tom Care50e8ac22010-08-16 21:43:52 +0000742 return false;
743}
Tom Careb0627952010-09-09 02:04:52 +0000744
745// Returns the successor nodes of N whose CFGBlocks cannot reach N's CFGBlock.
746// This effectively gives us a set of points in the ExplodedGraph where
747// subsequent execution could not affect the idempotent operation on this path.
748// This is useful for displaying paths after the point of the error, providing
749// an example of how this idempotent operation cannot change.
750const ExplodedNodeSet IdempotentOperationChecker::getLastRelevantNodes(
751 const CFGBlock *Begin, const ExplodedNode *N) {
752 std::deque<const ExplodedNode *> WorkList;
753 llvm::SmallPtrSet<const ExplodedNode *, 32> Visited;
754 ExplodedNodeSet Result;
755
756 WorkList.push_back(N);
757
758 while (!WorkList.empty()) {
759 const ExplodedNode *Head = WorkList.front();
760 WorkList.pop_front();
761 Visited.insert(Head);
762
763 const ProgramPoint &PP = Head->getLocation();
764 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&PP)) {
765 // Get the CFGBlock and test the reachability
766 const CFGBlock *CB = BE->getBlock();
767
768 // If we cannot reach the beginning CFGBlock from this block, then we are
769 // finished
770 if (!CRA.isReachable(CB, Begin)) {
771 Result.Add(const_cast<ExplodedNode *>(Head));
772 continue;
773 }
774 }
775
776 // Add unvisited children to the worklist
777 for (ExplodedNode::const_succ_iterator I = Head->succ_begin(),
778 E = Head->succ_end(); I != E; ++I)
779 if (!Visited.count(*I))
780 WorkList.push_back(*I);
781 }
782
783 // Return the ExplodedNodes that were found
784 return Result;
785}
786
787bool IdempotentOperationChecker::CFGReachabilityAnalysis::isReachable(
788 const CFGBlock *Src,
789 const CFGBlock *Dst) {
790 const unsigned DstBlockID = Dst->getBlockID();
791
792 // If we haven't analyzed the destination node, run the analysis now
793 if (!analyzed.count(DstBlockID)) {
794 MapReachability(Dst);
795 analyzed.insert(DstBlockID);
796 }
797
798 // Return the cached result
799 return reachable[DstBlockID].count(Src->getBlockID());
800}
801
802// Maps reachability to a common node by walking the predecessors of the
803// destination node.
804void IdempotentOperationChecker::CFGReachabilityAnalysis::MapReachability(
805 const CFGBlock *Dst) {
806 std::deque<const CFGBlock *> WorkList;
807 // Maintain a visited list to ensure we don't get stuck on cycles
808 llvm::SmallSet<unsigned, 32> Visited;
809 ReachableSet &DstReachability = reachable[Dst->getBlockID()];
810
811 // Start searching from the destination node, since we commonly will perform
812 // multiple queries relating to a destination node.
813 WorkList.push_back(Dst);
814
815 bool firstRun = true;
816 while (!WorkList.empty()) {
817 const CFGBlock *Head = WorkList.front();
818 WorkList.pop_front();
819 Visited.insert(Head->getBlockID());
820
821 // Update reachability information for this node -> Dst
822 if (!firstRun)
823 // Don't insert Dst -> Dst unless it was a predecessor of itself
824 DstReachability.insert(Head->getBlockID());
825 else
826 firstRun = false;
827
828 // Add the predecessors to the worklist unless we have already visited them
829 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
830 I != Head->pred_end(); ++I)
831 if (!Visited.count((*I)->getBlockID()))
832 WorkList.push_back(*I);
833 }
834}