Coverage Report

Created: 2023-09-12 09:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//==- DeadStoresChecker.cpp - Check for stores to dead variables -*- C++ -*-==//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines a DeadStores, a flow-sensitive checker that looks for
10
//  stores to variables that are no longer live.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/Attr.h"
16
#include "clang/AST/ParentMap.h"
17
#include "clang/AST/RecursiveASTVisitor.h"
18
#include "clang/Analysis/Analyses/LiveVariables.h"
19
#include "clang/Lex/Lexer.h"
20
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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/STLExtras.h"
26
#include "llvm/ADT/SmallString.h"
27
#include "llvm/Support/SaveAndRestore.h"
28
29
using namespace clang;
30
using namespace ento;
31
32
namespace {
33
34
/// A simple visitor to record what VarDecls occur in EH-handling code.
35
class EHCodeVisitor : public RecursiveASTVisitor<EHCodeVisitor> {
36
public:
37
  bool inEH;
38
  llvm::DenseSet<const VarDecl *> &S;
39
40
0
  bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
41
0
    SaveAndRestore inFinally(inEH, true);
42
0
    return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
43
0
  }
44
45
0
  bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S) {
46
0
    SaveAndRestore inCatch(inEH, true);
47
0
    return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
48
0
  }
49
50
8
  bool TraverseCXXCatchStmt(CXXCatchStmt *S) {
51
8
    SaveAndRestore inCatch(inEH, true);
52
8
    return TraverseStmt(S->getHandlerBlock());
53
8
  }
54
55
641
  bool VisitDeclRefExpr(DeclRefExpr *DR) {
56
641
    if (inEH)
57
8
      if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
58
8
        S.insert(D);
59
641
    return true;
60
641
  }
61
62
  EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) :
63
142
  inEH(false), S(S) {}
