Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- 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 the C++ expression evaluation engine.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
14
#include "clang/Analysis/ConstructionContext.h"
15
#include "clang/AST/DeclCXX.h"
16
#include "clang/AST/StmtCXX.h"
17
#include "clang/AST/ParentMap.h"
18
#include "clang/Basic/PrettyStackTrace.h"
19
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
23
using namespace clang;
24
using namespace ento;
25
26
void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
27
                                          ExplodedNode *Pred,
28
11.1k
                                          ExplodedNodeSet &Dst) {
29
11.1k
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
30
11.1k
  const Expr *tempExpr = ME->getSubExpr()->IgnoreParens();
31
11.1k
  ProgramStateRef state = Pred->getState();
32
11.1k
  const LocationContext *LCtx = Pred->getLocationContext();
33
11.1k
34
11.1k
  state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
35
11.1k
  Bldr.generateNode(ME, Pred, state);
36
11.1k
}
37
38
// FIXME: This is the sort of code that should eventually live in a Core
39
// checker rather than as a special case in ExprEngine.
40
void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
41
19.9k
                                    const CallEvent &Call) {
42
19.9k
  SVal ThisVal;
43
19.9k
  bool AlwaysReturnsLValue;
44
19.9k
  const CXXRecordDecl *ThisRD = nullptr;
45
19.9k
  if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
46
19.8k
    assert(Ctor->getDecl()->isTrivial());
47
19.8k
    assert(Ctor->getDecl()->isCopyOrMoveConstructor());
48
19.8k
    ThisVal = Ctor->getCXXThisVal();
49
19.8k
    ThisRD = Ctor->getDecl()->getParent();
50
19.8k
    AlwaysReturnsLValue = false;
51
19.8k
  } else {
52
110
    assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
53
110
    assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
54
110
           OO_Equal);
55
110
    ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
56
110
    ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
57
110
    AlwaysReturnsLValue = true;
58
110
  }
59
19.9k
60
19.9k
  assert(ThisRD);
61
19.9k
  if (ThisRD->isEmpty()) {
62
5.09k
    // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal
63
5.09k
    // and bind it and RegionStore would think that the actual value
64
5.09k
    // in this region at this offset is unknown.
65
5.09k
    return;
66
5.09k
  }
67
14.8k
68
14.8k
  const LocationContext *LCtx = Pred->getLocationContext();
69
14.8k
70
14.8k
  ExplodedNodeSet Dst;
71
14.8k
  Bldr.takeNodes(Pred);
72
14.8k
73
14.8k
  SVal V = Call.getArgSVal(0);
74
14.8k
75
14.8k
  // If the value being copied is not unknown, load from its location to get
76
14.8k
  // an aggregate rvalue.
77
14.8k
  if (Optional<Loc> L = V.getAs<Loc>())
78
14.8k
    V = Pred->getState()->getSVal(*L);
79
14.8k
  else
80
14.8k
    assert(V.isUnknownOrUndef());
81
14.8k
82
14.8k
  const Expr *CallExpr = Call.getOriginExpr();
83
14.8k
  evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
84
14.8k
85
14.8k
  PostStmt PS(CallExpr, LCtx);
86
14.8k
  for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
87
29.7k
       I != E; 
++I14.8k
) {
88
14.8k
    ProgramStateRef State = (*I)->getState();
89
14.8k
    if (AlwaysReturnsLValue)
90
79
      State = State->BindExpr(CallExpr, LCtx, ThisVal);
91
14.8k
    else
92
14.8k
      State = bindReturnValue(Call, LCtx, State);
93
14.8k
    Bldr.generateNode(PS, State, *I);
94
14.8k
  }
95
14.8k
}
96
97
98
SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue,
99
15.6k
                                       QualType &Ty, bool &IsArray) {
100
15.6k
  SValBuilder &SVB = State->getStateManager().getSValBuilder();
101
15.6k
  ASTContext &Ctx = SVB.getContext();
102
15.6k
103
15.8k
  while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
104
128
    Ty = AT->getElementType();
105
128
    LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
106
128
    IsArray = true;
107
128
  }
108
15.6k
109
15.6k
  return LValue;
