24 #include "llvm/ADT/BitVector.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/Support/SaveAndRestore.h" 28 using namespace clang;
41 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
46 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
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 {
82 void ReachableCode::computeReachableBlocks() {
83 if (!cfg.getNumBlockIDs())
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()];
98 worklist.push_back(succ);
127 const CheckerBase *Checker;
130 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
131 std::unique_ptr<ReachableCode> reachableCode;
133 std::unique_ptr<llvm::DenseSet<const VarDecl *>> InEH;
135 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
138 DeadStoreObs(
const CFG &cfg,
ASTContext &ctx, BugReporter &br,
141 llvm::SmallPtrSet<const VarDecl *, 20> &escaped)
142 : cfg(cfg), Ctx(ctx), BR(br), Checker(checker), AC(ac), Parents(parents),
143 Escaped(escaped), currentBlock(
nullptr) {}
145 ~DeadStoreObs()
override {}
154 EHCodeVisitor V(*InEH.get());
161 return InEH->count(D);
164 void Report(
const VarDecl *V, DeadStoreKind dsk,
166 if (Escaped.count(V))
171 if (!reachableCode.get()) {
172 reachableCode.reset(
new ReachableCode(cfg));
173 reachableCode->computeReachableBlocks();
176 if (!reachableCode->isReachable(currentBlock))
180 llvm::raw_svector_ostream os(buf);
181 const char *BugType =
nullptr;
185 BugType =
"Dead initialization";
186 os <<
"Value stored to '" << *V
187 <<
"' during its initialization is never read";
191 BugType =
"Dead increment";
194 if (!BugType) BugType =
"Dead assignment";
195 os <<
"Value stored to '" << *V <<
"' is never read";
205 BR.EmitBasicReport(AC->
getDecl(), Checker, BugType,
"Dead store", os.str(),
220 if (!isLive(Live, VD) &&
222 VD->
hasAttr<ObjCPreciseLifetimeAttr>())) {
224 PathDiagnosticLocation ExLoc =
230 void CheckDeclRef(
const DeclRefExpr *DR,
const Expr *Val, DeadStoreKind dsk,
233 CheckVarDecl(VD, DR, Val, dsk, Live);
262 currentBlock = block;
291 if (
const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
292 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
298 : (isIncrement(VD,B) ? DeadIncrement : Standard);
300 CheckVarDecl(VD, DR, B->
getRHS(), dsk, Live);
303 else if (
const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
304 if (!U->isIncrementOp() || U->isPrefix())
308 if (!parent || !isa<ReturnStmt>(parent))
313 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
314 CheckDeclRef(DR, U, DeadIncrement, Live);
316 else if (
const DeclStmt *DS = dyn_cast<DeclStmt>(S))
319 for (
const auto *DI : DS->decls()) {
320 const auto *V = dyn_cast<
VarDecl>(DI);
332 while (
const FullExpr *FE = dyn_cast<FullExpr>(E))
333 E = FE->getSubExpr();
341 if (isa<CXXConstructExpr>(E))
347 if (!isLive(Live, V) &&
349 !V->
hasAttr<ObjCPreciseLifetimeAttr>()) {
357 if (E->isEvaluatable(Ctx))
361 dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
362 if (
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
381 PathDiagnosticLocation Loc =
400 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
402 void operator()(
const Stmt *S) {
406 if (
auto *LE = dyn_cast<LambdaExpr>(S)) {
407 findLambdaReferenceCaptures(LE);
418 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
424 void findLambdaReferenceCaptures(
const LambdaExpr *LE) {
426 llvm::DenseMap<const VarDecl *, FieldDecl *> CaptureFields;
431 if (!C.capturesVariable())
434 VarDecl *VD = C.getCapturedVar();
453 class DeadStoresChecker :
public Checker<check::ASTCodeBody> {
455 void checkASTCodeBody(
const Decl *D, AnalysisManager& mgr,
456 BugReporter &BR)
const {
463 if (FD->isTemplateInstantiation())
467 CFG &cfg = *mgr.getCFG(D);
472 DeadStoreObs A(cfg, BR.getContext(), BR,
this, AC, pmap, FS.Escaped);
473 L->runOnAllBlocks(A);
479 void ento::registerDeadStoresChecker(CheckerManager &mgr) {
480 mgr.registerChecker<DeadStoresChecker>();
Defines the clang::ASTContext interface.
Represents a function declaration or definition.
A (possibly-)qualified type.
Stmt * getBody() const
Get the body of the Declaration.
succ_iterator succ_begin()
Stmt - This represents one statement.
unsigned getBlockID() const
Decl - This represents one declaration (or definition), e.g.
Stmt * getHandlerBlock() const
Describes the capture of a variable or of this, or of a C++1y init-capture.
bool isConsumedExpr(Expr *E) const
Represents a variable declaration or definition.
const T * getAs() const
Member-template getAs<specific type>'.
static bool isAssignmentOp(Opcode Opc)
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
FullExpr - Represents a "full-expression" node.
SourceLocation getBeginLoc() const LLVM_READONLY
Represents a member of a struct/union/class.
AnalysisDeclContext contains the context data for the function or method under analysis.
bool isReferenceType() const
Represents Objective-C's @catch statement.
AdjacentBlocks::const_iterator const_succ_iterator
A builtin binary operation expression such as "x + y" or "x <= y".
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
bool isScalarType() const
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents a single basic block in a source-level CFG.
This represents one expression.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
bool isConstQualified() const
Determine whether this type is const-qualified.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
Expr * getSubExpr() const
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
const Decl * getDecl() const
bool isObjCObjectPointerType() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Dataflow Directional Tag Classes.
void VisitBlockStmts(CALLBACK &O) const
static const Expr * LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex)
bool isLive(const Stmt *S) const
const Expr * getInit() const
Base for LValueReferenceType and RValueReferenceType.
Represents Objective-C's @finally statement.
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl *> &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Represents a C++ struct/union/class.
static bool isCompoundAssignmentOp(Opcode Opc)
CXXCatchStmt - This represents a C++ catch block.
capture_range captures() const
Retrieve this lambda's captures.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Stmt * getParentIgnoreParenCasts(Stmt *) const
A reference to a declared variable, function, enum, etc.
bool isPointerType() const
A trivial tuple used to represent a source range.