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/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                                           ExplodedNodeSet &Dst) {
29   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
30   const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
31   ProgramStateRef state = Pred->getState();
32   const LocationContext *LCtx = Pred->getLocationContext();
33 
34   state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
35   Bldr.generateNode(ME, Pred, state);
36 }
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                                     const CallEvent &Call) {
42   SVal ThisVal;
43   bool AlwaysReturnsLValue;
44   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
45     assert(Ctor->getDecl()->isTrivial());
46     assert(Ctor->getDecl()->isCopyOrMoveConstructor());
47     ThisVal = Ctor->getCXXThisVal();
48     AlwaysReturnsLValue = false;
49   } else {
50     assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
51     assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
52            OO_Equal);
53     ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
54     AlwaysReturnsLValue = true;
55   }
56 
57   const LocationContext *LCtx = Pred->getLocationContext();
58 
59   ExplodedNodeSet Dst;
60   Bldr.takeNodes(Pred);
61 
62   SVal V = Call.getArgSVal(0);
63 
64   // If the value being copied is not unknown, load from its location to get
65   // an aggregate rvalue.
66   if (Optional<Loc> L = V.getAs<Loc>())
67     V = Pred->getState()->getSVal(*L);
68   else
69     assert(V.isUnknownOrUndef());
70 
71   const Expr *CallExpr = Call.getOriginExpr();
72   evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
73 
74   PostStmt PS(CallExpr, LCtx);
75   for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
76        I != E; ++I) {
77     ProgramStateRef State = (*I)->getState();
78     if (AlwaysReturnsLValue)
79       State = State->BindExpr(CallExpr, LCtx, ThisVal);
80     else
81       State = bindReturnValue(Call, LCtx, State);
82     Bldr.generateNode(PS, State, *I);
83   }
84 }
85 
86 
87 /// Returns a region representing the first element of a (possibly
88 /// multi-dimensional) array, for the purposes of element construction or
89 /// destruction.
90 ///
91 /// On return, \p Ty will be set to the base type of the array.
92 ///
93 /// If the type is not an array type at all, the original value is returned.
94 /// Otherwise the "IsArray" flag is set.
95 static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
96                                   QualType &Ty, bool &IsArray) {
97   SValBuilder &SVB = State->getStateManager().getSValBuilder();
98   ASTContext &Ctx = SVB.getContext();
99 
100   while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
101     Ty = AT->getElementType();
102     LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
103     IsArray = true;
104   }
105 
106   return LValue;
107 }
108 
109 
110 const MemRegion *
111 ExprEngine::getRegionForConstructedObject(const CXXConstructExpr *CE,
112                                           ExplodedNode *Pred,
113                                           EvalCallOptions &CallOpts) {
114   const LocationContext *LCtx = Pred->getLocationContext();
115   ProgramStateRef State = Pred->getState();
116 
117   // See if we're constructing an existing region by looking at the
118   // current construction context.
119   const NodeBuilderContext &CurrBldrCtx = getBuilderContext();
120   const CFGBlock *B = CurrBldrCtx.getBlock();
121   const CFGElement &E = (*B)[currStmtIdx];
122   if (auto CC = E.getAs<CFGConstructor>()) {
123     if (const Stmt *TriggerStmt = CC->getTriggerStmt()) {
124       if (const CXXNewExpr *CNE = dyn_cast<CXXNewExpr>(TriggerStmt)) {
125         if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
126           // TODO: Detect when the allocator returns a null pointer.
127           // Constructor shall not be called in this case.
128           if (const SubRegion *MR = dyn_cast_or_null<SubRegion>(
129                   getCXXNewAllocatorValue(State, CNE, LCtx).getAsRegion())) {
130             if (CNE->isArray()) {
131               // TODO: In fact, we need to call the constructor for every
132               // allocated element, not just the first one!
133               CallOpts.IsArrayConstructorOrDestructor = true;
134               return getStoreManager().GetElementZeroRegion(
135                   MR, CNE->getType()->getPointeeType());
136             }
137             return MR;
138           }
139         }
140       } else if (auto *DS = dyn_cast<DeclStmt>(TriggerStmt)) {
141         if (const auto *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) {
142           if (Var->getInit() && Var->getInit()->IgnoreImplicit() == CE) {
143             SVal LValue = State->getLValue(Var, LCtx);
144             QualType Ty = Var->getType();
145             LValue = makeZeroElementRegion(
146                 State, LValue, Ty, CallOpts.IsArrayConstructorOrDestructor);
147             return LValue.getAsRegion();
148           }
149         }
150       }
151       // TODO: Consider other directly initialized elements.
152     } else if (const CXXCtorInitializer *Init = CC->getTriggerInit()) {
153       assert(Init->isAnyMemberInitializer());
154       const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
155       Loc ThisPtr =
156       getSValBuilder().getCXXThis(CurCtor, LCtx->getCurrentStackFrame());
157       SVal ThisVal = State->getSVal(ThisPtr);
158 
159       const ValueDecl *Field;
160       SVal FieldVal;
161       if (Init->isIndirectMemberInitializer()) {
162         Field = Init->getIndirectMember();
163         FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
164       } else {
165         Field = Init->getMember();
166         FieldVal = State->getLValue(Init->getMember(), ThisVal);
167       }
168 
169       QualType Ty = Field->getType();
170       FieldVal = makeZeroElementRegion(State, FieldVal, Ty,
171                                        CallOpts.IsArrayConstructorOrDestructor);
172       return FieldVal.getAsRegion();
173     }
174 
175     // FIXME: This will eventually need to handle new-expressions as well.
176     // Don't forget to update the pre-constructor initialization code in
177     // ExprEngine::VisitCXXConstructExpr.
178   }
179   // If we couldn't find an existing region to construct into, assume we're
180   // constructing a temporary. Notify the caller of our failure.
181   CallOpts.IsConstructorWithImproperlyModeledTargetRegion = true;
182   MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
183   return MRMgr.getCXXTempObjectRegion(CE, LCtx);
184 }
185 
186 const CXXConstructExpr *
187 ExprEngine::findDirectConstructorForCurrentCFGElement() {
188   // Go backward in the CFG to see if the previous element (ignoring
189   // destructors) was a CXXConstructExpr. If so, that constructor
190   // was constructed directly into an existing region.
191   // This process is essentially the inverse of that performed in
192   // findElementDirectlyInitializedByCurrentConstructor().
193   if (currStmtIdx == 0)
194     return nullptr;
195 
196   const CFGBlock *B = getBuilderContext().getBlock();
197 
198   unsigned int PreviousStmtIdx = currStmtIdx - 1;
199   CFGElement Previous = (*B)[PreviousStmtIdx];
200 
201   while (Previous.getAs<CFGImplicitDtor>() && PreviousStmtIdx > 0) {
202     --PreviousStmtIdx;
203     Previous = (*B)[PreviousStmtIdx];
204   }
205 
206   if (Optional<CFGStmt> PrevStmtElem = Previous.getAs<CFGStmt>()) {
207     if (auto *CtorExpr = dyn_cast<CXXConstructExpr>(PrevStmtElem->getStmt())) {
208       return CtorExpr;
209     }
210   }
211 
212   return nullptr;
213 }
214 
215 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
216                                        ExplodedNode *Pred,
217                                        ExplodedNodeSet &destNodes) {
218   const LocationContext *LCtx = Pred->getLocationContext();
219   ProgramStateRef State = Pred->getState();
220 
221   const MemRegion *Target = nullptr;
222 
223   // FIXME: Handle arrays, which run the same constructor for every element.
224   // For now, we just run the first constructor (which should still invalidate
225   // the entire array).
226 
227   EvalCallOptions CallOpts;
228 
229   switch (CE->getConstructionKind()) {
230   case CXXConstructExpr::CK_Complete: {
231     Target = getRegionForConstructedObject(CE, Pred, CallOpts);
232     break;
233   }
234   case CXXConstructExpr::CK_VirtualBase:
235     // Make sure we are not calling virtual base class initializers twice.
236     // Only the most-derived object should initialize virtual base classes.
237     if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) {
238       const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer);
239       if (OuterCtor) {
240         switch (OuterCtor->getConstructionKind()) {
241         case CXXConstructExpr::CK_NonVirtualBase:
242         case CXXConstructExpr::CK_VirtualBase:
243           // Bail out!
244           destNodes.Add(Pred);
245           return;
246         case CXXConstructExpr::CK_Complete:
247         case CXXConstructExpr::CK_Delegating:
248           break;
249         }
250       }
251     }
252     // FALLTHROUGH
253   case CXXConstructExpr::CK_NonVirtualBase:
254     // In C++17, classes with non-virtual bases may be aggregates, so they would
255     // be initialized as aggregates without a constructor call, so we may have
256     // a base class constructed directly into an initializer list without
257     // having the derived-class constructor call on the previous stack frame.
258     // Initializer lists may be nested into more initializer lists that
259     // correspond to surrounding aggregate initializations.
260     // FIXME: For now this code essentially bails out. We need to find the
261     // correct target region and set it.
262     // FIXME: Instead of relying on the ParentMap, we should have the
263     // trigger-statement (InitListExpr in this case) passed down from CFG or
264     // otherwise always available during construction.
265     if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) {
266       MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
267       Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
268       CallOpts.IsConstructorWithImproperlyModeledTargetRegion = true;
269       break;
270     }
271     // FALLTHROUGH
272   case CXXConstructExpr::CK_Delegating: {
273     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
274     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
275                                               LCtx->getCurrentStackFrame());
276     SVal ThisVal = State->getSVal(ThisPtr);
277 
278     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
279       Target = ThisVal.getAsRegion();
280     } else {
281       // Cast to the base type.
282       bool IsVirtual =
283         (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
284       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
285                                                          IsVirtual);
286       Target = BaseVal.getAsRegion();
287     }
288     break;
289   }
290   }
291 
292   CallEventManager &CEMgr = getStateManager().getCallEventManager();
293   CallEventRef<CXXConstructorCall> Call =
294     CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
295 
296   ExplodedNodeSet DstPreVisit;
297   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
298 
299   ExplodedNodeSet PreInitialized;
300   {
301     StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
302     if (CE->requiresZeroInitialization()) {
303       // Type of the zero doesn't matter.
304       SVal ZeroVal = svalBuilder.makeZeroVal(getContext().CharTy);
305 
306       for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
307                                      E = DstPreVisit.end();
308            I != E; ++I) {
309         ProgramStateRef State = (*I)->getState();
310         // FIXME: Once we properly handle constructors in new-expressions, we'll
311         // need to invalidate the region before setting a default value, to make
312         // sure there aren't any lingering bindings around. This probably needs
313         // to happen regardless of whether or not the object is zero-initialized
314         // to handle random fields of a placement-initialized object picking up
315         // old bindings. We might only want to do it when we need to, though.
316         // FIXME: This isn't actually correct for arrays -- we need to zero-
317         // initialize the entire array, not just the first element -- but our
318         // handling of arrays everywhere else is weak as well, so this shouldn't
319         // actually make things worse. Placement new makes this tricky as well,
320         // since it's then possible to be initializing one part of a multi-
321         // dimensional array.
322         State = State->bindDefault(loc::MemRegionVal(Target), ZeroVal, LCtx);
323         Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
324                           ProgramPoint::PreStmtKind);
325       }
326     }
327   }
328 
329   ExplodedNodeSet DstPreCall;
330   getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
331                                             *Call, *this);
332 
333   ExplodedNodeSet DstEvaluated;
334   StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
335 
336   if (CE->getConstructor()->isTrivial() &&
337       CE->getConstructor()->isCopyOrMoveConstructor() &&
338       !CallOpts.IsArrayConstructorOrDestructor) {
339     // FIXME: Handle other kinds of trivial constructors as well.
340     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
341          I != E; ++I)
342       performTrivialCopy(Bldr, *I, *Call);
343 
344   } else {
345     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
346          I != E; ++I)
347       defaultEvalCall(Bldr, *I, *Call, CallOpts);
348   }
349 
350   // If the CFG was contructed without elements for temporary destructors
351   // and the just-called constructor created a temporary object then
352   // stop exploration if the temporary object has a noreturn constructor.
353   // This can lose coverage because the destructor, if it were present
354   // in the CFG, would be called at the end of the full expression or
355   // later (for life-time extended temporaries) -- but avoids infeasible
356   // paths when no-return temporary destructors are used for assertions.
357   const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
358   if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
359     const MemRegion *Target = Call->getCXXThisVal().getAsRegion();
360     if (Target && isa<CXXTempObjectRegion>(Target) &&
361         Call->getDecl()->getParent()->isAnyDestructorNoReturn()) {
362 
363       // If we've inlined the constructor, then DstEvaluated would be empty.
364       // In this case we still want a sink, which could be implemented
365       // in processCallExit. But we don't have that implemented at the moment,
366       // so if you hit this assertion, see if you can avoid inlining
367       // the respective constructor when analyzer-config cfg-temporary-dtors
368       // is set to false.
369       // Otherwise there's nothing wrong with inlining such constructor.
370       assert(!DstEvaluated.empty() &&
371              "We should not have inlined this constructor!");
372 
373       for (ExplodedNode *N : DstEvaluated) {
374         Bldr.generateSink(CE, N, N->getState());
375       }
376 
377       // There is no need to run the PostCall and PostStmt checker
378       // callbacks because we just generated sinks on all nodes in th
379       // frontier.
380       return;
381     }
382   }
383 
384   ExplodedNodeSet DstPostCall;
385   getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
386                                              *Call, *this);
387   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
388 }
389 
390 void ExprEngine::VisitCXXDestructor(QualType ObjectType,
391                                     const MemRegion *Dest,
392                                     const Stmt *S,
393                                     bool IsBaseDtor,
394                                     ExplodedNode *Pred,
395                                     ExplodedNodeSet &Dst) {
396   const LocationContext *LCtx = Pred->getLocationContext();
397   ProgramStateRef State = Pred->getState();
398 
399   // FIXME: We need to run the same destructor on every element of the array.
400   // This workaround will just run the first destructor (which will still
401   // invalidate the entire array).
402   SVal DestVal = UnknownVal();
403   if (Dest)
404     DestVal = loc::MemRegionVal(Dest);
405 
406   EvalCallOptions CallOpts;
407   DestVal = makeZeroElementRegion(State, DestVal, ObjectType,
408                                   CallOpts.IsArrayConstructorOrDestructor);
409 
410   Dest = DestVal.getAsRegion();
411 
412   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
413   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
414   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
415 
416   CallEventManager &CEMgr = getStateManager().getCallEventManager();
417   CallEventRef<CXXDestructorCall> Call =
418     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
419 
420   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
421                                 Call->getSourceRange().getBegin(),
422                                 "Error evaluating destructor");
423 
424   ExplodedNodeSet DstPreCall;
425   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
426                                             *Call, *this);
427 
428   ExplodedNodeSet DstInvalidated;
429   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
430   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
431        I != E; ++I)
432     defaultEvalCall(Bldr, *I, *Call, CallOpts);
433 
434   ExplodedNodeSet DstPostCall;
435   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
436                                              *Call, *this);
437 }
438 
439 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
440                                           ExplodedNode *Pred,
441                                           ExplodedNodeSet &Dst) {
442   ProgramStateRef State = Pred->getState();
443   const LocationContext *LCtx = Pred->getLocationContext();
444   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
445                                 CNE->getStartLoc(),
446                                 "Error evaluating New Allocator Call");
447   CallEventManager &CEMgr = getStateManager().getCallEventManager();
448   CallEventRef<CXXAllocatorCall> Call =
449     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
450 
451   ExplodedNodeSet DstPreCall;
452   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
453                                             *Call, *this);
454 
455   ExplodedNodeSet DstPostCall;
456   StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
457   for (auto I : DstPreCall) {
458     // FIXME: Provide evalCall for checkers?
459     defaultEvalCall(CallBldr, I, *Call);
460   }
461   // If the call is inlined, DstPostCall will be empty and we bail out now.
462 
463   // Store return value of operator new() for future use, until the actual
464   // CXXNewExpr gets processed.
465   ExplodedNodeSet DstPostValue;
466   StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
467   for (auto I : DstPostCall) {
468     // FIXME: Because CNE serves as the "call site" for the allocator (due to
469     // lack of a better expression in the AST), the conjured return value symbol
470     // is going to be of the same type (C++ object pointer type). Technically
471     // this is not correct because the operator new's prototype always says that
472     // it returns a 'void *'. So we should change the type of the symbol,
473     // and then evaluate the cast over the symbolic pointer from 'void *' to
474     // the object pointer type. But without changing the symbol's type it
475     // is breaking too much to evaluate the no-op symbolic cast over it, so we
476     // skip it for now.
477     ProgramStateRef State = I->getState();
478     SVal RetVal = State->getSVal(CNE, LCtx);
479 
480     // If this allocation function is not declared as non-throwing, failures
481     // /must/ be signalled by exceptions, and thus the return value will never
482     // be NULL. -fno-exceptions does not influence this semantics.
483     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
484     // where new can return NULL. If we end up supporting that option, we can
485     // consider adding a check for it here.
486     // C++11 [basic.stc.dynamic.allocation]p3.
487     if (const FunctionDecl *FD = CNE->getOperatorNew()) {
488       QualType Ty = FD->getType();
489       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
490         if (!ProtoType->isNothrow(getContext()))
491           State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
492     }
493 
494     ValueBldr.generateNode(CNE, I,
495                            setCXXNewAllocatorValue(State, CNE, LCtx, RetVal));
496   }
497 
498   ExplodedNodeSet DstPostPostCallCallback;
499   getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
500                                              DstPostValue, *Call, *this);
501   for (auto I : DstPostPostCallCallback) {
502     getCheckerManager().runCheckersForNewAllocator(
503         CNE, getCXXNewAllocatorValue(I->getState(), CNE, LCtx), Dst, I, *this);
504   }
505 }
506 
507 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
508                                    ExplodedNodeSet &Dst) {
509   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
510   // Also, we need to decide how allocators actually work -- they're not
511   // really part of the CXXNewExpr because they happen BEFORE the
512   // CXXConstructExpr subexpression. See PR12014 for some discussion.
513 
514   unsigned blockCount = currBldrCtx->blockCount();
515   const LocationContext *LCtx = Pred->getLocationContext();
516   SVal symVal = UnknownVal();
517   FunctionDecl *FD = CNE->getOperatorNew();
518 
519   bool IsStandardGlobalOpNewFunction =
520       FD->isReplaceableGlobalAllocationFunction();
521 
522   ProgramStateRef State = Pred->getState();
523 
524   // Retrieve the stored operator new() return value.
525   if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
526     symVal = getCXXNewAllocatorValue(State, CNE, LCtx);
527     State = clearCXXNewAllocatorValue(State, CNE, LCtx);
528   }
529 
530   // We assume all standard global 'operator new' functions allocate memory in
531   // heap. We realize this is an approximation that might not correctly model
532   // a custom global allocator.
533   if (symVal.isUnknown()) {
534     if (IsStandardGlobalOpNewFunction)
535       symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
536     else
537       symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
538                                             blockCount);
539   }
540 
541   CallEventManager &CEMgr = getStateManager().getCallEventManager();
542   CallEventRef<CXXAllocatorCall> Call =
543     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
544 
545   if (!AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
546     // Invalidate placement args.
547     // FIXME: Once we figure out how we want allocators to work,
548     // we should be using the usual pre-/(default-)eval-/post-call checks here.
549     State = Call->invalidateRegions(blockCount);
550     if (!State)
551       return;
552 
553     // If this allocation function is not declared as non-throwing, failures
554     // /must/ be signalled by exceptions, and thus the return value will never
555     // be NULL. -fno-exceptions does not influence this semantics.
556     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
557     // where new can return NULL. If we end up supporting that option, we can
558     // consider adding a check for it here.
559     // C++11 [basic.stc.dynamic.allocation]p3.
560     if (FD) {
561       QualType Ty = FD->getType();
562       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
563         if (!ProtoType->isNothrow(getContext()))
564           if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
565             State = State->assume(*dSymVal, true);
566     }
567   }
568 
569   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
570 
571   SVal Result = symVal;
572 
573   if (CNE->isArray()) {
574     // FIXME: allocating an array requires simulating the constructors.
575     // For now, just return a symbolicated region.
576     if (const SubRegion *NewReg =
577             dyn_cast_or_null<SubRegion>(symVal.getAsRegion())) {
578       QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
579       const ElementRegion *EleReg =
580           getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
581       Result = loc::MemRegionVal(EleReg);
582     }
583     State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
584     Bldr.generateNode(CNE, Pred, State);
585     return;
586   }
587 
588   // FIXME: Once we have proper support for CXXConstructExprs inside
589   // CXXNewExpr, we need to make sure that the constructed object is not
590   // immediately invalidated here. (The placement call should happen before
591   // the constructor call anyway.)
592   if (FD && FD->isReservedGlobalPlacementOperator()) {
593     // Non-array placement new should always return the placement location.
594     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
595     Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
596                                   CNE->getPlacementArg(0)->getType());
597   }
598 
599   // Bind the address of the object, then check to see if we cached out.
600   State = State->BindExpr(CNE, LCtx, Result);
601   ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
602   if (!NewN)
603     return;
604 
605   // If the type is not a record, we won't have a CXXConstructExpr as an
606   // initializer. Copy the value over.
607   if (const Expr *Init = CNE->getInitializer()) {
608     if (!isa<CXXConstructExpr>(Init)) {
609       assert(Bldr.getResults().size() == 1);
610       Bldr.takeNodes(NewN);
611       evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
612                /*FirstInit=*/IsStandardGlobalOpNewFunction);
613     }
614   }
615 }
616 
617 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
618                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
619   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
620   ProgramStateRef state = Pred->getState();
621   Bldr.generateNode(CDE, Pred, state);
622 }
623 
624 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
625                                    ExplodedNode *Pred,
626                                    ExplodedNodeSet &Dst) {
627   const VarDecl *VD = CS->getExceptionDecl();
628   if (!VD) {
629     Dst.Add(Pred);
630     return;
631   }
632 
633   const LocationContext *LCtx = Pred->getLocationContext();
634   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
635                                         currBldrCtx->blockCount());
636   ProgramStateRef state = Pred->getState();
637   state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
638 
639   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
640   Bldr.generateNode(CS, Pred, state);
641 }
642 
643 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
644                                     ExplodedNodeSet &Dst) {
645   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
646 
647   // Get the this object region from StoreManager.
648   const LocationContext *LCtx = Pred->getLocationContext();
649   const MemRegion *R =
650     svalBuilder.getRegionManager().getCXXThisRegion(
651                                   getContext().getCanonicalType(TE->getType()),
652                                                     LCtx);
653 
654   ProgramStateRef state = Pred->getState();
655   SVal V = state->getSVal(loc::MemRegionVal(R));
656   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
657 }
658 
659 void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
660                                  ExplodedNodeSet &Dst) {
661   const LocationContext *LocCtxt = Pred->getLocationContext();
662 
663   // Get the region of the lambda itself.
664   const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
665       LE, LocCtxt);
666   SVal V = loc::MemRegionVal(R);
667 
668   ProgramStateRef State = Pred->getState();
669 
670   // If we created a new MemRegion for the lambda, we should explicitly bind
671   // the captures.
672   CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
673   for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
674                                                e = LE->capture_init_end();
675        i != e; ++i, ++CurField) {
676     FieldDecl *FieldForCapture = *CurField;
677     SVal FieldLoc = State->getLValue(FieldForCapture, V);
678 
679     SVal InitVal;
680     if (!FieldForCapture->hasCapturedVLAType()) {
681       Expr *InitExpr = *i;
682       assert(InitExpr && "Capture missing initialization expression");
683       InitVal = State->getSVal(InitExpr, LocCtxt);
684     } else {
685       // The field stores the length of a captured variable-length array.
686       // These captures don't have initialization expressions; instead we
687       // get the length from the VLAType size expression.
688       Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
689       InitVal = State->getSVal(SizeExpr, LocCtxt);
690     }
691 
692     State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
693   }
694 
695   // Decay the Loc into an RValue, because there might be a
696   // MaterializeTemporaryExpr node above this one which expects the bound value
697   // to be an RValue.
698   SVal LambdaRVal = State->getSVal(R);
699 
700   ExplodedNodeSet Tmp;
701   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
702   // FIXME: is this the right program point kind?
703   Bldr.generateNode(LE, Pred,
704                     State->BindExpr(LE, LocCtxt, LambdaRVal),
705                     nullptr, ProgramPoint::PostLValueKind);
706 
707   // FIXME: Move all post/pre visits to ::Visit().
708   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
709 }
710