110
15.6k
}
111
112
std::pair<ProgramStateRef, SVal> ExprEngine::handleConstructionContext(
113
    const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
114
47.0k
    const ConstructionContext *CC, EvalCallOptions &CallOpts) {
115
47.0k
  SValBuilder &SVB = getSValBuilder();
116
47.0k
  MemRegionManager &MRMgr = SVB.getRegionManager();
117
47.0k
  ASTContext &ACtx = SVB.getContext();
118
47.0k
119
47.0k
  // See if we're constructing an existing region by looking at the
120
47.0k
  // current construction context.
121
47.0k
  if (CC) {
122
46.7k
    switch (CC->getKind()) {
123
12.4k
    case ConstructionContext::CXX17ElidedCopyVariableKind:
124
12.4k
    case ConstructionContext::SimpleVariableKind: {
125
12.4k
      const auto *DSCC = cast<VariableConstructionContext>(CC);
126
12.4k
      const auto *DS = DSCC->getDeclStmt();
127
12.4k
      const auto *Var = cast<VarDecl>(DS->getSingleDecl());
128
12.4k
      SVal LValue = State->getLValue(Var, LCtx);
129
12.4k
      QualType Ty = Var->getType();
130
12.4k
      LValue =
131
12.4k
          makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor);
132
12.4k
      State =
133
12.4k
          addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, LValue);
134
12.4k
      return std::make_pair(State, LValue);
135
12.4k
    }
136
12.4k
    case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
137
2.55k
    case ConstructionContext::SimpleConstructorInitializerKind: {
138
2.55k
      const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
139
2.55k
      const auto *Init = ICC->getCXXCtorInitializer();
140
2.55k
      assert(Init->isAnyMemberInitializer());
141
2.55k
      const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
142
2.55k
      Loc ThisPtr =
143
2.55k
      SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
144
2.55k
      SVal ThisVal = State->getSVal(ThisPtr);
145
2.55k
146
2.55k
      const ValueDecl *Field;
147
2.55k
      SVal FieldVal;
148
2.55k
      if (Init->isIndirectMemberInitializer()) {
149
0
        Field = Init->getIndirectMember();
150
0
        FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
151
2.55k
      } else {
152
2.55k
        Field = Init->getMember();
153
2.55k
        FieldVal = State->getLValue(Init->getMember(), ThisVal);
154
2.55k
      }
155
2.55k
156
2.55k
      QualType Ty = Field->getType();
157
2.55k
      FieldVal = makeZeroElementRegion(State, FieldVal, Ty,
158
2.55k
                                       CallOpts.IsArrayCtorOrDtor);
159
2.55k
      State = addObjectUnderConstruction(State, Init, LCtx, FieldVal);
160
2.55k
      return std::make_pair(State, FieldVal);
161
2.55k
    }
162
3.17k
    case ConstructionContext::NewAllocatedObjectKind: {
163
3.17k
      if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
164
3.16k
        const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
165
3.16k
        const auto *NE = NECC->getCXXNewExpr();
166
3.16k
        SVal V = *getObjectUnderConstruction(State, NE, LCtx);
167
3.16k
        if (const SubRegion *MR =
168
3.15k
                dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
169
3.15k
          if (NE->isArray()) {
170
39
            // TODO: In fact, we need to call the constructor for every
171
39
            // allocated element, not just the first one!
172
39
            CallOpts.IsArrayCtorOrDtor = true;
173
39
            return std::make_pair(
174
39
                State, loc::MemRegionVal(getStoreManager().GetElementZeroRegion(
175
39
                           MR, NE->getType()->getPointeeType())));
176
39
          }
177
3.11k
          return std::make_pair(State, V);
178
3.11k
        }
179
3.16k
        // TODO: Detect when the allocator returns a null pointer.
180
3.16k
        // Constructor shall not be called in this case.
181
3.16k
      }
182
15
      break;
183
15
    }
184
1.13k
    case ConstructionContext::SimpleReturnedValueKind:
185
1.13k
    case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
186
1.13k
      // The temporary is to be managed by the parent stack frame.
187
1.13k
      // So build it in the parent stack frame if we're not in the
188
1.13k
      // top frame of the analysis.
189
1.13k
      const StackFrameContext *SFC = LCtx->getStackFrame();
190
1.13k
      if (const LocationContext *CallerLCtx = SFC->getParent()) {
191
1.07k
        auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
192
1.07k
                       .getAs<CFGCXXRecordTypedCall>();
193
1.07k
        if (!RTC) {
194
175
          // We were unable to find the correct construction context for the
195
175
          // call in the parent stack frame. This is equivalent to not being
196
175
          // able to find construction context at all.
197
175
          break;
198
175
        }
199
899
        if (isa<BlockInvocationContext>(CallerLCtx)) {
200
1
          // Unwrap block invocation contexts. They're mostly part of
201
1
          // the current stack frame.
202
1
          CallerLCtx = CallerLCtx->getParent();
203
1
          assert(!isa<BlockInvocationContext>(CallerLCtx));
204
1
        }
205
899
        return handleConstructionContext(
206
899
            cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
207
899
            RTC->getConstructionContext(), CallOpts);
208
899
      } else {
209
57
        // We are on the top frame of the analysis. We do not know where is the
210
57
        // object returned to. Conjure a symbolic region for the return value.
211
57
        // TODO: We probably need a new MemRegion kind to represent the storage
212
57
        // of that SymbolicRegion, so that we cound produce a fancy symbol
213
57
        // instead of an anonymous conjured symbol.
214
57
        // TODO: Do we need to track the region to avoid having it dead
215
57
        // too early? It does die too early, at least in C++17, but because
216
57
        // putting anything into a SymbolicRegion causes an immediate escape,
217
57
        // it doesn't cause any leak false positives.
218
57
        const auto *RCC = cast<ReturnedValueConstructionContext>(CC);
219
57
        // Make sure that this doesn't coincide with any other symbol
220
57
        // conjured for the returned expression.
221
57
        static const int TopLevelSymRegionTag = 0;
222
57
        const Expr *RetE = RCC->getReturnStmt()->getRetValue();
223
57
        assert(RetE && "Void returns should not have a construction context");
224
57
        QualType ReturnTy = RetE->getType();
225
57
        QualType RegionTy = ACtx.getPointerType(ReturnTy);
226
57
        SVal V = SVB.conjureSymbolVal(&TopLevelSymRegionTag, RetE, SFC,
227
57
                                      RegionTy, currBldrCtx->blockCount());
228
57
        return std::make_pair(State, V);
229
57
      }
230
0
      llvm_unreachable("Unhandled return value construction context!");
231
0
    }
