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