Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/Environment.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Environment.cpp - Map from Stmt* to Locations/Values ---------------===//
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 defined the Environment and EnvironmentManager classes.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
14
#include "clang/AST/Expr.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/AST/PrettyPrinter.h"
17
#include "clang/AST/Stmt.h"
18
#include "clang/AST/StmtObjC.h"
19
#include "clang/Analysis/AnalysisDeclContext.h"
20
#include "clang/Basic/LLVM.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/JsonSupport.h"
23
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
25
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
26
#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
27
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
28
#include "llvm/ADT/ImmutableMap.h"
29
#include "llvm/ADT/SmallPtrSet.h"
30
#include "llvm/Support/Casting.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include "llvm/Support/raw_ostream.h"
33
#include <cassert>
34
35
using namespace clang;
36
using namespace ento;
37
38
3.96M
static const Expr *ignoreTransparentExprs(const Expr *E) {
39
3.96M
  E = E->IgnoreParens();
40
41
3.96M
  switch (E->getStmtClass()) {
42
3.39k
  case Stmt::OpaqueValueExprClass:
43
3.39k
    E = cast<OpaqueValueExpr>(E)->getSourceExpr();
44
3.39k
    break;
45
14.0k
  case Stmt::ExprWithCleanupsClass:
46
14.0k
    E = cast<ExprWithCleanups>(E)->getSubExpr();
47
14.0k
    break;
48
30
  case Stmt::ConstantExprClass:
49
30
    E = cast<ConstantExpr>(E)->getSubExpr();
50
30
    break;
51
2.28k
  case Stmt::CXXBindTemporaryExprClass:
52
2.28k
    E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
53
2.28k
    break;
54
14
  case Stmt::SubstNonTypeTemplateParmExprClass:
55
14
    E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
56
14
    break;
57
3.94M
  default:
58
    // This is the base case: we can't look through more than we already have.
59
3.94M
    return E;
60
19.7k
  }
61
62
19.7k
  return ignoreTransparentExprs(E);
63
19.7k
}
64
65
3.96M
static const Stmt *ignoreTransparentExprs(const Stmt *S) {
66
3.96M
  if (const auto *E = dyn_cast<Expr>(S))
67
3.94M
    return ignoreTransparentExprs(E);
68
16.6k
  return S;
69
16.6k
}
70
71
EnvironmentEntry::EnvironmentEntry(const Stmt *S, const LocationContext *L)
72
    : std::pair<const Stmt *,
73
                const StackFrameContext *>(ignoreTransparentExprs(S),
74
                                           L ? L->getStackFrame()
75
3.96M
                                             : nullptr) {}