232
6.95k
    case ConstructionContext::ElidedTemporaryObjectKind: {
233
6.95k
      assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
234
6.95k
      const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
235
6.95k
      const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
236
6.95k
      const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
237
6.95k
      const CXXConstructExpr *CE = TCC->getConstructorAfterElision();
238
6.95k
239
6.95k
      // Support pre-C++17 copy elision. We'll have the elidable copy
240
6.95k
      // constructor in the AST and in the CFG, but we'll skip it
241
6.95k
      // and construct directly into the final object. This call
242
6.95k
      // also sets the CallOpts flags for us.
243
6.95k
      SVal V;
244
6.95k
      // If the elided copy/move constructor is not supported, there's still
245
6.95k
      // benefit in trying to model the non-elided constructor.
246
6.95k
      // Stash our state before trying to elide, as it'll get overwritten.
247
6.95k
      ProgramStateRef PreElideState = State;
248
6.95k
      EvalCallOptions PreElideCallOpts = CallOpts;
249
6.95k
250
6.95k
      std::tie(State, V) = handleConstructionContext(
251
6.95k
          CE, State, LCtx, TCC->getConstructionContextAfterElision(), CallOpts);
252
6.95k
253
6.95k
      // FIXME: This definition of "copy elision has not failed" is unreliable.
254
6.95k
      // It doesn't indicate that the constructor will actually be inlined
255
6.95k
      // later; it is still up to evalCall() to decide.
256
6.95k
      if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) {
257
6.47k
        // Remember that we've elided the constructor.
258
6.47k
        State = addObjectUnderConstruction(State, CE, LCtx, V);
259
6.47k
260
6.47k
        // Remember that we've elided the destructor.
261
6.47k
        if (BTE)
262
317
          State = elideDestructor(State, BTE, LCtx);
263
6.47k
264
6.47k
        // Instead of materialization, shamelessly return
265
6.47k
        // the final object destination.
266
6.47k
        if (MTE)
267
6.47k
          State = addObjectUnderConstruction(State, MTE, LCtx, V);
268
6.47k
269
6.47k
        return std::make_pair(State, V);
270
6.47k
      } else {
271
480
        // Copy elision failed. Revert the changes and proceed as if we have
272
480
        // a simple temporary.
273
480
        State = PreElideState;
274
480
        CallOpts = PreElideCallOpts;
275
480
      }
276
6.95k
      
LLVM_FALLTHROUGH480
;
277
480
    }
278
2.07k
    case ConstructionContext::SimpleTemporaryObjectKind: {
279
2.07k
      const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
280
2.07k
      const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
281
2.07k
      const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
282
2.07k
      SVal V = UnknownVal();
283
2.07k
284
2.07k
      if (MTE) {
285
1.95k
        if (const ValueDecl *VD = MTE->getExtendingDecl()) {
286
182
          assert(MTE->getStorageDuration() != SD_FullExpression);
287
182
          if (!VD->getType()->isReferenceType()) {
288
24
            // We're lifetime-extended by a surrounding aggregate.
289
24
            // Automatic destructors aren't quite working in this case
290
24
            // on the CFG side. We should warn the caller about that.
291
24
            // FIXME: Is there a better way to retrieve this information from
292
24
            // the MaterializeTemporaryExpr?
293
24
            CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true;
294
24
          }
295
182
        }
296
1.95k
297
1.95k
        if (MTE->getStorageDuration() == SD_Static ||
298
1.95k
            
MTE->getStorageDuration() == SD_Thread1.95k
)
299
14
          V = loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E));
300
1.95k
      }
301
2.07k
302
2.07k
      if (V.isUnknown())
303
2.06k
        V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
304
2.07k
305
2.07k
      if (BTE)
306
615
        State = addObjectUnderConstruction(State, BTE, LCtx, V);
307
2.07k
308
2.07k
      if (MTE)
309
1.95k
        State = addObjectUnderConstruction(State, MTE, LCtx, V);
310
2.07k
311
2.07k
      CallOpts.IsTemporaryCtorOrDtor = true;
312
2.07k
      return std::make_pair(State, V);
313
480
    }
314
18.8k
    case ConstructionContext::ArgumentKind: {
315
18.8k
      // Arguments are technically temporaries.
316
18.8k
      CallOpts.IsTemporaryCtorOrDtor = true;
317
18.8k
318
18.8k
      const auto *ACC = cast<ArgumentConstructionContext>(CC);
319
18.8k
      const Expr *E = ACC->getCallLikeExpr();
320
18.8k
      unsigned Idx = ACC->getIndex();
321
18.8k
      const CXXBindTemporaryExpr *BTE = ACC->getCXXBindTemporaryExpr();
322
18.8k
323
18.8k
      CallEventManager &CEMgr = getStateManager().getCallEventManager();
324
18.8k
      SVal V = UnknownVal();
325
18.8k
      auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> {
326
18.8k
        const LocationContext *FutureSFC =
327
18.8k
            Caller->getCalleeStackFrame(currBldrCtx->blockCount());
328
18.8k
        // Return early if we are unable to reliably foresee
329
18.8k
        // the future stack frame.
330
18.8k
        if (!FutureSFC)
331
10.2k
          return None;
332
8.60k
333
8.60k
        // This should be equivalent to Caller->getDecl() for now, but
334
8.60k
        // FutureSFC->getDecl() is likely to support better stuff (like
335
8.60k
        // virtual functions) earlier.
336
8.60k
        const Decl *CalleeD = FutureSFC->getDecl();
337
8.60k
338
8.60k
        // FIXME: Support for variadic arguments is not implemented here yet.
339
8.60k
        if (CallEvent::isVariadic(CalleeD))
340
0
          return None;
341
8.60k
342
8.60k
        // Operator arguments do not correspond to operator parameters
343
8.60k
        // because this-argument is implemented as a normal argument in
344
8.60k
        // operator call expressions but not in operator declarations.
345
8.60k
        const VarRegion *VR = Caller->getParameterLocation(
346
8.60k
            *Caller->getAdjustedParameterIndex(Idx), currBldrCtx->blockCount());
347
8.60k
        if (!VR)
348
0
          return None;
349
8.60k
350
8.60k
        return loc::MemRegionVal(VR);
351
8.60k
      };
352
18.8k
353
18.8k
      if (const auto *CE = dyn_cast<CallExpr>(E)) {
354
18.8k
        CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx);
355
18.8k
        if (auto OptV = getArgLoc(Caller))
356
8.57k
          V = *OptV;
357
10.2k
        else
358
10.2k
          break;
359
8.57k
        State = addObjectUnderConstruction(State, {CE, Idx}, LCtx, V);
360
8.57k
      } else 
