blob: f7b5f61cfb8aa2097d1147421acaaa3648f58c7d [file] [log] [blame]
Ted Kremenekf2248202011-01-13 20:58:56 +00001//==- DeadStoresChecker.cpp - Check for stores to dead variables -*- C++ -*-==//
Ted Kremenek1bb9f252007-09-06 23:01:46 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek1bb9f252007-09-06 23:01:46 +00007//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif3a8edd82008-03-06 10:40:09 +000010// This file defines a DeadStores, a flow-sensitive checker that looks for
Ted Kremenek1bb9f252007-09-06 23:01:46 +000011// stores to variables that are no longer live.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +000015#include "ClangSACheckers.h"
Ted Kremenek2f1a79d2007-09-11 17:24:14 +000016#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Ted Kremenek34a69172008-06-20 21:45:25 +000018#include "clang/AST/ParentMap.h"
Ted Kremenekcadd9f12012-09-06 22:32:48 +000019#include "clang/AST/RecursiveASTVisitor.h"
Ted Kremenek8de92c02012-10-30 04:43:51 +000020#include "clang/Analysis/Analyses/LiveVariables.h"
Ted Kremenek8de92c02012-10-30 04:43:51 +000021#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"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Ted Kremenekcadd9f12012-09-06 22:32:48 +000026#include "llvm/Support/SaveAndRestore.h"
Ted Kremenek1bb9f252007-09-06 23:01:46 +000027
28using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000029using namespace ento;
Ted Kremenek1bb9f252007-09-06 23:01:46 +000030
Ted Kremenek3a0678e2015-09-08 03:50:52 +000031namespace {
32
Ted Kremenekcadd9f12012-09-06 22:32:48 +000033/// A simple visitor to record what VarDecls occur in EH-handling code.
34class EHCodeVisitor : public RecursiveASTVisitor<EHCodeVisitor> {
35public:
36 bool inEH;
37 llvm::DenseSet<const VarDecl *> &S;
Ted Kremenek3a0678e2015-09-08 03:50:52 +000038
Ted Kremenekcadd9f12012-09-06 22:32:48 +000039 bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
40 SaveAndRestore<bool> inFinally(inEH, true);
41 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
42 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000043
Ted Kremenekcadd9f12012-09-06 22:32:48 +000044 bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S) {
45 SaveAndRestore<bool> inCatch(inEH, true);
46 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
47 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000048
Ted Kremenekcadd9f12012-09-06 22:32:48 +000049 bool TraverseCXXCatchStmt(CXXCatchStmt *S) {
50 SaveAndRestore<bool> inCatch(inEH, true);
51 return TraverseStmt(S->getHandlerBlock());
52 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000053
Ted Kremenekcadd9f12012-09-06 22:32:48 +000054 bool VisitDeclRefExpr(DeclRefExpr *DR) {
55 if (inEH)
56 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
57 S.insert(D);
58 return true;
59 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000060
Ted Kremenekcadd9f12012-09-06 22:32:48 +000061 EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) :
62 inEH(false), S(S) {}
63};
Ted Kremenek34a69172008-06-20 21:45:25 +000064
Ted Kremenek9865d7f2011-02-11 23:24:26 +000065// FIXME: Eventually migrate into its own file, and have it managed by
66// AnalysisManager.
67class ReachableCode {
68 const CFG &cfg;
69 llvm::BitVector reachable;
70public:
71 ReachableCode(const CFG &cfg)
72 : cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {}
Ted Kremenek3a0678e2015-09-08 03:50:52 +000073
Ted Kremenek9865d7f2011-02-11 23:24:26 +000074 void computeReachableBlocks();
Ted Kremenek3a0678e2015-09-08 03:50:52 +000075
Ted Kremenek9865d7f2011-02-11 23:24:26 +000076 bool isReachable(const CFGBlock *block) const {
77 return reachable[block->getBlockID()];
78 }
79};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000080}
Ted Kremenek9865d7f2011-02-11 23:24:26 +000081
82void ReachableCode::computeReachableBlocks() {
83 if (!cfg.getNumBlockIDs())
84 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +000085
Chris Lattner0e62c1c2011-07-23 10:55:15 +000086 SmallVector<const CFGBlock*, 10> worklist;
Ted Kremenek9865d7f2011-02-11 23:24:26 +000087 worklist.push_back(&cfg.getEntry());
Robert Wilhelm25284cc2013-08-23 16:11:15 +000088
Ted Kremenek9865d7f2011-02-11 23:24:26 +000089 while (!worklist.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000090 const CFGBlock *block = worklist.pop_back_val();
Ted Kremenek9865d7f2011-02-11 23:24:26 +000091 llvm::BitVector::reference isReachable = reachable[block->getBlockID()];
92 if (isReachable)
93 continue;
94 isReachable = true;
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);
99 }
100}
101
Anna Zaks144579e2013-04-25 21:52:35 +0000102static const Expr *
103LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex) {
Ted Kremenekdc53f002012-04-04 19:58:03 +0000104 while (Ex) {
105 const BinaryOperator *BO =
106 dyn_cast<BinaryOperator>(Ex->IgnoreParenCasts());
107 if (!BO)
108 break;
109 if (BO->getOpcode() == BO_Assign) {
110 Ex = BO->getRHS();
111 continue;
112 }
Anna Zaks144579e2013-04-25 21:52:35 +0000113 if (BO->getOpcode() == BO_Comma) {
114 Ex = BO->getRHS();
115 continue;
116 }
Ted Kremenekdc53f002012-04-04 19:58:03 +0000117 break;
118 }
119 return Ex;
120}
121
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000122namespace {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000123class DeadStoreObs : public LiveVariables::Observer {
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000124 const CFG &cfg;
Chris Lattner254987c2007-09-15 23:21:08 +0000125 ASTContext &Ctx;
Ted Kremenekc18255d2008-07-14 20:56:04 +0000126 BugReporter& BR;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000127 const CheckerBase *Checker;
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000128 AnalysisDeclContext* AC;
Ted Kremenek34a69172008-06-20 21:45:25 +0000129 ParentMap& Parents;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000130 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000131 std::unique_ptr<ReachableCode> reachableCode;
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000132 const CFGBlock *currentBlock;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000133 std::unique_ptr<llvm::DenseSet<const VarDecl *>> InEH;
Mike Stump11289f42009-09-09 15:08:12 +0000134
Ted Kremenekecc851b2008-07-23 21:16:38 +0000135 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
Mike Stump11289f42009-09-09 15:08:12 +0000136
Ted Kremenek1bb9f252007-09-06 23:01:46 +0000137public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000138 DeadStoreObs(const CFG &cfg, ASTContext &ctx, BugReporter &br,
139 const CheckerBase *checker, AnalysisDeclContext *ac,
140 ParentMap &parents,
141 llvm::SmallPtrSet<const VarDecl *, 20> &escaped)
142 : cfg(cfg), Ctx(ctx), BR(br), Checker(checker), AC(ac), Parents(parents),
Craig Topper0dbb7832014-05-27 02:45:47 +0000143 Escaped(escaped), currentBlock(nullptr) {}
Mike Stump11289f42009-09-09 15:08:12 +0000144
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000145 ~DeadStoreObs() override {}
Ted Kremenek8b0dba32009-04-01 06:52:48 +0000146
Ted Kremenekcadd9f12012-09-06 22:32:48 +0000147 bool isLive(const LiveVariables::LivenessValues &Live, const VarDecl *D) {
148 if (Live.isLive(D))
149 return true;
150 // Lazily construct the set that records which VarDecls are in
151 // EH code.
152 if (!InEH.get()) {
153 InEH.reset(new llvm::DenseSet<const VarDecl *>());
154 EHCodeVisitor V(*InEH.get());
155 V.TraverseStmt(AC->getBody());
156 }
157 // Treat all VarDecls that occur in EH code as being "always live"
158 // when considering to suppress dead stores. Frequently stores
159 // are followed by reads in EH code, but we don't have the ability
160 // to analyze that yet.
161 return InEH->count(D);
162 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000163
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000164 void Report(const VarDecl *V, DeadStoreKind dsk,
Anna Zaksc29bed32011-09-20 21:38:35 +0000165 PathDiagnosticLocation L, SourceRange R) {
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000166 if (Escaped.count(V))
167 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000168
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000169 // Compute reachable blocks within the CFG for trivial cases
170 // where a bogus dead store can be reported because itself is unreachable.
171 if (!reachableCode.get()) {
172 reachableCode.reset(new ReachableCode(cfg));
173 reachableCode->computeReachableBlocks();
174 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000175
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000176 if (!reachableCode->isReachable(currentBlock))
177 return;
Ted Kremenekc18255d2008-07-14 20:56:04 +0000178
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000179 SmallString<64> buf;
Jordy Rose82c673d2011-08-21 05:25:15 +0000180 llvm::raw_svector_ostream os(buf);
Craig Topper0dbb7832014-05-27 02:45:47 +0000181 const char *BugType = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000182
Ted Kremenekecc851b2008-07-23 21:16:38 +0000183 switch (dsk) {
Ted Kremenekecc851b2008-07-23 21:16:38 +0000184 case DeadInit:
Ted Kremenek6e4c2842009-04-02 22:50:16 +0000185 BugType = "Dead initialization";
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000186 os << "Value stored to '" << *V
Jordy Rose82c673d2011-08-21 05:25:15 +0000187 << "' during its initialization is never read";
Ted Kremenekecc851b2008-07-23 21:16:38 +0000188 break;
Mike Stump11289f42009-09-09 15:08:12 +0000189
Ted Kremenekecc851b2008-07-23 21:16:38 +0000190 case DeadIncrement:
Ted Kremenek6e4c2842009-04-02 22:50:16 +0000191 BugType = "Dead increment";
Galina Kistanovaa65d5782017-06-03 06:26:27 +0000192 LLVM_FALLTHROUGH;
Ted Kremenekecc851b2008-07-23 21:16:38 +0000193 case Standard:
Ted Kremenek6e4c2842009-04-02 22:50:16 +0000194 if (!BugType) BugType = "Dead assignment";
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000195 os << "Value stored to '" << *V << "' is never read";
Ted Kremenekecc851b2008-07-23 21:16:38 +0000196 break;
Mike Stump11289f42009-09-09 15:08:12 +0000197
Ted Kremenekecc851b2008-07-23 21:16:38 +0000198 case Enclosing:
Ted Kremenekf2248202011-01-13 20:58:56 +0000199 // Don't report issues in this case, e.g.: "if (x = foo())",
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000200 // where 'x' is unused later. We have yet to see a case where
Ted Kremenekf2248202011-01-13 20:58:56 +0000201 // this is a real bug.
202 return;
Ted Kremenek81bfc072008-07-15 18:06:32 +0000203 }
Mike Stump11289f42009-09-09 15:08:12 +0000204
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000205 BR.EmitBasicReport(AC->getDecl(), Checker, BugType, "Dead store", os.str(),
206 L, R);
Ted Kremenek34a69172008-06-20 21:45:25 +0000207 }
Mike Stump11289f42009-09-09 15:08:12 +0000208
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000209 void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val,
Ted Kremenekecc851b2008-07-23 21:16:38 +0000210 DeadStoreKind dsk,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000211 const LiveVariables::LivenessValues &Live) {
Ted Kremenek34a69172008-06-20 21:45:25 +0000212
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000213 if (!VD->hasLocalStorage())
214 return;
215 // Reference types confuse the dead stores checker. Skip them
216 // for now.
217 if (VD->getType()->getAs<ReferenceType>())
218 return;
219
Ted Kremenekcadd9f12012-09-06 22:32:48 +0000220 if (!isLive(Live, VD) &&
Ted Kremenek0f833902014-01-15 00:59:23 +0000221 !(VD->hasAttr<UnusedAttr>() || VD->hasAttr<BlocksAttr>() ||
222 VD->hasAttr<ObjCPreciseLifetimeAttr>())) {
Anna Zaksc29bed32011-09-20 21:38:35 +0000223
224 PathDiagnosticLocation ExLoc =
225 PathDiagnosticLocation::createBegin(Ex, BR.getSourceManager(), AC);
226 Report(VD, dsk, ExLoc, Val->getSourceRange());
227 }
Ted Kremenek91f035c2008-05-21 22:59:16 +0000228 }
Mike Stump11289f42009-09-09 15:08:12 +0000229
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000230 void CheckDeclRef(const DeclRefExpr *DR, const Expr *Val, DeadStoreKind dsk,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000231 const LiveVariables::LivenessValues& Live) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000232 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000233 CheckVarDecl(VD, DR, Val, dsk, Live);
Ted Kremenekecc851b2008-07-23 21:16:38 +0000234 }
Mike Stump11289f42009-09-09 15:08:12 +0000235
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000236 bool isIncrement(VarDecl *VD, const BinaryOperator* B) {
Ted Kremenekecc851b2008-07-23 21:16:38 +0000237 if (B->isCompoundAssignmentOp())
238 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000239
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000240 const Expr *RHS = B->getRHS()->IgnoreParenCasts();
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000241 const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS);
Mike Stump11289f42009-09-09 15:08:12 +0000242
Ted Kremenekecc851b2008-07-23 21:16:38 +0000243 if (!BRHS)
244 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000245
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000246 const DeclRefExpr *DR;
Mike Stump11289f42009-09-09 15:08:12 +0000247
Ted Kremenekecc851b2008-07-23 21:16:38 +0000248 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts())))
249 if (DR->getDecl() == VD)
250 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000251
Ted Kremenekecc851b2008-07-23 21:16:38 +0000252 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts())))
253 if (DR->getDecl() == VD)
254 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Ted Kremenekecc851b2008-07-23 21:16:38 +0000256 return false;
Ted Kremenekf15cd142008-05-05 23:12:21 +0000257 }
Mike Stump11289f42009-09-09 15:08:12 +0000258
Craig Topperfb6b25b2014-03-15 04:29:04 +0000259 void observeStmt(const Stmt *S, const CFGBlock *block,
260 const LiveVariables::LivenessValues &Live) override {
Mike Stump11289f42009-09-09 15:08:12 +0000261
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000262 currentBlock = block;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000263
Ted Kremenek87bfc032008-04-14 18:28:25 +0000264 // Skip statements in macros.
265 if (S->getLocStart().isMacroID())
266 return;
Mike Stump11289f42009-09-09 15:08:12 +0000267
Ted Kremenekb1c392a2011-02-12 00:17:19 +0000268 // Only cover dead stores from regular assignments. ++/-- dead stores
269 // have never flagged a real bug.
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000270 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
Ted Kremenekad8bce02007-09-25 04:31:27 +0000271 if (!B->isAssignmentOp()) return; // Skip non-assignments.
Mike Stump11289f42009-09-09 15:08:12 +0000272
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000273 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()))
Ted Kremenek34a69172008-06-20 21:45:25 +0000274 if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
Ted Kremenek0216b832008-08-09 00:05:14 +0000275 // Special case: check for assigning null to a pointer.
Mike Stump11289f42009-09-09 15:08:12 +0000276 // This is a common form of defensive programming.
Anna Zaks144579e2013-04-25 21:52:35 +0000277 const Expr *RHS =
278 LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
279 RHS = RHS->IgnoreParenCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000280
Ted Kremenekb4331a92010-02-23 21:19:33 +0000281 QualType T = VD->getType();
Stephan Bergmannbf95fff2016-06-24 16:26:43 +0000282 if (T.isVolatileQualified())
283 return;
Ted Kremenekb4331a92010-02-23 21:19:33 +0000284 if (T->isPointerType() || T->isObjCObjectPointerType()) {
Ted Kremenekdc53f002012-04-04 19:58:03 +0000285 if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull))
Ted Kremenek12b64952009-11-22 20:26:21 +0000286 return;
Ted Kremenek0216b832008-08-09 00:05:14 +0000287 }
Ted Kremenek12b64952009-11-22 20:26:21 +0000288
Ted Kremenek890d44e2009-01-09 22:15:01 +0000289 // Special case: self-assignments. These are often used to shut up
290 // "unused variable" compiler warnings.
Ted Kremenekdc53f002012-04-04 19:58:03 +0000291 if (const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
Ted Kremenek890d44e2009-01-09 22:15:01 +0000292 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
293 return;
Mike Stump11289f42009-09-09 15:08:12 +0000294
Ted Kremenek890d44e2009-01-09 22:15:01 +0000295 // Otherwise, issue a warning.
Ted Kremenek8b0dba32009-04-01 06:52:48 +0000296 DeadStoreKind dsk = Parents.isConsumedExpr(B)
Mike Stump11289f42009-09-09 15:08:12 +0000297 ? Enclosing
Ted Kremeneke5fe6172009-01-20 00:47:45 +0000298 : (isIncrement(VD,B) ? DeadIncrement : Standard);
Mike Stump11289f42009-09-09 15:08:12 +0000299
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000300 CheckVarDecl(VD, DR, B->getRHS(), dsk, Live);
Mike Stump11289f42009-09-09 15:08:12 +0000301 }
Ted Kremenek1bb9f252007-09-06 23:01:46 +0000302 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000303 else if (const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
Ted Kremenekb1c392a2011-02-12 00:17:19 +0000304 if (!U->isIncrementOp() || U->isPrefix())
Ted Kremenekf15cd142008-05-05 23:12:21 +0000305 return;
Mike Stump11289f42009-09-09 15:08:12 +0000306
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000307 const Stmt *parent = Parents.getParentIgnoreParenCasts(U);
Ted Kremenekb1c392a2011-02-12 00:17:19 +0000308 if (!parent || !isa<ReturnStmt>(parent))
Ted Kremenekbb7818b2008-10-15 05:23:41 +0000309 return;
Ted Kremenek87b16f42008-07-24 17:01:17 +0000310
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000311 const Expr *Ex = U->getSubExpr()->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000312
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000313 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000314 CheckDeclRef(DR, U, DeadIncrement, Live);
Mike Stump11289f42009-09-09 15:08:12 +0000315 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000316 else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S))
Ted Kremenekad8bce02007-09-25 04:31:27 +0000317 // Iterate through the decls. Warn if any initializers are complex
318 // expressions that are not live (never used).
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000319 for (const auto *DI : DS->decls()) {
320 const auto *V = dyn_cast<VarDecl>(DI);
Ted Kremenek092ec762008-07-25 04:47:34 +0000321
322 if (!V)
323 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000324
325 if (V->hasLocalStorage()) {
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000326 // Reference types confuse the dead stores checker. Skip them
327 // for now.
328 if (V->getType()->getAs<ReferenceType>())
329 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000330
Ted Kremenekdc53f002012-04-04 19:58:03 +0000331 if (const Expr *E = V->getInit()) {
332 while (const ExprWithCleanups *exprClean =
333 dyn_cast<ExprWithCleanups>(E))
John McCall31168b02011-06-15 23:02:42 +0000334 E = exprClean->getSubExpr();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000335
Ted Kremenekdc53f002012-04-04 19:58:03 +0000336 // Look through transitive assignments, e.g.:
337 // int x = y = 0;
Anna Zaks144579e2013-04-25 21:52:35 +0000338 E = LookThroughTransitiveAssignmentsAndCommaOperators(E);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000339
Ted Kremenek29f38082009-12-15 04:12:12 +0000340 // Don't warn on C++ objects (yet) until we can show that their
341 // constructors/destructors don't have side effects.
342 if (isa<CXXConstructExpr>(E))
343 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000344
Ted Kremenek092ec762008-07-25 04:47:34 +0000345 // A dead initialization is a variable that is dead after it
346 // is initialized. We don't flag warnings for those variables
Ted Kremenek0f833902014-01-15 00:59:23 +0000347 // marked 'unused' or 'objc_precise_lifetime'.
348 if (!isLive(Live, V) &&
349 !V->hasAttr<UnusedAttr>() &&
350 !V->hasAttr<ObjCPreciseLifetimeAttr>()) {
Ted Kremeneka6ef56e2007-09-28 20:48:41 +0000351 // Special case: check for initializations with constants.
352 //
353 // e.g. : int x = 0;
354 //
355 // If x is EVER assigned a new value later, don't issue
356 // a warning. This is because such initialization can be
357 // due to defensive programming.
Richard Smith1e1f5ab2011-12-06 23:25:15 +0000358 if (E->isEvaluatable(Ctx))
Ted Kremenek0203db72009-02-09 18:01:00 +0000359 return;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Ted Kremenekdc53f002012-04-04 19:58:03 +0000361 if (const DeclRefExpr *DRE =
362 dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
363 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Ted Kremeneke174fda2010-03-18 01:22:39 +0000364 // Special case: check for initialization from constant
365 // variables.
366 //
367 // e.g. extern const int MyConstant;
368 // int x = MyConstant;
369 //
Ted Kremenek0203db72009-02-09 18:01:00 +0000370 if (VD->hasGlobalStorage() &&
Ted Kremeneke174fda2010-03-18 01:22:39 +0000371 VD->getType().isConstQualified())
372 return;
373 // Special case: check for initialization from scalar
374 // parameters. This is often a form of defensive
375 // programming. Non-scalars are still an error since
376 // because it more likely represents an actual algorithmic
377 // bug.
378 if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType())
379 return;
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Anna Zaksc29bed32011-09-20 21:38:35 +0000382 PathDiagnosticLocation Loc =
383 PathDiagnosticLocation::create(V, BR.getSourceManager());
384 Report(V, DeadInit, Loc, E->getSourceRange());
Ted Kremenek2f1a79d2007-09-11 17:24:14 +0000385 }
Ted Kremenek092ec762008-07-25 04:47:34 +0000386 }
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000387 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000388 }
Ted Kremenek1bb9f252007-09-06 23:01:46 +0000389 }
390};
Mike Stump11289f42009-09-09 15:08:12 +0000391
Ted Kremenek1bb9f252007-09-06 23:01:46 +0000392} // end anonymous namespace
393
Ted Kremenek7e151302008-04-14 17:39:48 +0000394//===----------------------------------------------------------------------===//
Ted Kremenekc7efb532008-07-02 23:16:33 +0000395// Driver function to invoke the Dead-Stores checker on a CFG.
396//===----------------------------------------------------------------------===//
397
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000398namespace {
Jordan Rosea7f94ce2013-05-15 23:22:55 +0000399class FindEscaped {
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000400public:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000401 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000402
Jordan Rosea7f94ce2013-05-15 23:22:55 +0000403 void operator()(const Stmt *S) {
404 // Check for '&'. Any VarDecl whose address has been taken we treat as
405 // escaped.
406 // FIXME: What about references?
Devin Coughlinc7315b32015-11-20 01:53:44 +0000407 if (auto *LE = dyn_cast<LambdaExpr>(S)) {
408 findLambdaReferenceCaptures(LE);
409 return;
410 }
411
Jordan Rosea7f94ce2013-05-15 23:22:55 +0000412 const UnaryOperator *U = dyn_cast<UnaryOperator>(S);
413 if (!U)
414 return;
415 if (U->getOpcode() != UO_AddrOf)
416 return;
417
418 const Expr *E = U->getSubExpr()->IgnoreParenCasts();
419 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
420 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
421 Escaped.insert(VD);
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000422 }
Devin Coughlinc7315b32015-11-20 01:53:44 +0000423
424 // Treat local variables captured by reference in C++ lambdas as escaped.
425 void findLambdaReferenceCaptures(const LambdaExpr *LE) {
426 const CXXRecordDecl *LambdaClass = LE->getLambdaClass();
427 llvm::DenseMap<const VarDecl *, FieldDecl *> CaptureFields;
428 FieldDecl *ThisCaptureField;
429 LambdaClass->getCaptureFields(CaptureFields, ThisCaptureField);
430
431 for (const LambdaCapture &C : LE->captures()) {
432 if (!C.capturesVariable())
433 continue;
434
435 VarDecl *VD = C.getCapturedVar();
436 const FieldDecl *FD = CaptureFields[VD];
437 if (!FD)
438 continue;
439
440 // If the capture field is a reference type, it is capture-by-reference.
441 if (FD->getType()->isReferenceType())
442 Escaped.insert(VD);
443 }
444 }
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000445};
446} // end anonymous namespace
Mike Stump11289f42009-09-09 15:08:12 +0000447
Ted Kremenek4d947fa2009-04-07 05:25:24 +0000448
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +0000449//===----------------------------------------------------------------------===//
450// DeadStoresChecker
451//===----------------------------------------------------------------------===//
452
453namespace {
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +0000454class DeadStoresChecker : public Checker<check::ASTCodeBody> {
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +0000455public:
456 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
457 BugReporter &BR) const {
Ted Kremenek3e05be92013-02-18 07:18:28 +0000458
459 // Don't do anything for template instantiations.
460 // Proving that code in a template instantiation is "dead"
461 // means proving that it is dead in all instantiations.
462 // This same problem exists with -Wunreachable-code.
463 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
464 if (FD->isTemplateInstantiation())
465 return;
466
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000467 if (LiveVariables *L = mgr.getAnalysis<LiveVariables>(D)) {
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +0000468 CFG &cfg = *mgr.getCFG(D);
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000469 AnalysisDeclContext *AC = mgr.getAnalysisDeclContext(D);
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +0000470 ParentMap &pmap = mgr.getParentMap(D);
Jordan Rosea7f94ce2013-05-15 23:22:55 +0000471 FindEscaped FS;
472 cfg.VisitBlockStmts(FS);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000473 DeadStoreObs A(cfg, BR.getContext(), BR, this, AC, pmap, FS.Escaped);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000474 L->runOnAllBlocks(A);
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +0000475 }
476 }
477};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000478}
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +0000479
480void ento::registerDeadStoresChecker(CheckerManager &mgr) {
481 mgr.registerChecker<DeadStoresChecker>();
Ted Kremenek7e151302008-04-14 17:39:48 +0000482}