76
77
1.51M
SVal Environment::lookupExpr(const EnvironmentEntry &E) const {
78
1.51M
  const SVal* X = ExprBindings.lookup(E);
79
1.51M
  if (X) {
80
1.46M
    SVal V = *X;
81
1.46M
    return V;
82
1.46M
  }
83
51.9k
  return UnknownVal();
84
51.9k
}
85
86
SVal Environment::getSVal(const EnvironmentEntry &Entry,
87
1.61M
                          SValBuilder& svalBuilder) const {
88
1.61M
  const Stmt *S = Entry.getStmt();
89
1.61M
  assert(!isa<ObjCForCollectionStmt>(S) &&
90
1.61M
         "Use ExprEngine::hasMoreIteration()!");
91
1.61M
  assert((isa<Expr>(S) || isa<ReturnStmt>(S)) &&
92
1.61M
         "Environment can only argue about Exprs, since only they express "
93
1.61M
         "a value! Any non-expression statement stored in Environment is a "
94
1.61M
         "result of a hack!");
95
1.61M
  const LocationContext *LCtx = Entry.getLocationContext();
96
97
1.61M
  switch (S->getStmtClass()) {
98
0
  case Stmt::CXXBindTemporaryExprClass:
99
0
  case Stmt::ExprWithCleanupsClass:
100
0
  case Stmt::GenericSelectionExprClass:
101
0
  case Stmt::OpaqueValueExprClass:
102
0
  case Stmt::ConstantExprClass:
103
0
  case Stmt::ParenExprClass:
104
0
  case Stmt::SubstNonTypeTemplateParmExprClass:
105
0
    llvm_unreachable("Should have been handled by ignoreTransparentExprs");
106
107
77.2k
  case Stmt::AddrLabelExprClass:
108
77.2k
  case Stmt::CharacterLiteralClass:
109
77.2k
  case Stmt::CXXBoolLiteralExprClass:
110
77.2k
  case Stmt::CXXScalarValueInitExprClass:
111
77.2k
  case Stmt::ImplicitValueInitExprClass:
112
77.2k
  case Stmt::IntegerLiteralClass:
113
77.2k
  case Stmt::ObjCBoolLiteralExprClass:
114
77.2k
  case Stmt::CXXNullPtrLiteralExprClass:
115
77.2k
  case Stmt::ObjCStringLiteralClass:
116
77.2k
  case Stmt::StringLiteralClass:
117
77.2k
  case Stmt::TypeTraitExprClass:
118
77.2k
  case Stmt::SizeOfPackExprClass:
119
77.2k
  case Stmt::PredefinedExprClass:
120
    // Known constants; defer to SValBuilder.
121
77.2k
    return svalBuilder.getConstantVal(cast<Expr>(S)).getValue();
122
123
16.6k
  case Stmt::ReturnStmtClass: {
124
16.6k
    const auto *RS = cast<ReturnStmt>(S);
125
16.6k
    if (const Expr *RE = RS->getRetValue())
126
14.7k
      return getSVal(EnvironmentEntry(RE, LCtx), svalBuilder);
127
1.92k
    return UndefinedVal();
128
1.92k
  }
129
130
  // Handle all other Stmt* using a lookup.
131
1.51M
  default:
132
1.51M
    return lookupExpr(EnvironmentEntry(S, LCtx));
133
1.61M
  }
134
1.61M
}
135
136
Environment EnvironmentManager::bindExpr(Environment Env,
137
                                         const EnvironmentEntry &E,
138
                                         SVal V,
139
830k
                                         bool Invalidate) {
140
830k
  if (V.isUnknown()) {
141
24.6k
    if (Invalidate)
142
24.6k
      return Environment(F.remove(Env.ExprBindings, E));
143
0
    else
144
0
      return Env;
145
805k
  }
146
805k
  return Environment(F.add(Env.ExprBindings, E, V));
147
805k
}
148
149
namespace {
150
151
class MarkLiveCallback final : public SymbolVisitor {
152
  SymbolReaper &SymReaper;
153
154
public:
155
361k
  MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {}
156
157
414k
  bool VisitSymbol(SymbolRef sym) override {
158
414k
    SymReaper.markLive(sym);
159
414k
    return true;
160
414k
  }
161
162
887k
  bool VisitMemRegion(const MemRegion *R) override {
163
887k
    SymReaper.markLive(R);
164
887k
    return true;
165
887k
  }
166
};
167
168
} // namespace
169
170
// removeDeadBindings:
171
//  - Remove subexpression bindings.
172
//  - Remove dead block expression bindings.
173
//  - Keep live block expression bindings:
174
//   - Mark their reachable symbols live in SymbolReaper,
175
//     see ScanReachableSymbols.
176
//   - Mark the region in DRoots if the binding is a loc::MemRegionVal.
177
Environment
178
EnvironmentManager::removeDeadBindings(Environment Env,
179
                                       SymbolReaper &SymReaper,
180
361k
                                       ProgramStateRef ST) {
181
  // We construct a new Environment object entirely, as this is cheaper than
182
  // individually removing all the subexpression bindings (which will greatly
183
  // outnumber block-level expression bindings).
184
361k
  Environment NewEnv = getInitialEnvironment();
185
186
361k
  MarkLiveCallback CB(SymReaper);
187
361k
  ScanReachableSymbols RSScaner(ST, CB);
188
189
361k
  llvm::ImmutableMapRef<EnvironmentEntry, SVal>
190
361k
    EBMapRef(NewEnv.ExprBindings.getRootWithoutRetain(),
191
361k
             F.getTreeFactory());
192
193
  // Iterate over the block-expr bindings.
194
2.36M
  for (Environment::iterator I = Env.begin(), End = Env.end(); I != End; 
++I2.00M
) {
195
2.00M
    const EnvironmentEntry &BlkExpr = I.getKey();
196
2.00M
    const SVal &X = I.getData();
197
198
2.00M
    const Expr *E = dyn_cast<Expr>(BlkExpr.getStmt());
199
2.00M
    if (!E)
200
0
      continue;
201
202
2.00M
    if (SymReaper.isLive(E, BlkExpr.getLocationContext())) {
203
      // Copy the binding to the new map.
204
1.11M
      EBMapRef = EBMapRef.add(BlkExpr, X);
205
206
      // Mark all symbols in the block expr's value live.
207
1.11M
      RSScaner.scan(X);
208
1.11M
    }
209
2.00M
  }
210
211
361k
  NewEnv.ExprBindings = EBMapRef.asImmutableMap();
212
361k
  return NewEnv;
213
361k
}
214
215
void Environment::printJson(raw_ostream &Out, const ASTContext &Ctx,
216
                            const LocationContext *LCtx, const char *NL,
217
126
                            unsigned int Space, bool IsDot) const {
218
126
  Indent(Out, Space, IsDot) << "\"environment\": ";
219
220
126
  if (ExprBindings.isEmpty()) {
221
36
    Out << "null," << NL;
222
36
    return;
223
36
  }
224
225
90
  ++Space;
226
90
  if (!LCtx) {
227
    // Find the freshest location context.
228
26
    llvm::SmallPtrSet<const LocationContext *, 16> FoundContexts;
229
26
    for (const auto &I : *this) {
230
26
      const LocationContext *LC = I.first.getLocationContext();
231
26
      if (FoundContexts.count(LC) == 0) {
232
        // This context is fresher than all other contexts so far.
233
26
        LCtx = LC;
234
52
        for (const LocationContext *LCI = LC; LCI; 
LCI = LCI->getParent()26
)
235
26
          FoundContexts.insert(LCI);
236
26
      }
237
26
    }
238
26
  }
239
240
90
  assert(LCtx);
241
242
90
  Out << "{ \"pointer\": \"" << (const void *)LCtx->getStackFrame()
243
90
      << "\", \"items\": [" << NL;
244
90
  PrintingPolicy PP = Ctx.getPrintingPolicy();
245
246
99
  LCtx->printJson(Out, NL, Space, IsDot, [&](const LocationContext *LC) {
247
    // LCtx items begin
248
99
    bool HasItem = false;
249
99
    unsigned int InnerSpace = Space + 1;
250
251
    // Store the last ExprBinding which we will print.
252
99
    BindingsTy::iterator LastI = ExprBindings.end();
253
228
    for (BindingsTy::iterator I = ExprBindings.begin(); I != ExprBindings.end();
254
129
         ++I) {
255
129
      if (I->first.getLocationContext() != LC)
256
9
        continue;
257
258
120
      if (!HasItem) {
259
90
        HasItem = true;
260
90
        Out << '[' << NL;
261
90
      }
262
263
120
      const Stmt *S = I->first.getStmt();
264
120
      (void)S;
265
120
      assert(S != nullptr && "Expected non-null Stmt");
266
267
120
      LastI = I;
268
120
    }
269
270
228
    for (BindingsTy::iterator I = ExprBindings.begin(); I != ExprBindings.end();
271
129
         ++I) {
272
129
      if (I->first.getLocationContext() != LC)
273
9
        continue;
274
275
120
      const Stmt *S = I->first.getStmt();
276
120
      Indent(Out, InnerSpace, IsDot)
277
120
          << "{ \"stmt_id\": " << S->getID(Ctx) << ", \"pretty\": ";
278
120
      S->printJson(Out, nullptr, PP, /*AddQuotes=*/true);
279
280
120
      Out << ", \"value\": ";
281
120
      I->second.printJson(Out, /*AddQuotes=*/true);
282
283
120
      Out << " }";
284
285
120
      if (I != LastI)
286
30
        Out << ',';
287
120
      Out << NL;
288
120
    }
289
290
99
    if (HasItem)
291
90
      Indent(Out, --InnerSpace, IsDot) << ']';
292
9
    else
293
9
      Out << "null ";
294
99
  });
295
296
90
  Indent(Out, --Space, IsDot) << "]}," << NL;
297
90
}