if (const auto *69
CCE69
= dyn_cast<CXXConstructExpr>(E)) {
361
58
        // Don't bother figuring out the target region for the future
362
58
        // constructor because we won't need it.
363
58
        CallEventRef<> Caller =
364
58
            CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx);
365
58
        if (auto OptV = getArgLoc(Caller))
366
22
          V = *OptV;
367
36
        else
368
36
          break;
369
22
        State = addObjectUnderConstruction(State, {CCE, Idx}, LCtx, V);
370
22
      } else 
if (const auto *11
ME11
= dyn_cast<ObjCMessageExpr>(E)) {
371
11
        CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx);
372
11
        if (auto OptV = getArgLoc(Caller))
373
0
          V = *OptV;
374
11
        else
375
11
          break;
376
0
        State = addObjectUnderConstruction(State, {ME, Idx}, LCtx, V);
377
0
      }
378
18.8k
379
18.8k
      assert(!V.isUnknown());
380
8.60k
381
8.60k
      if (BTE)
382
18
        State = addObjectUnderConstruction(State, BTE, LCtx, V);
383
8.60k
384
8.60k
      return std::make_pair(State, V);
385
10.7k
    }
386
46.7k
    }
387
46.7k
  }
388
10.7k
  // If we couldn't find an existing region to construct into, assume we're
389
10.7k
  // constructing a temporary. Notify the caller of our failure.
390
10.7k
  CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
391
10.7k
  return std::make_pair(
392
10.7k
      State, loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)));
393
10.7k
}
394
395
void ExprEngine::handleConstructor(const Expr *E,
396
                                   ExplodedNode *Pred,
397
44.7k
                                   ExplodedNodeSet &destNodes) {
398
44.7k
  const auto *CE = dyn_cast<CXXConstructExpr>(E);
399
44.7k
  const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E);
400
44.7k
  assert(CE || CIE);
401
44.7k
402
44.7k
  const LocationContext *LCtx = Pred->getLocationContext();
403
44.7k
  ProgramStateRef State = Pred->getState();
404
44.7k
405
44.7k
  SVal Target = UnknownVal();
406
44.7k
407
44.7k
  if (CE) {
408
44.7k
    if (Optional<SVal> ElidedTarget =
409
6.47k
            getObjectUnderConstruction(State, CE, LCtx)) {
410
6.47k
      // We've previously modeled an elidable constructor by pretending that it
411
6.47k
      // in fact constructs into the correct target. This constructor can
412
6.47k
      // therefore be skipped.
413
6.47k
      Target = *ElidedTarget;
414
6.47k
      StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx);
415
6.47k
      State = finishObjectConstruction(State, CE, LCtx);
416
6.47k
      if (auto L = Target.getAs<Loc>())
417
6.47k
        State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType()));
418
6.47k
      Bldr.generateNode(CE, Pred, State);
419
6.47k
      return;
420
6.47k
    }
421
38.2k
  }
422
38.2k
423
38.2k
  // FIXME: Handle arrays, which run the same constructor for every element.
424
38.2k
  // For now, we just run the first constructor (which should still invalidate
425
38.2k
  // the entire array).
426
38.2k
427
38.2k
  EvalCallOptions CallOpts;
428
38.2k
  auto C = getCurrentCFGElement().getAs<CFGConstructor>();
429
38.2k
  assert(C || getCurrentCFGElement().getAs<CFGStmt>());
430
38.2k
  const ConstructionContext *CC = C ? 
C->getConstructionContext()37.9k
:
nullptr326
;
431
38.2k
432
38.2k
  const CXXConstructExpr::ConstructionKind CK =
433
38.2k
      CE ? 
CE->getConstructionKind()38.2k
:
CIE->getConstructionKind()5
;
434
38.2k
  switch (CK) {
435
37.4k
  case CXXConstructExpr::CK_Complete: {
436
37.4k
    // Inherited constructors are always base class constructors.
437
37.4k
    assert(CE && !CIE && "A complete constructor is inherited?!");
438
37.4k
439
37.4k
    // The target region is found from construction context.
440
37.4k
    std::tie(State, Target) =
441
37.4k
        handleConstructionContext(CE, State, LCtx, CC, CallOpts);
442
37.4k
    break;
443
0
  }
444
116
  case CXXConstructExpr::CK_VirtualBase: {
445
116
    // Make sure we are not calling virtual base class initializers twice.
446
116
    // Only the most-derived object should initialize virtual base classes.
447
116
    const auto *OuterCtor = dyn_cast_or_null<CXXConstructExpr>(
448
116
        LCtx->getStackFrame()->getCallSite());
449
116
    assert(
450
116
        (!OuterCtor ||
451
116
         OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Complete ||
452
116
         OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Delegating) &&
453
116
        ("This virtual base should have already been initialized by "
454
116
         "the most derived class!"));
455
116
    (void)OuterCtor;
456
116
    LLVM_FALLTHROUGH;
457
116
  }
458
760
  case CXXConstructExpr::CK_NonVirtualBase:
459
760
    // In C++17, classes with non-virtual bases may be aggregates, so they would
460
760
    // be initialized as aggregates without a constructor call, so we may have
461
760
    // a base class constructed directly into an initializer list without
462
760
    // having the derived-class constructor call on the previous stack frame.
463
760
    // Initializer lists may be nested into more initializer lists that
464
760
    // correspond to surrounding aggregate initializations.
465
760
    // FIXME: For now this code essentially bails out. We need to find the
466
760
    // correct target region and set it.
467
760
    // FIXME: Instead of relying on the ParentMap, we should have the
468
760
    // trigger-statement (InitListExpr in this case) passed down from CFG or
469
760
    // otherwise always available during construction.
470
760
    if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(E))) {
471
24
      MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
472
24
      Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
473
24
      CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
474
24
      break;
475
24
    }
