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