64
};
65
66
// FIXME: Eventually migrate into its own file, and have it managed by
67
// AnalysisManager.
68
class ReachableCode {
69
  const CFG &cfg;
70
  llvm::BitVector reachable;
71
public:
72
  ReachableCode(const CFG &cfg)
73
95
    : cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {}
74
75
  void computeReachableBlocks();
76
77
138
  bool isReachable(const CFGBlock *block) const {
78
138
    return reachable[block->getBlockID()];
79
138
  }
80
};
81
}
82
83
95
void ReachableCode::computeReachableBlocks() {
84
95
  if (!cfg.getNumBlockIDs())
85
0
    return;
86
87
95
  SmallVector<const CFGBlock*, 10> worklist;
88
95
  worklist.push_back(&cfg.getEntry());
89
90
650
  while (!worklist.empty()) {
91
555
    const CFGBlock *block = worklist.pop_back_val();
92
555
    llvm::BitVector::reference isReachable = reachable[block->getBlockID()];
93
555
    if (isReachable)
94
72
      continue;
95
483
    isReachable = true;
96
97
483
    for (const CFGBlock *succ : block->succs())
98
517
      if (succ)
99
460
        worklist.push_back(succ);
100
483
  }
101
95
}
102
103
static const Expr *
104
794
LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex) {
105
825
  while (Ex) {
106
825
    Ex = Ex->IgnoreParenCasts();
107
825
    const BinaryOperator *BO = dyn_cast<BinaryOperator>(Ex);
108
825
    if (!BO)
109
730
      break;
110
95
    BinaryOperatorKind Op = BO->getOpcode();
111
95
    if (Op == BO_Assign || 
Op == BO_Comma82
) {
112
31
      Ex = BO->getRHS();
113
31
      continue;
114
31
    }
115
64
    break;
116
95
  }
117
794
  return Ex;
118
794
}
119
120
namespace {
121
class DeadStoresChecker : public Checker<check::ASTCodeBody> {
122
public:
123
  bool ShowFixIts = false;
124
  bool WarnForDeadNestedAssignments = true;
125
126
  void checkASTCodeBody(const Decl *D, AnalysisManager &Mgr,
127
                        BugReporter &BR) const;
128
};
129
130
class DeadStoreObs : public LiveVariables::Observer {
131
  const CFG &cfg;
132
  ASTContext &Ctx;
133
  BugReporter& BR;
134
  const DeadStoresChecker *Checker;
135
  AnalysisDeclContext* AC;
136
  ParentMap& Parents;
137
  llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
138
  std::unique_ptr<ReachableCode> reachableCode;
139
  const CFGBlock *currentBlock;
140
  std::unique_ptr<llvm::DenseSet<const VarDecl *>> InEH;
141
142
  enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
143
144
public:
145
  DeadStoreObs(const CFG &cfg, ASTContext &ctx, BugReporter &br,
146
               const DeadStoresChecker *checker, AnalysisDeclContext *ac,
147
               ParentMap &parents,
148
               llvm::SmallPtrSet<const VarDecl *, 20> &escaped,
149
               bool warnForDeadNestedAssignments)
150
      : cfg(cfg), Ctx(ctx), BR(br), Checker(checker), AC(ac), Parents(parents),
151
543
        Escaped(escaped), currentBlock(nullptr) {}
152
153
543
  ~DeadStoreObs() override {}
154
155
694
  bool isLive(const LiveVariables::LivenessValues &Live, const VarDecl *D) {
156
694
    if (Live.isLive(D))
157
479
      return true;
158
    // Lazily construct the set that records which VarDecls are in
159
    // EH code.
160
215
    if (!InEH.get()) {
161
142
      InEH.reset(new llvm::DenseSet<const VarDecl *>());
162
142
      EHCodeVisitor V(*InEH.get());
163
142
      V.TraverseStmt(AC->getBody());
164
142
    }
165
    // Treat all VarDecls that occur in EH code as being "always live"
166
    // when considering to suppress dead stores.  Frequently stores
167
    // are followed by reads in EH code, but we don't have the ability
168
    // to analyze that yet.
169
215
    return InEH->count(D);
170
694
  }
171
172
130
  bool isSuppressed(SourceRange R) {
173
130
    SourceManager &SMgr = Ctx.getSourceManager();
174
130
    SourceLocation Loc = R.getBegin();
175
130
    if (!Loc.isValid())
176
0
      return false;
177
178
130
    FileID FID = SMgr.getFileID(Loc);
179
130
    bool Invalid = false;
180
130
    StringRef Data = SMgr.getBufferData(FID, &Invalid);
181
130
    if (Invalid)
182
0
      return false;
183
184
    // Files autogenerated by DriverKit IIG contain some dead stores that
185
    // we don't want to report.
186
130
    if (Data.startswith("/* iig"))
187
2
      return true;
188
189
128
    return false;
190
130
  }
191
192
  void Report(const VarDecl *V, DeadStoreKind dsk,
193
140
              PathDiagnosticLocation L, SourceRange R) {
194
140
    if (Escaped.count(V))
195
2
      return;
196
197
    // Compute reachable blocks within the CFG for trivial cases
198
    // where a bogus dead store can be reported because itself is unreachable.
199
138
    if (!reachableCode.get()) {
200
95
      reachableCode.reset(new ReachableCode(cfg));
201
95
      reachableCode->computeReachableBlocks();
202
95
    }
203
204
138
    if (!reachableCode->isReachable(currentBlock))
205
8
      return;
206
207
130
    if (isSuppressed(R))
208
2
      return;
209
210
128
    SmallString<64> buf;
211
128
    llvm::raw_svector_ostream os(buf);
212
128
    const char *BugType = nullptr;
213
214
128
    SmallVector<FixItHint, 1> Fixits;
215
216
128
    switch (dsk) {
217
55
      case DeadInit: {
218
55
        BugType = "Dead initialization";
219
55
        os << "Value stored to '" << *V
220
55
           << "' during its initialization is never read";
221
222
55
        ASTContext &ACtx = V->getASTContext();
223
55
        if (Checker->ShowFixIts) {
224
35
          if (V->getInit()->HasSideEffects(ACtx,
225
35
                                           /*IncludePossibleEffects=*/true)) {
226
25
            break;
227
25
          }
228
10
          SourceManager &SM = ACtx.getSourceManager();
229
10
          const LangOptions &LO = ACtx.getLangOpts();
230
10
          SourceLocation L1 =
231
10
              Lexer::findNextToken(
232
10
                  V->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
233
10
                  SM, LO)->getEndLoc();
234
10
          SourceLocation L2 =
235
10
              Lexer::getLocForEndOfToken(V->getInit()->getEndLoc(), 1, SM, LO);
236
10
          Fixits.push_back(FixItHint::CreateRemoval({L1, L2}));
237
10
        }
238
30
        break;
239
55
      }
240
241
30
      case DeadIncrement:
242
27
        BugType = "Dead increment";
243
27
        [[fallthrough]];
244
56
      case Standard:
245
56
        if (!BugType) 
BugType = "Dead assignment"29
;
246
56
        os << "Value stored to '" << *V << "' is never read";
247
56
        break;
248
249
      // eg.: f((x = foo()))
250
17
      case Enclosing:
251
17
        if (!Checker->WarnForDeadNestedAssignments)
252
8
          return;
253
9
        BugType = "Dead nested assignment";
254
9
        os << "Although the value stored to '" << *V
255
9
           << "' is used in the enclosing expression, the value is never "
256
9
              "actually read from '"
257
9
           << *V << "'";
258
9
        break;
259
128
    }
260
261
120
    BR.EmitBasicReport(AC->getDecl(), Checker, BugType, categories::UnusedCode,
262
120
                       os.str(), L, R, Fixits);
263
120
  }
264
265
  void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val,
266
                    DeadStoreKind dsk,
267
237
                    const LiveVariables::LivenessValues &Live) {
268
269
237
    if (!VD->hasLocalStorage())
270
8
      return;
271
    // Reference types confuse the dead stores checker.  Skip them
272
    // for now.
273
229
    if (VD->getType()->getAs<ReferenceType>())
274
7
      return;
275
276
222
    if (!isLive(Live, VD) &&
277
222
        
!(100
VD->hasAttr<UnusedAttr>()100
||
VD->hasAttr<BlocksAttr>()100
||
278
100
          
VD->hasAttr<ObjCPreciseLifetimeAttr>()86
)) {
279
280
85
      PathDiagnosticLocation ExLoc =
281
85
        PathDiagnosticLocation::createBegin(Ex, BR.getSourceManager(), AC);
282
85
      Report(VD, dsk, ExLoc, Val->getSourceRange());
283
85
    }
284
222
  }
285
286
  void CheckDeclRef(const DeclRefExpr *DR, const Expr *Val, DeadStoreKind dsk,
287
2
                    const LiveVariables::LivenessValues& Live) {
288
2
    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
289
2
      CheckVarDecl(VD, DR, Val, dsk, Live);
290
2
  }
291
292
207
  bool isIncrement(VarDecl *VD, const BinaryOperator* B) {
293
207
    if (B->isCompoundAssignmentOp())
294
23
      return true;
295
296
184
    const Expr *RHS = B->getRHS()->IgnoreParenCasts();
297
184
    const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS);
298
299
184
    if (!BRHS)
300
143
      return false;
301
302
41
    const DeclRefExpr *DR;
303
304
41
    if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts())))