476
736
    LLVM_FALLTHROUGH;
477
746
  case CXXConstructExpr::CK_Delegating: {
478
746
    const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
479
746
    Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
480
746
                                              LCtx->getStackFrame());
481
746
    SVal ThisVal = State->getSVal(ThisPtr);
482
746
483
746
    if (CK == CXXConstructExpr::CK_Delegating) {
484
10
      Target = ThisVal;
485
736
    } else {
486
736
      // Cast to the base type.
487
736
      bool IsVirtual = (CK == CXXConstructExpr::CK_VirtualBase);
488
736
      SVal BaseVal =
489
736
          getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual);
490
736
      Target = BaseVal;
491
736
    }
492
746
    break;
493
38.2k
  }
494
38.2k
  }
495
38.2k
496
38.2k
  if (State != Pred->getState()) {
497
24.0k
    static SimpleProgramPointTag T("ExprEngine",
498
24.0k
                                   "Prepare for object construction");
499
24.0k
    ExplodedNodeSet DstPrepare;
500
24.0k
    StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx);
501
24.0k
    BldrPrepare.generateNode(E, Pred, State, &T, ProgramPoint::PreStmtKind);
502
24.0k
    assert(DstPrepare.size() <= 1);
503
24.0k
    if (DstPrepare.size() == 0)
504
26
      return;
505
23.9k
    Pred = *BldrPrepare.begin();
506
23.9k
  }
507
38.2k
508
38.2k
  const MemRegion *TargetRegion = Target.getAsRegion();
509
38.2k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
510
38.2k
  CallEventRef<> Call =
511
38.2k
      CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall(
512
5
                CIE, TargetRegion, State, LCtx)
513
38.2k
          : (CallEventRef<>)CEMgr.getCXXConstructorCall(
514
38.2k
                CE, TargetRegion, State, LCtx);
515
38.2k
516
38.2k
  ExplodedNodeSet DstPreVisit;
517
38.2k
  getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this);
518
38.2k
519
38.2k
  ExplodedNodeSet PreInitialized;
520
38.2k
  if (CE) {
521
38.2k
    // FIXME: Is it possible and/or useful to do this before PreStmt?
522
38.2k
    StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
523
38.2k
    for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
524
38.2k
                                   E = DstPreVisit.end();
525
76.4k
         I != E; 
++I38.2k
) {
526
38.2k
      ProgramStateRef State = (*I)->getState();
527
38.2k
      if (CE->requiresZeroInitialization()) {
528
1.81k
        // FIXME: Once we properly handle constructors in new-expressions, we'll
529
1.81k
        // need to invalidate the region before setting a default value, to make
530
1.81k
        // sure there aren't any lingering bindings around. This probably needs
531
1.81k
        // to happen regardless of whether or not the object is zero-initialized
532
1.81k
        // to handle random fields of a placement-initialized object picking up
533
1.81k
        // old bindings. We might only want to do it when we need to, though.
534
1.81k
        // FIXME: This isn't actually correct for arrays -- we need to zero-
535
1.81k
        // initialize the entire array, not just the first element -- but our
536
1.81k
        // handling of arrays everywhere else is weak as well, so this shouldn't
537
1.81k
        // actually make things worse. Placement new makes this tricky as well,
538
1.81k
        // since it's then possible to be initializing one part of a multi-
539
1.81k
        // dimensional array.
540
1.81k
        State = State->bindDefaultZero(Target, LCtx);
541
1.81k
      }
542
38.2k
543
38.2k
      Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
544
38.2k
                        ProgramPoint::PreStmtKind);
545
38.2k
    }
546
38.2k
  } else {
547
5
    PreInitialized = DstPreVisit;
548
5
  }
549
38.2k
550
38.2k
  ExplodedNodeSet DstPreCall;
551
38.2k
  getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
552
38.2k
                                            *Call, *this);
553
38.2k
554
38.2k
  ExplodedNodeSet DstEvaluated;
555
38.2k
  StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
556
38.2k
557
38.2k
  if (CE && 
CE->getConstructor()->isTrivial()38.2k
&&
558
38.2k
      
CE->getConstructor()->isCopyOrMoveConstructor()25.5k
&&
559
38.2k
      
!CallOpts.IsArrayCtorOrDtor19.8k
) {
560
19.8k
    // FIXME: Handle other kinds of trivial constructors as well.
561
19.8k
    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
562
39.7k
         I != E; 
++I19.8k
)
563
19.8k
      performTrivialCopy(Bldr, *I, *Call);
564
19.8k
565
19.8k
  } else {
566
18.3k
    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
567
36.7k
         I != E; 
++I18.3k
)
568
18.3k
      defaultEvalCall(Bldr, *I, *Call, CallOpts);
569
18.3k
  }
570
38.2k
571
38.2k
  // If the CFG was constructed without elements for temporary destructors
572
38.2k
  // and the just-called constructor created a temporary object then
573
38.2k
  // stop exploration if the temporary object has a noreturn constructor.
574
38.2k
  // This can lose coverage because the destructor, if it were present
575
38.2k
  // in the CFG, would be called at the end of the full expression or
576
38.2k
  // later (for life-time extended temporaries) -- but avoids infeasible
577
38.2k
  // paths when no-return temporary destructors are used for assertions.
578
38.2k
  const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
579
38.2k
  if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
