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