305
36
      if (DR->getDecl() == VD)
306
23
        return true;
307
308
18
    if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts())))
309
7
      if (DR->getDecl() == VD)
310
3
        return true;
311
312
15
    return false;
313
18
  }
314
315
  void observeStmt(const Stmt *S, const CFGBlock *block,
316
9.36k
                   const LiveVariables::LivenessValues &Live) override {
317
318
9.36k
    currentBlock = block;
319
320
    // Skip statements in macros.
321
9.36k
    if (S->getBeginLoc().isMacroID())
322
172
      return;
323
324
    // Only cover dead stores from regular assignments.  ++/-- dead stores
325
    // have never flagged a real bug.
326
9.19k
    if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
327
861
      if (!B->isAssignmentOp()) 
return438
; // Skip non-assignments.
328
329
423
      if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()))
330
280
        if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
331
          // Special case: check for assigning null to a pointer.
332
          //  This is a common form of defensive programming.
333
273
          const Expr *RHS =
334
273
              LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
335
336
273
          QualType T = VD->getType();
337
273
          if (T.isVolatileQualified())
338
2
            return;
339
271
          if (T->isPointerType() || 
T->isObjCObjectPointerType()205
) {
340
73
            if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull))
341
34
              return;
342
73
          }
343
344
          // Special case: self-assignments.  These are often used to shut up
345
          //  "unused variable" compiler warnings.
346
237
          if (const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
347
17
            if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
348
2
              return;
349
350
          // Otherwise, issue a warning.
351
235
          DeadStoreKind dsk = Parents.isConsumedExpr(B)
352
235
                              ? 
Enclosing28
353
235
                              : 
(207
isIncrement(VD,B)207
?
DeadIncrement49
:
Standard158
);
354
355
235
          CheckVarDecl(VD, DR, B->getRHS(), dsk, Live);
356
235
        }