580
291
    if (TargetRegion && isa<CXXTempObjectRegion>(TargetRegion) &&
581
291
        cast<CXXConstructorDecl>(Call->getDecl())
582
126
            ->getParent()->isAnyDestructorNoReturn()) {
583
4
584
4
      // If we've inlined the constructor, then DstEvaluated would be empty.
585
4
      // In this case we still want a sink, which could be implemented
586
4
      // in processCallExit. But we don't have that implemented at the moment,
587
4
      // so if you hit this assertion, see if you can avoid inlining
588
4
      // the respective constructor when analyzer-config cfg-temporary-dtors
589
4
      // is set to false.
590
4
      // Otherwise there's nothing wrong with inlining such constructor.
591
4
      assert(!DstEvaluated.empty() &&
592
4
             "We should not have inlined this constructor!");
593
4
594
4
      for (ExplodedNode *N : DstEvaluated) {
595
4
        Bldr.generateSink(E, N, N->getState());
596
4
      }
597
4
598
4
      // There is no need to run the PostCall and PostStmt checker
599
4
      // callbacks because we just generated sinks on all nodes in th
600
4
      // frontier.
601
4
      return;
602
4
    }
603
38.2k
  }
604
38.2k
605
38.2k
  ExplodedNodeSet DstPostArgumentCleanup;
606
38.2k
  for (auto I : DstEvaluated)
607
21.2k
    finishArgumentConstruction(DstPostArgumentCleanup, I, *Call);
608
38.2k
609
38.2k
  // If there were other constructors called for object-type arguments
610
38.2k
  // of this constructor, clean them up.
611
38.2k
  ExplodedNodeSet DstPostCall;
612
38.2k
  getCheckerManager().runCheckersForPostCall(DstPostCall,
613
38.2k
                                             DstPostArgumentCleanup,
614
38.2k
                                             *Call, *this);
615
38.2k
  getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this);
616
38.2k
}
617
618
void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
619
                                       ExplodedNode *Pred,
620
44.7k
                                       ExplodedNodeSet &Dst) {
621
44.7k
  handleConstructor(CE, Pred, Dst);
622
44.7k
}
623
624
void ExprEngine::VisitCXXInheritedCtorInitExpr(
625
    const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
626
5
    ExplodedNodeSet &Dst) {
627
5
  handleConstructor(CE, Pred, Dst);
628
5
}
629
630
void ExprEngine::VisitCXXDestructor(QualType ObjectType,
631
                                    const MemRegion *Dest,
632
                                    const Stmt *S,
633
                                    bool IsBaseDtor,
634
                                    ExplodedNode *Pred,
635
                                    ExplodedNodeSet &Dst,
636
1.80k
                                    EvalCallOptions &CallOpts) {
637
1.80k
  assert(S && "A destructor without a trigger!");
638
1.80k
  const LocationContext *LCtx = Pred->getLocationContext();
639
1.80k
  ProgramStateRef State = Pred->getState();
640
1.80k
641
1.80k
  const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
642
1.80k
  assert(RecordDecl && "Only CXXRecordDecls should have destructors");
643
1.80k
  const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
644
1.80k
  // FIXME: There should always be a Decl, otherwise the destructor call
645
1.80k
  // shouldn't have been added to the CFG in the first place.
646
1.80k
  if (!DtorDecl) {
647
1
    // Skip the invalid destructor. We cannot simply return because
648
1
    // it would interrupt the analysis instead.
649
1
    static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
650
1
    // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway.
651
1
    PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, &T);
652
1
    NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
653
1
    Bldr.generateNode(PP, Pred->getState(), Pred);
654
1
    return;
655
1
  }
656
1.79k
657
1.79k
  if (!Dest) {
658
339
    // We're trying to destroy something that is not a region. This may happen
659
339
    // for a variety of reasons (unknown target region, concrete integer instead
660
339
    // of target region, etc.). The current code makes an attempt to recover.
661
339
    // FIXME: We probably don't really need to recover when we're dealing
662
339
    // with concrete integers specifically.
663
339
    CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
664
339
    if (const Expr *E = dyn_cast_or_null<Expr>(S)) {
665
337
      Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext());
666
337
    } else {
667
2
      static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
668
2
      NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
669
2
      Bldr.generateSink(Pred->getLocation().withTag(&T),
670
2
                        Pred->getState(), Pred);
671
2
      return;
672
2
    }
673
1.79k
  }
674
1.79k
675
1.79k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
676
1.79k
  CallEventRef<CXXDestructorCall> Call =
677
1.79k
      CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
678
1.79k
679
1.79k
  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
680
1.79k
                                Call->getSourceRange().getBegin(),
681
1.79k
                                "Error evaluating destructor");
682
1.79k
683
1.79k
  ExplodedNodeSet DstPreCall;
684
1.79k
  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
685
1.79k
                                            *Call, *this);
686
1.79k
687
1.79k
  ExplodedNodeSet DstInvalidated;
688
1.79k
  StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
689
1.79k
  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
690
3.57k
       I != E; 
++I1.78k
)
691
1.78k
    defaultEvalCall(Bldr, *I, *Call, CallOpts);
692
1.79k
693
1.79k
  getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
694
1.79k
                                             *Call, *this);
695
1.79k
}
696
697
void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
698
                                          ExplodedNode *Pred,
699
6.42k
                                          ExplodedNodeSet &Dst) {
700
6.42k
  ProgramStateRef State = Pred->getState();
701
6.42k
  const LocationContext *LCtx = Pred->getLocationContext();
702
6.42k
  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
703
6.42k
                                CNE->getBeginLoc(),
704
6.42k
                                "Error evaluating New Allocator Call");
705
6.42k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
706
6.42k
  CallEventRef<CXXAllocatorCall> Call =
707
6.42k
    CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
708
6.42k
709
6.42k
  ExplodedNodeSet DstPreCall;
710
6.42k
  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
