DeadStoresChecker.cpp revision f4e532b5a1683a9f6c842f361c7415bf3474315f
1//==- DeadStoresChecker.cpp - Check for stores to dead variables -*- 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 DeadStores, a flow-sensitive checker that looks for 11// stores to variables that are no longer live. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 16#include "clang/Analysis/Analyses/LiveVariables.h" 17#include "clang/Analysis/Visitors/CFGRecStmtVisitor.h" 18#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 20#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/ParentMap.h" 24#include "llvm/ADT/SmallPtrSet.h" 25 26using namespace clang; 27using namespace ento; 28 29namespace { 30 31// FIXME: Eventually migrate into its own file, and have it managed by 32// AnalysisManager. 33class ReachableCode { 34 const CFG &cfg; 35 llvm::BitVector reachable; 36public: 37 ReachableCode(const CFG &cfg) 38 : cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {} 39 40 void computeReachableBlocks(); 41 42 bool isReachable(const CFGBlock *block) const { 43 return reachable[block->getBlockID()]; 44 } 45}; 46} 47 48void ReachableCode::computeReachableBlocks() { 49 if (!cfg.getNumBlockIDs()) 50 return; 51 52 llvm::SmallVector<const CFGBlock*, 10> worklist; 53 worklist.push_back(&cfg.getEntry()); 54 55 while (!worklist.empty()) { 56 const CFGBlock *block = worklist.back(); 57 worklist.pop_back(); 58 llvm::BitVector::reference isReachable = reachable[block->getBlockID()]; 59 if (isReachable) 60 continue; 61 isReachable = true; 62 for (CFGBlock::const_succ_iterator i = block->succ_begin(), 63 e = block->succ_end(); i != e; ++i) 64 if (const CFGBlock *succ = *i) 65 worklist.push_back(succ); 66 } 67} 68 69namespace { 70class DeadStoreObs : public LiveVariables::ObserverTy { 71 const CFG &cfg; 72 ASTContext &Ctx; 73 BugReporter& BR; 74 ParentMap& Parents; 75 llvm::SmallPtrSet<VarDecl*, 20> Escaped; 76 llvm::OwningPtr<ReachableCode> reachableCode; 77 const CFGBlock *currentBlock; 78 79 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit }; 80 81public: 82 DeadStoreObs(const CFG &cfg, ASTContext &ctx, 83 BugReporter& br, ParentMap& parents, 84 llvm::SmallPtrSet<VarDecl*, 20> &escaped) 85 : cfg(cfg), Ctx(ctx), BR(br), Parents(parents), 86 Escaped(escaped), currentBlock(0) {} 87 88 virtual ~DeadStoreObs() {} 89 90 void Report(VarDecl* V, DeadStoreKind dsk, SourceLocation L, SourceRange R) { 91 if (Escaped.count(V)) 92 return; 93 94 // Compute reachable blocks within the CFG for trivial cases 95 // where a bogus dead store can be reported because itself is unreachable. 96 if (!reachableCode.get()) { 97 reachableCode.reset(new ReachableCode(cfg)); 98 reachableCode->computeReachableBlocks(); 99 } 100 101 if (!reachableCode->isReachable(currentBlock)) 102 return; 103 104 const std::string &name = V->getNameAsString(); 105 106 const char* BugType = 0; 107 std::string msg; 108 109 switch (dsk) { 110 default: 111 assert(false && "Impossible dead store type."); 112 113 case DeadInit: 114 BugType = "Dead initialization"; 115 msg = "Value stored to '" + name + 116 "' during its initialization is never read"; 117 break; 118 119 case DeadIncrement: 120 BugType = "Dead increment"; 121 case Standard: 122 if (!BugType) BugType = "Dead assignment"; 123 msg = "Value stored to '" + name + "' is never read"; 124 break; 125 126 case Enclosing: 127 // Don't report issues in this case, e.g.: "if (x = foo())", 128 // where 'x' is unused later. We have yet to see a case where 129 // this is a real bug. 130 return; 131 } 132 133 BR.EmitBasicReport(BugType, "Dead store", msg, L, R); 134 } 135 136 void CheckVarDecl(VarDecl* VD, Expr* Ex, Expr* Val, 137 DeadStoreKind dsk, 138 const LiveVariables::AnalysisDataTy& AD, 139 const LiveVariables::ValTy& Live) { 140 141 if (!VD->hasLocalStorage()) 142 return; 143 // Reference types confuse the dead stores checker. Skip them 144 // for now. 145 if (VD->getType()->getAs<ReferenceType>()) 146 return; 147 148 if (!Live(VD, AD) && 149 !(VD->getAttr<UnusedAttr>() || VD->getAttr<BlocksAttr>())) 150 Report(VD, dsk, Ex->getSourceRange().getBegin(), 151 Val->getSourceRange()); 152 } 153 154 void CheckDeclRef(DeclRefExpr* DR, Expr* Val, DeadStoreKind dsk, 155 const LiveVariables::AnalysisDataTy& AD, 156 const LiveVariables::ValTy& Live) { 157 if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) 158 CheckVarDecl(VD, DR, Val, dsk, AD, Live); 159 } 160 161 bool isIncrement(VarDecl* VD, BinaryOperator* B) { 162 if (B->isCompoundAssignmentOp()) 163 return true; 164 165 Expr* RHS = B->getRHS()->IgnoreParenCasts(); 166 BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS); 167 168 if (!BRHS) 169 return false; 170 171 DeclRefExpr *DR; 172 173 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts()))) 174 if (DR->getDecl() == VD) 175 return true; 176 177 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts()))) 178 if (DR->getDecl() == VD) 179 return true; 180 181 return false; 182 } 183 184 virtual void ObserveStmt(Stmt* S, const CFGBlock *block, 185 const LiveVariables::AnalysisDataTy& AD, 186 const LiveVariables::ValTy& Live) { 187 188 currentBlock = block; 189 190 // Skip statements in macros. 191 if (S->getLocStart().isMacroID()) 192 return; 193 194 // Only cover dead stores from regular assignments. ++/-- dead stores 195 // have never flagged a real bug. 196 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 197 if (!B->isAssignmentOp()) return; // Skip non-assignments. 198 199 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS())) 200 if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 201 // Special case: check for assigning null to a pointer. 202 // This is a common form of defensive programming. 203 QualType T = VD->getType(); 204 if (T->isPointerType() || T->isObjCObjectPointerType()) { 205 if (B->getRHS()->isNullPointerConstant(Ctx, 206 Expr::NPC_ValueDependentIsNull)) 207 return; 208 } 209 210 Expr* RHS = B->getRHS()->IgnoreParenCasts(); 211 // Special case: self-assignments. These are often used to shut up 212 // "unused variable" compiler warnings. 213 if (DeclRefExpr* RhsDR = dyn_cast<DeclRefExpr>(RHS)) 214 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl())) 215 return; 216 217 // Otherwise, issue a warning. 218 DeadStoreKind dsk = Parents.isConsumedExpr(B) 219 ? Enclosing 220 : (isIncrement(VD,B) ? DeadIncrement : Standard); 221 222 CheckVarDecl(VD, DR, B->getRHS(), dsk, AD, Live); 223 } 224 } 225 else if (UnaryOperator* U = dyn_cast<UnaryOperator>(S)) { 226 if (!U->isIncrementOp() || U->isPrefix()) 227 return; 228 229 Stmt *parent = Parents.getParentIgnoreParenCasts(U); 230 if (!parent || !isa<ReturnStmt>(parent)) 231 return; 232 233 Expr *Ex = U->getSubExpr()->IgnoreParenCasts(); 234 235 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(Ex)) 236 CheckDeclRef(DR, U, DeadIncrement, AD, Live); 237 } 238 else if (DeclStmt* DS = dyn_cast<DeclStmt>(S)) 239 // Iterate through the decls. Warn if any initializers are complex 240 // expressions that are not live (never used). 241 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 242 DI != DE; ++DI) { 243 244 VarDecl* V = dyn_cast<VarDecl>(*DI); 245 246 if (!V) 247 continue; 248 249 if (V->hasLocalStorage()) { 250 // Reference types confuse the dead stores checker. Skip them 251 // for now. 252 if (V->getType()->getAs<ReferenceType>()) 253 return; 254 255 if (Expr* E = V->getInit()) { 256 // Don't warn on C++ objects (yet) until we can show that their 257 // constructors/destructors don't have side effects. 258 if (isa<CXXConstructExpr>(E)) 259 return; 260 261 if (isa<ExprWithCleanups>(E)) 262 return; 263 264 // A dead initialization is a variable that is dead after it 265 // is initialized. We don't flag warnings for those variables 266 // marked 'unused'. 267 if (!Live(V, AD) && V->getAttr<UnusedAttr>() == 0) { 268 // Special case: check for initializations with constants. 269 // 270 // e.g. : int x = 0; 271 // 272 // If x is EVER assigned a new value later, don't issue 273 // a warning. This is because such initialization can be 274 // due to defensive programming. 275 if (E->isConstantInitializer(Ctx, false)) 276 return; 277 278 if (DeclRefExpr *DRE=dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 279 if (VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 280 // Special case: check for initialization from constant 281 // variables. 282 // 283 // e.g. extern const int MyConstant; 284 // int x = MyConstant; 285 // 286 if (VD->hasGlobalStorage() && 287 VD->getType().isConstQualified()) 288 return; 289 // Special case: check for initialization from scalar 290 // parameters. This is often a form of defensive 291 // programming. Non-scalars are still an error since 292 // because it more likely represents an actual algorithmic 293 // bug. 294 if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType()) 295 return; 296 } 297 298 Report(V, DeadInit, V->getLocation(), E->getSourceRange()); 299 } 300 } 301 } 302 } 303 } 304}; 305 306} // end anonymous namespace 307 308//===----------------------------------------------------------------------===// 309// Driver function to invoke the Dead-Stores checker on a CFG. 310//===----------------------------------------------------------------------===// 311 312namespace { 313class FindEscaped : public CFGRecStmtDeclVisitor<FindEscaped>{ 314 CFG *cfg; 315public: 316 FindEscaped(CFG *c) : cfg(c) {} 317 318 CFG& getCFG() { return *cfg; } 319 320 llvm::SmallPtrSet<VarDecl*, 20> Escaped; 321 322 void VisitUnaryOperator(UnaryOperator* U) { 323 // Check for '&'. Any VarDecl whose value has its address-taken we 324 // treat as escaped. 325 Expr* E = U->getSubExpr()->IgnoreParenCasts(); 326 if (U->getOpcode() == UO_AddrOf) 327 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 328 if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) { 329 Escaped.insert(VD); 330 return; 331 } 332 Visit(E); 333 } 334}; 335} // end anonymous namespace 336 337 338void ento::CheckDeadStores(CFG &cfg, LiveVariables &L, ParentMap &pmap, 339 BugReporter& BR) { 340 FindEscaped FS(&cfg); 341 FS.getCFG().VisitBlockStmts(FS); 342 DeadStoreObs A(cfg, BR.getContext(), BR, pmap, FS.Escaped); 343 L.runOnAllBlocks(cfg, &A); 344} 345