357
423
    }
358
8.33k
    else if (const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
359
368
      if (!U->isIncrementOp() || 
U->isPrefix()115
)
360
349
        return;
361
362
19
      const Stmt *parent = Parents.getParentIgnoreParenCasts(U);
363
19
      if (!parent || !isa<ReturnStmt>(parent))
364
13
        return;
365
366
6
      const Expr *Ex = U->getSubExpr()->IgnoreParenCasts();
367
368
6
      if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
369
2
        CheckDeclRef(DR, U, DeadIncrement, Live);
370
6
    }
371
7.96k
    else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S))
372
      // Iterate through the decls.  Warn if any initializers are complex
373
      // expressions that are not live (never used).
374
675
      for (const auto *DI : DS->decls()) {
375
675
        const auto *V = dyn_cast<VarDecl>(DI);
376
377
675
        if (!V)
378
0
          continue;
379
380
675
        if (V->hasLocalStorage()) {
381
          // Reference types confuse the dead stores checker.  Skip them
382
          // for now.
383
655
          if (V->getType()->getAs<ReferenceType>())
384
23
            return;
385
386
632
          if (const Expr *E = V->getInit()) {
387
585
            while (const FullExpr *FE = dyn_cast<FullExpr>(E))
388
64
              E = FE->getSubExpr();
389
390
            // Look through transitive assignments, e.g.:
391
            // int x = y = 0;
392
521
            E = LookThroughTransitiveAssignmentsAndCommaOperators(E);
393
394
            // Don't warn on C++ objects (yet) until we can show that their
395
            // constructors/destructors don't have side effects.
396
521
            if (isa<CXXConstructExpr>(E))
397
49
              return;
398
399
            // A dead initialization is a variable that is dead after it
400
            // is initialized.  We don't flag warnings for those variables
401
            // marked 'unused' or 'objc_precise_lifetime'.
402
472
            if (!isLive(Live, V) &&
403
472
                
!V->hasAttr<UnusedAttr>()107
&&
404
472
                
!V->hasAttr<ObjCPreciseLifetimeAttr>()103
) {
405
              // Special case: check for initializations with constants.
406
              //
407
              //  e.g. : int x = 0;
408
              //         struct A = {0, 1};
409
              //         struct B = {{0}, {1, 2}};
410
              //
411
              // If x is EVER assigned a new value later, don't issue
412
              // a warning.  This is because such initialization can be
413
              // due to defensive programming.
414
102
              if (isConstant(E))
415
40
                return;
416
417
62
              if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
418
7
                if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
419
                  // Special case: check for initialization from constant
420
                  //  variables.
421
                  //
422
                  //  e.g. extern const int MyConstant;
423
                  //       int x = MyConstant;
424
                  //
425
7
                  if (VD->hasGlobalStorage() &&
426
7
                      
VD->getType().isConstQualified()2
)
427
2
                    return;
428
                  // Special case: check for initialization from scalar
429
                  //  parameters.  This is often a form of defensive
430
                  //  programming.  Non-scalars are still an error since
431
                  //  because it more likely represents an actual algorithmic
432
                  //  bug.
433
5
                  if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType())
434
5
                    return;
435
5
                }
436
437
55
              PathDiagnosticLocation Loc =
438
55
                PathDiagnosticLocation::create(V, BR.getSourceManager());
439
55
              Report(V, DeadInit, Loc, V->getInit()->getSourceRange());
440
55
            }
441
472
          }
442
632
        }
443
675
      }
444
9.19k
  }
445
446
private:
447
  /// Return true if the given init list can be interpreted as constant
448
0
  bool isConstant(const InitListExpr *Candidate) const {
449
    // We consider init list to be constant if each member of the list can be
450
    // interpreted as constant.
451
0
    return llvm::all_of(Candidate->inits(), [this](const Expr *Init) {
452
0
      return isConstant(Init->IgnoreParenCasts());
453
0
    });
454
0
  }
455
456
  /// Return true if the given expression can be interpreted as constant
457
102
  bool isConstant(const Expr *E) const {
458
    // It looks like E itself is a constant
459
102
    if (E->isEvaluatable(Ctx))
460
40
      return true;
461
462
    // We should also allow defensive initialization of structs, i.e. { 0 }
463
62
    if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
464
0
      return isConstant(ILE);
465
0
    }