711
6.42k
                                            *Call, *this);
712
6.42k
713
6.42k
  ExplodedNodeSet DstPostCall;
714
6.42k
  StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
715
6.42k
  for (auto I : DstPreCall) {
716
6.41k
    // FIXME: Provide evalCall for checkers?
717
6.41k
    defaultEvalCall(CallBldr, I, *Call);
718
6.41k
  }
719
6.42k
  // If the call is inlined, DstPostCall will be empty and we bail out now.
720
6.42k
721
6.42k
  // Store return value of operator new() for future use, until the actual
722
6.42k
  // CXXNewExpr gets processed.
723
6.42k
  ExplodedNodeSet DstPostValue;
724
6.42k
  StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
725
6.42k
  for (auto I : DstPostCall) {
726
703
    // FIXME: Because CNE serves as the "call site" for the allocator (due to
727
703
    // lack of a better expression in the AST), the conjured return value symbol
728
703
    // is going to be of the same type (C++ object pointer type). Technically
729
703
    // this is not correct because the operator new's prototype always says that
730
703
    // it returns a 'void *'. So we should change the type of the symbol,
731
703
    // and then evaluate the cast over the symbolic pointer from 'void *' to
732
703
    // the object pointer type. But without changing the symbol's type it
733
703
    // is breaking too much to evaluate the no-op symbolic cast over it, so we
734
703
    // skip it for now.
735
703
    ProgramStateRef State = I->getState();
736
703
    SVal RetVal = State->getSVal(CNE, LCtx);
737
703
738
703
    // If this allocation function is not declared as non-throwing, failures
739
703
    // /must/ be signalled by exceptions, and thus the return value will never
740
703
    // be NULL. -fno-exceptions does not influence this semantics.
741
703
    // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
742
703
    // where new can return NULL. If we end up supporting that option, we can
743
703
    // consider adding a check for it here.
744
703
    // C++11 [basic.stc.dynamic.allocation]p3.
745
703
    if (const FunctionDecl *FD = CNE->getOperatorNew()) {
746
703
      QualType Ty = FD->getType();
747
703
      if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
748
703
        if (!ProtoType->isNothrow())
749
683
          State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
750
703
    }
751
703
752
703
    ValueBldr.generateNode(
753
703
        CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
754
703
  }
755
6.42k
756
6.42k
  ExplodedNodeSet DstPostPostCallCallback;
757
6.42k
  getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
758
6.42k
                                             DstPostValue, *Call, *this);
759
6.42k
  for (auto I : DstPostPostCallCallback) {
760
703
    getCheckerManager().runCheckersForNewAllocator(
761
703
        CNE, *getObjectUnderConstruction(I->getState(), CNE, LCtx), Dst, I,
762
703
        *this);
763
703
  }
764
6.42k
}
765
766
void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
767
6.41k
                                   ExplodedNodeSet &Dst) {
768
6.41k
  // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
769
6.41k
  // Also, we need to decide how allocators actually work -- they're not
770
6.41k
  // really part of the CXXNewExpr because they happen BEFORE the
771
6.41k
  // CXXConstructExpr subexpression. See PR12014 for some discussion.
772
6.41k
773
6.41k
  unsigned blockCount = currBldrCtx->blockCount();
774
6.41k
  const LocationContext *LCtx = Pred->getLocationContext();
775
6.41k
  SVal symVal = UnknownVal();
776
6.41k
  FunctionDecl *FD = CNE->getOperatorNew();
777
6.41k
778
6.41k
  bool IsStandardGlobalOpNewFunction =
779
6.41k
      FD->isReplaceableGlobalAllocationFunction();
780
6.41k
781
6.41k
  ProgramStateRef State = Pred->getState();
782
6.41k
783
6.41k
  // Retrieve the stored operator new() return value.
784
6.41k
  if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
785
6.40k
    symVal = *getObjectUnderConstruction(State, CNE, LCtx);
786
6.40k
    State = finishObjectConstruction(State, CNE, LCtx);
787
6.40k
  }
788
6.41k
789
6.41k
  // We assume all standard global 'operator new' functions allocate memory in
790
6.41k
  // heap. We realize this is an approximation that might not correctly model
791
6.41k
  // a custom global allocator.
792
6.41k
  if (symVal.isUnknown()) {
793
7
    if (IsStandardGlobalOpNewFunction)
794
5
      symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
795
2
    else
796
2
      symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
797
2
                                            blockCount);
798
7
  }
799
6.41k
800
6.41k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
801
6.41k
  CallEventRef<CXXAllocatorCall> Call =
802
6.41k
    CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
803
6.41k
804
6.41k
  if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
805
7
    // Invalidate placement args.
806
7
    // FIXME: Once we figure out how we want allocators to work,
807
7
    // we should be using the usual pre-/(default-)eval-/post-call checkers
808
7
    // here.
809
7
    State = Call->invalidateRegions(blockCount);
810
7
    if (!State)
811
0
      return;
812
7
813
7
    // If this allocation function is not declared as non-throwing, failures
814
7
    // /must/ be signalled by exceptions, and thus the return value will never
815
7
    // be NULL. -fno-exceptions does not influence this semantics.
816
7
    // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
817
7
    // where new can return NULL. If we end up supporting that option, we can
818
7
    // consider adding a check for it here.
819
7
    // C++11 [basic.stc.dynamic.allocation]p3.
820
7
    if (FD) {
821
7
      QualType Ty = FD->getType();
822
7
      if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
823
7
        if (!ProtoType->isNothrow())
824
3
          if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
825
3
            State = State->assume(*dSymVal, true);
826
7
    }
827
7
  }
828
6.41k
829
6.41k
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
830
6.41k
831
6.41k
  SVal Result = symVal;
