1 //==- DeadStoresChecker.cpp - Check for stores to dead variables -*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a DeadStores, a flow-sensitive checker that looks for
11 // stores to variables that are no longer live.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/SaveAndRestore.h"
28 using namespace clang;
33 /// A simple visitor to record what VarDecls occur in EH-handling code.
34 class EHCodeVisitor : public RecursiveASTVisitor<EHCodeVisitor> {
37 llvm::DenseSet<const VarDecl *> &S;
39 bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
40 SaveAndRestore<bool> inFinally(inEH, true);
41 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
44 bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S) {
45 SaveAndRestore<bool> inCatch(inEH, true);
46 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
49 bool TraverseCXXCatchStmt(CXXCatchStmt *S) {
50 SaveAndRestore<bool> inCatch(inEH, true);
51 return TraverseStmt(S->getHandlerBlock());
54 bool VisitDeclRefExpr(DeclRefExpr *DR) {
56 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
61 EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) :
65 // FIXME: Eventually migrate into its own file, and have it managed by
69 llvm::BitVector reachable;
71 ReachableCode(const CFG &cfg)
72 : cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {}
74 void computeReachableBlocks();
76 bool isReachable(const CFGBlock *block) const {
77 return reachable[block->getBlockID()];
82 void ReachableCode::computeReachableBlocks() {
83 if (!cfg.getNumBlockIDs())
86 SmallVector<const CFGBlock*, 10> worklist;
87 worklist.push_back(&cfg.getEntry());
89 while (!worklist.empty()) {
90 const CFGBlock *block = worklist.pop_back_val();
91 llvm::BitVector::reference isReachable = reachable[block->getBlockID()];
95 for (CFGBlock::const_succ_iterator i = block->succ_begin(),
96 e = block->succ_end(); i != e; ++i)
97 if (const CFGBlock *succ = *i)
98 worklist.push_back(succ);
103 LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex) {
105 const BinaryOperator *BO =
106 dyn_cast<BinaryOperator>(Ex->IgnoreParenCasts());
109 if (BO->getOpcode() == BO_Assign) {
113 if (BO->getOpcode() == BO_Comma) {
123 class DeadStoreObs : public LiveVariables::Observer {
127 AnalysisDeclContext* AC;
129 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
130 OwningPtr<ReachableCode> reachableCode;
131 const CFGBlock *currentBlock;
132 OwningPtr<llvm::DenseSet<const VarDecl *> > InEH;
134 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
137 DeadStoreObs(const CFG &cfg, ASTContext &ctx,
138 BugReporter& br, AnalysisDeclContext* ac, ParentMap& parents,
139 llvm::SmallPtrSet<const VarDecl*, 20> &escaped)
140 : cfg(cfg), Ctx(ctx), BR(br), AC(ac), Parents(parents),
141 Escaped(escaped), currentBlock(0) {}
143 virtual ~DeadStoreObs() {}
145 bool isLive(const LiveVariables::LivenessValues &Live, const VarDecl *D) {
148 // Lazily construct the set that records which VarDecls are in
151 InEH.reset(new llvm::DenseSet<const VarDecl *>());
152 EHCodeVisitor V(*InEH.get());
153 V.TraverseStmt(AC->getBody());
155 // Treat all VarDecls that occur in EH code as being "always live"
156 // when considering to suppress dead stores. Frequently stores
157 // are followed by reads in EH code, but we don't have the ability
158 // to analyze that yet.
159 return InEH->count(D);
162 void Report(const VarDecl *V, DeadStoreKind dsk,
163 PathDiagnosticLocation L, SourceRange R) {
164 if (Escaped.count(V))
167 // Compute reachable blocks within the CFG for trivial cases
168 // where a bogus dead store can be reported because itself is unreachable.
169 if (!reachableCode.get()) {
170 reachableCode.reset(new ReachableCode(cfg));
171 reachableCode->computeReachableBlocks();
174 if (!reachableCode->isReachable(currentBlock))
178 llvm::raw_svector_ostream os(buf);
179 const char *BugType = 0;
183 BugType = "Dead initialization";
184 os << "Value stored to '" << *V
185 << "' during its initialization is never read";
189 BugType = "Dead increment";
191 if (!BugType) BugType = "Dead assignment";
192 os << "Value stored to '" << *V << "' is never read";
196 // Don't report issues in this case, e.g.: "if (x = foo())",
197 // where 'x' is unused later. We have yet to see a case where
198 // this is a real bug.
202 BR.EmitBasicReport(AC->getDecl(), BugType, "Dead store", os.str(), L, R);
205 void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val,
207 const LiveVariables::LivenessValues &Live) {
209 if (!VD->hasLocalStorage())
211 // Reference types confuse the dead stores checker. Skip them
213 if (VD->getType()->getAs<ReferenceType>())
216 if (!isLive(Live, VD) &&
217 !(VD->getAttr<UnusedAttr>() || VD->getAttr<BlocksAttr>())) {
219 PathDiagnosticLocation ExLoc =
220 PathDiagnosticLocation::createBegin(Ex, BR.getSourceManager(), AC);
221 Report(VD, dsk, ExLoc, Val->getSourceRange());
225 void CheckDeclRef(const DeclRefExpr *DR, const Expr *Val, DeadStoreKind dsk,
226 const LiveVariables::LivenessValues& Live) {
227 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
228 CheckVarDecl(VD, DR, Val, dsk, Live);
231 bool isIncrement(VarDecl *VD, const BinaryOperator* B) {
232 if (B->isCompoundAssignmentOp())
235 const Expr *RHS = B->getRHS()->IgnoreParenCasts();
236 const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS);
241 const DeclRefExpr *DR;
243 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts())))
244 if (DR->getDecl() == VD)
247 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts())))
248 if (DR->getDecl() == VD)
254 virtual void observeStmt(const Stmt *S, const CFGBlock *block,
255 const LiveVariables::LivenessValues &Live) {
257 currentBlock = block;
259 // Skip statements in macros.
260 if (S->getLocStart().isMacroID())
263 // Only cover dead stores from regular assignments. ++/-- dead stores
264 // have never flagged a real bug.
265 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
266 if (!B->isAssignmentOp()) return; // Skip non-assignments.
268 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()))
269 if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
270 // Special case: check for assigning null to a pointer.
271 // This is a common form of defensive programming.
273 LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
274 RHS = RHS->IgnoreParenCasts();
276 QualType T = VD->getType();
277 if (T->isPointerType() || T->isObjCObjectPointerType()) {
278 if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull))
282 // Special case: self-assignments. These are often used to shut up
283 // "unused variable" compiler warnings.
284 if (const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
285 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
288 // Otherwise, issue a warning.
289 DeadStoreKind dsk = Parents.isConsumedExpr(B)
291 : (isIncrement(VD,B) ? DeadIncrement : Standard);
293 CheckVarDecl(VD, DR, B->getRHS(), dsk, Live);
296 else if (const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
297 if (!U->isIncrementOp() || U->isPrefix())
300 const Stmt *parent = Parents.getParentIgnoreParenCasts(U);
301 if (!parent || !isa<ReturnStmt>(parent))
304 const Expr *Ex = U->getSubExpr()->IgnoreParenCasts();
306 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
307 CheckDeclRef(DR, U, DeadIncrement, Live);
309 else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S))
310 // Iterate through the decls. Warn if any initializers are complex
311 // expressions that are not live (never used).
312 for (DeclStmt::const_decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
315 VarDecl *V = dyn_cast<VarDecl>(*DI);
320 if (V->hasLocalStorage()) {
321 // Reference types confuse the dead stores checker. Skip them
323 if (V->getType()->getAs<ReferenceType>())
326 if (const Expr *E = V->getInit()) {
327 while (const ExprWithCleanups *exprClean =
328 dyn_cast<ExprWithCleanups>(E))
329 E = exprClean->getSubExpr();
331 // Look through transitive assignments, e.g.:
333 E = LookThroughTransitiveAssignmentsAndCommaOperators(E);
335 // Don't warn on C++ objects (yet) until we can show that their
336 // constructors/destructors don't have side effects.
337 if (isa<CXXConstructExpr>(E))
340 // A dead initialization is a variable that is dead after it
341 // is initialized. We don't flag warnings for those variables
343 if (!isLive(Live, V) && V->getAttr<UnusedAttr>() == 0) {
344 // Special case: check for initializations with constants.
348 // If x is EVER assigned a new value later, don't issue
349 // a warning. This is because such initialization can be
350 // due to defensive programming.
351 if (E->isEvaluatable(Ctx))
354 if (const DeclRefExpr *DRE =
355 dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
356 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
357 // Special case: check for initialization from constant
360 // e.g. extern const int MyConstant;
361 // int x = MyConstant;
363 if (VD->hasGlobalStorage() &&
364 VD->getType().isConstQualified())
366 // Special case: check for initialization from scalar
367 // parameters. This is often a form of defensive
368 // programming. Non-scalars are still an error since
369 // because it more likely represents an actual algorithmic
371 if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType())
375 PathDiagnosticLocation Loc =
376 PathDiagnosticLocation::create(V, BR.getSourceManager());
377 Report(V, DeadInit, Loc, E->getSourceRange());
385 } // end anonymous namespace
387 //===----------------------------------------------------------------------===//
388 // Driver function to invoke the Dead-Stores checker on a CFG.
389 //===----------------------------------------------------------------------===//
394 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
396 void operator()(const Stmt *S) {
397 // Check for '&'. Any VarDecl whose address has been taken we treat as
399 // FIXME: What about references?
400 const UnaryOperator *U = dyn_cast<UnaryOperator>(S);
403 if (U->getOpcode() != UO_AddrOf)
406 const Expr *E = U->getSubExpr()->IgnoreParenCasts();
407 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
408 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
412 } // end anonymous namespace
415 //===----------------------------------------------------------------------===//
417 //===----------------------------------------------------------------------===//
420 class DeadStoresChecker : public Checker<check::ASTCodeBody> {
422 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
423 BugReporter &BR) const {
425 // Don't do anything for template instantiations.
426 // Proving that code in a template instantiation is "dead"
427 // means proving that it is dead in all instantiations.
428 // This same problem exists with -Wunreachable-code.
429 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
430 if (FD->isTemplateInstantiation())
433 if (LiveVariables *L = mgr.getAnalysis<LiveVariables>(D)) {
434 CFG &cfg = *mgr.getCFG(D);
435 AnalysisDeclContext *AC = mgr.getAnalysisDeclContext(D);
436 ParentMap &pmap = mgr.getParentMap(D);
438 cfg.VisitBlockStmts(FS);
439 DeadStoreObs A(cfg, BR.getContext(), BR, AC, pmap, FS.Escaped);
440 L->runOnAllBlocks(A);
446 void ento::registerDeadStoresChecker(CheckerManager &mgr) {
447 mgr.registerChecker<DeadStoresChecker>();