466
467
62
    return false;
468
62
  }
469
};
470
471
} // end anonymous namespace
472
473
//===----------------------------------------------------------------------===//
474
// Driver function to invoke the Dead-Stores checker on a CFG.
475
//===----------------------------------------------------------------------===//
476
477
namespace {
478
class FindEscaped {
479
public:
480
  llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
481
482
8.90k
  void operator()(const Stmt *S) {
483
    // Check for '&'. Any VarDecl whose address has been taken we treat as
484
    // escaped.
485
    // FIXME: What about references?
486
8.90k
    if (auto *LE = dyn_cast<LambdaExpr>(S)) {
487
55
      findLambdaReferenceCaptures(LE);
488
55
      return;
489
55
    }
490
491
8.85k
    const UnaryOperator *U = dyn_cast<UnaryOperator>(S);
492
8.85k
    if (!U)
493
8.47k
      return;
494
376
    if (U->getOpcode() != UO_AddrOf)
495
344
      return;
496
497
32
    const Expr *E = U->getSubExpr()->IgnoreParenCasts();
498
32
    if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
499
30
      if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
500
29
        Escaped.insert(VD);
501
32
  }
502
503
  // Treat local variables captured by reference in C++ lambdas as escaped.
504
55
  void findLambdaReferenceCaptures(const LambdaExpr *LE)  {
505
55
    const CXXRecordDecl *LambdaClass = LE->getLambdaClass();
506
55
    llvm::DenseMap<const ValueDecl *, FieldDecl *> CaptureFields;
507
55
    FieldDecl *ThisCaptureField;
508
55
    LambdaClass->getCaptureFields(CaptureFields, ThisCaptureField);
509
510
59
    for (const LambdaCapture &C : LE->captures()) {
511
59
      if (!C.capturesVariable())
512
5
        continue;
513
514
54
      ValueDecl *VD = C.getCapturedVar();
515
54
      const FieldDecl *FD = CaptureFields[VD];
516
54
      if (!FD || !isa<VarDecl>(VD))
517
0
        continue;
518
519
      // If the capture field is a reference type, it is capture-by-reference.
520
54
      if (FD->getType()->isReferenceType())
521
21
        Escaped.insert(cast<VarDecl>(VD));
522
54
    }
523
55
  }
524
};
525
} // end anonymous namespace
526
527
528
//===----------------------------------------------------------------------===//
529
// DeadStoresChecker
530
//===----------------------------------------------------------------------===//
531
532
void DeadStoresChecker::checkASTCodeBody(const Decl *D, AnalysisManager &mgr,
533
569
                                         BugReporter &BR) const {
534
535
  // Don't do anything for template instantiations.
536
  // Proving that code in a template instantiation is "dead"
537
  // means proving that it is dead in all instantiations.
538
  // This same problem exists with -Wunreachable-code.
539
569
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
540
521
    if (FD->isTemplateInstantiation())
541
26
      return;
542
543
543
  if (LiveVariables *L = mgr.getAnalysis<LiveVariables>(D)) {
544
543
    CFG &cfg = *mgr.getCFG(D);
545
543
    AnalysisDeclContext *AC = mgr.getAnalysisDeclContext(D);
546
543
    ParentMap &pmap = mgr.getParentMap(D);
547
543
    FindEscaped FS;
548
543
    cfg.VisitBlockStmts(FS);
549
543
    DeadStoreObs A(cfg, BR.getContext(), BR, this, AC, pmap, FS.Escaped,
550
543
                   WarnForDeadNestedAssignments);
551
543
    L->runOnAllBlocks(A);
552
543
  }
553
543
}
554
555
59
void ento::registerDeadStoresChecker(CheckerManager &Mgr) {
556
59
  auto *Chk = Mgr.registerChecker<DeadStoresChecker>();
557
558
59
  const AnalyzerOptions &AnOpts = Mgr.getAnalyzerOptions();
559
59
  Chk->WarnForDeadNestedAssignments =
560
59
      AnOpts.getCheckerBooleanOption(Chk, "WarnForDeadNestedAssignments");
561
59
  Chk->ShowFixIts =
562
59
      AnOpts.getCheckerBooleanOption(Chk, "ShowFixIts");
563
59
}
564
565
122
bool ento::shouldRegisterDeadStoresChecker(const CheckerManager &mgr) {
566
122
  return true;
567
122
}