832
6.41k
833
6.41k
  if (CNE->isArray()) {
834
138
    // FIXME: allocating an array requires simulating the constructors.
835
138
    // For now, just return a symbolicated region.
836
138
    if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) {
837
133
      QualType ObjTy = CNE->getType()->getPointeeType();
838
133
      const ElementRegion *EleReg =
839
133
          getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
840
133
      Result = loc::MemRegionVal(EleReg);
841
133
    }
842
138
    State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
843
138
    Bldr.generateNode(CNE, Pred, State);
844
138
    return;
845
138
  }
846
6.27k
847
6.27k
  // FIXME: Once we have proper support for CXXConstructExprs inside
848
6.27k
  // CXXNewExpr, we need to make sure that the constructed object is not
849
6.27k
  // immediately invalidated here. (The placement call should happen before
850
6.27k
  // the constructor call anyway.)
851
6.27k
  if (FD && FD->isReservedGlobalPlacementOperator()) {
852
5.65k
    // Non-array placement new should always return the placement location.
853
5.65k
    SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
854
5.65k
    Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
855
5.65k
                                  CNE->getPlacementArg(0)->getType());
856
5.65k
  }
857
6.27k
858
6.27k
  // Bind the address of the object, then check to see if we cached out.
859
6.27k
  State = State->BindExpr(CNE, LCtx, Result);
860
6.27k
  ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
861
6.27k
  if (!NewN)
862
0
    return;
863
6.27k
864
6.27k
  // If the type is not a record, we won't have a CXXConstructExpr as an
865
6.27k
  // initializer. Copy the value over.
866
6.27k
  if (const Expr *Init = CNE->getInitializer()) {
867
5.97k
    if (!isa<CXXConstructExpr>(Init)) {
868
2.85k
      assert(Bldr.getResults().size() == 1);
869
2.85k
      Bldr.takeNodes(NewN);
870
2.85k
      evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
871
2.85k
               /*FirstInit=*/IsStandardGlobalOpNewFunction);
872
2.85k
    }
873
5.97k
  }
874
6.27k
}
875
876
void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
877
392
                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
878
392
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
879
392
  ProgramStateRef state = Pred->getState();
880
392
  Bldr.generateNode(CDE, Pred, state);
881
392
}
882
883
void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
884
                                   ExplodedNode *Pred,
885
0
                                   ExplodedNodeSet &Dst) {
886
0
  const VarDecl *VD = CS->getExceptionDecl();
887
0
  if (!VD) {
888
0
    Dst.Add(Pred);
889
0
    return;
890
0
  }
891
0
892
0
  const LocationContext *LCtx = Pred->getLocationContext();
893
0
  SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
894
0
                                        currBldrCtx->blockCount());
895
0
  ProgramStateRef state = Pred->getState();
896
0
  state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
897
0
898
0
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
899
0
  Bldr.generateNode(CS, Pred, state);
900
0
}
901
902
void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
903
26.8k
                                    ExplodedNodeSet &Dst) {
904
26.8k
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
905
26.8k
906
26.8k
  // Get the this object region from StoreManager.
907
26.8k
  const LocationContext *LCtx = Pred->getLocationContext();
908
26.8k
  const MemRegion *R =
909
26.8k
    svalBuilder.getRegionManager().getCXXThisRegion(
910
26.8k
                                  getContext().getCanonicalType(TE->getType()),
911
26.8k
                                                    LCtx);
912
26.8k
913
26.8k
  ProgramStateRef state = Pred->getState();
914
26.8k
  SVal V = state->getSVal(loc::MemRegionVal(R));
915
26.8k
  Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
916
26.8k
}
917
918
void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
919
191
                                 ExplodedNodeSet &Dst) {
920
191
  const LocationContext *LocCtxt = Pred->getLocationContext();
921
191
922
191
  // Get the region of the lambda itself.
923
191
  const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
924
191
      LE, LocCtxt);
925
191
  SVal V = loc::MemRegionVal(R);
926
191
927
191
  ProgramStateRef State = Pred->getState();
928
191
929
191
  // If we created a new MemRegion for the lambda, we should explicitly bind
930
191
  // the captures.
931
191
  CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
932
191
  for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
933
191
                                               e = LE->capture_init_end();
934
392
       i != e; 
++i, ++CurField201
) {
935
201
    FieldDecl *FieldForCapture = *CurField;
936
201
    SVal FieldLoc = State->getLValue(FieldForCapture, V);
937
201
938
201
    SVal InitVal;
939
201
    if (!FieldForCapture->hasCapturedVLAType()) {
940
199
      Expr *InitExpr = *i;
941
199
      assert(InitExpr && "Capture missing initialization expression");
942
199
      InitVal = State->getSVal(InitExpr, LocCtxt);
943
199
    } else {
944
2
      // The field stores the length of a captured variable-length array.
945
2
      // These captures don't have initialization expressions; instead we
946
2
      // get the length from the VLAType size expression.
947
2
      Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
948
2
      InitVal = State->getSVal(SizeExpr, LocCtxt);
949
2
    }
950
201
951
201
    State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
952
201
  }
953
191
954
191
  // Decay the Loc into an RValue, because there might be a
955
191
  // MaterializeTemporaryExpr node above this one which expects the bound value
956
191
  // to be an RValue.
957
191
  SVal LambdaRVal = State->getSVal(R);
958
191
959
191
  ExplodedNodeSet Tmp;
960
191
  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
961
191
  // FIXME: is this the right program point kind?
962
191
  Bldr.generateNode(LE, Pred,
963
191
                    State->BindExpr(LE, LocCtxt, LambdaRVal),
964
191
                    nullptr, ProgramPoint::PostLValueKind);
965
191
966
191
  // FIXME: Move all post/pre visits to ::Visit().
967
191
  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
968
191
}