110e25031STed Kremenek //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
210e25031STed Kremenek //
310e25031STed Kremenek //                     The LLVM Compiler Infrastructure
410e25031STed Kremenek //
510e25031STed Kremenek // This file is distributed under the University of Illinois Open Source
610e25031STed Kremenek // License. See LICENSE.TXT for details.
710e25031STed Kremenek //
810e25031STed Kremenek //===----------------------------------------------------------------------===//
910e25031STed Kremenek //
1010e25031STed Kremenek //  This file defines the C++ expression evaluation engine.
1110e25031STed Kremenek //
1210e25031STed Kremenek //===----------------------------------------------------------------------===//
1310e25031STed Kremenek 
1410e25031STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
1510e25031STed Kremenek #include "clang/AST/DeclCXX.h"
168fdb59f9STed Kremenek #include "clang/AST/StmtCXX.h"
1717a8757aSJordan Rose #include "clang/Basic/PrettyStackTrace.h"
183a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/CheckerManager.h"
193a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
203a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
2110e25031STed Kremenek 
2210e25031STed Kremenek using namespace clang;
2310e25031STed Kremenek using namespace ento;
2410e25031STed Kremenek 
2510e25031STed Kremenek void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
2610e25031STed Kremenek                                           ExplodedNode *Pred,
2710e25031STed Kremenek                                           ExplodedNodeSet &Dst) {
28d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
292a14c695STed Kremenek   const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
3049b1e38eSTed Kremenek   ProgramStateRef state = Pred->getState();
31632e3b7eSTed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
3210e25031STed Kremenek 
33861a1740SJordan Rose   state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
345772f82dSJordan Rose   Bldr.generateNode(ME, Pred, state);
3510e25031STed Kremenek }
3610e25031STed Kremenek 
373d7b7f52SJordan Rose // FIXME: This is the sort of code that should eventually live in a Core
383d7b7f52SJordan Rose // checker rather than as a special case in ExprEngine.
3988bb563cSJordan Rose void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
403d7b7f52SJordan Rose                                     const CallEvent &Call) {
413d7b7f52SJordan Rose   SVal ThisVal;
423d7b7f52SJordan Rose   bool AlwaysReturnsLValue;
433d7b7f52SJordan Rose   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
443d7b7f52SJordan Rose     assert(Ctor->getDecl()->isTrivial());
453d7b7f52SJordan Rose     assert(Ctor->getDecl()->isCopyOrMoveConstructor());
463d7b7f52SJordan Rose     ThisVal = Ctor->getCXXThisVal();
473d7b7f52SJordan Rose     AlwaysReturnsLValue = false;
483d7b7f52SJordan Rose   } else {
493d7b7f52SJordan Rose     assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
503d7b7f52SJordan Rose     assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
513d7b7f52SJordan Rose            OO_Equal);
523d7b7f52SJordan Rose     ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
533d7b7f52SJordan Rose     AlwaysReturnsLValue = true;
543d7b7f52SJordan Rose   }
5588bb563cSJordan Rose 
5688bb563cSJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
5788bb563cSJordan Rose 
5888bb563cSJordan Rose   ExplodedNodeSet Dst;
5988bb563cSJordan Rose   Bldr.takeNodes(Pred);
6088bb563cSJordan Rose 
6188bb563cSJordan Rose   SVal V = Call.getArgSVal(0);
6288bb563cSJordan Rose 
633d7b7f52SJordan Rose   // If the value being copied is not unknown, load from its location to get
643d7b7f52SJordan Rose   // an aggregate rvalue.
6505785d16SDavid Blaikie   if (Optional<Loc> L = V.getAs<Loc>())
6688bb563cSJordan Rose     V = Pred->getState()->getSVal(*L);
673d7b7f52SJordan Rose   else
683d7b7f52SJordan Rose     assert(V.isUnknown());
6988bb563cSJordan Rose 
703d7b7f52SJordan Rose   const Expr *CallExpr = Call.getOriginExpr();
713d7b7f52SJordan Rose   evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
7288bb563cSJordan Rose 
733d7b7f52SJordan Rose   PostStmt PS(CallExpr, LCtx);
7488bb563cSJordan Rose   for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
7588bb563cSJordan Rose        I != E; ++I) {
7688bb563cSJordan Rose     ProgramStateRef State = (*I)->getState();
773d7b7f52SJordan Rose     if (AlwaysReturnsLValue)
783d7b7f52SJordan Rose       State = State->BindExpr(CallExpr, LCtx, ThisVal);
793d7b7f52SJordan Rose     else
8088bb563cSJordan Rose       State = bindReturnValue(Call, LCtx, State);
8188bb563cSJordan Rose     Bldr.generateNode(PS, State, *I);
8288bb563cSJordan Rose   }
8388bb563cSJordan Rose }
8488bb563cSJordan Rose 
85bc74eb1cSJordan Rose 
86bc74eb1cSJordan Rose /// Returns a region representing the first element of a (possibly
87bc74eb1cSJordan Rose /// multi-dimensional) array.
88bc74eb1cSJordan Rose ///
89bc74eb1cSJordan Rose /// On return, \p Ty will be set to the base type of the array.
90bc74eb1cSJordan Rose ///
91bc74eb1cSJordan Rose /// If the type is not an array type at all, the original value is returned.
92bc74eb1cSJordan Rose static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
93bc74eb1cSJordan Rose                                   QualType &Ty) {
94bc74eb1cSJordan Rose   SValBuilder &SVB = State->getStateManager().getSValBuilder();
95bc74eb1cSJordan Rose   ASTContext &Ctx = SVB.getContext();
96bc74eb1cSJordan Rose 
97bc74eb1cSJordan Rose   while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
98bc74eb1cSJordan Rose     Ty = AT->getElementType();
99bc74eb1cSJordan Rose     LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
100bc74eb1cSJordan Rose   }
101bc74eb1cSJordan Rose 
102bc74eb1cSJordan Rose   return LValue;
103bc74eb1cSJordan Rose }
104bc74eb1cSJordan Rose 
10517f41608SJordan Rose 
106*412c0af2SDevin Coughlin const MemRegion *
107*412c0af2SDevin Coughlin ExprEngine::getRegionForConstructedObject(const CXXConstructExpr *CE,
108*412c0af2SDevin Coughlin                                           ExplodedNode *Pred) {
109b970505dSJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
11005375eb4SJordan Rose   ProgramStateRef State = Pred->getState();
11105375eb4SJordan Rose 
11205375eb4SJordan Rose   // See if we're constructing an existing region by looking at the next
11305375eb4SJordan Rose   // element in the CFG.
1148a5a094eSJordan Rose 
115*412c0af2SDevin Coughlin   if (auto Elem = findElementDirectlyInitializedByCurrentConstructor()) {
116*412c0af2SDevin Coughlin     if (Optional<CFGStmt> StmtElem = Elem->getAs<CFGStmt>()) {
117*412c0af2SDevin Coughlin       auto *DS = cast<DeclStmt>(StmtElem->getStmt());
118*412c0af2SDevin Coughlin       if (const auto *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) {
119bcd88973SJordan Rose         if (Var->getInit() && Var->getInit()->IgnoreImplicit() == CE) {
120bc74eb1cSJordan Rose           SVal LValue = State->getLValue(Var, LCtx);
12120edae87SJordan Rose           QualType Ty = Var->getType();
122bc74eb1cSJordan Rose           LValue = makeZeroElementRegion(State, LValue, Ty);
12317f41608SJordan Rose           return LValue.getAsRegion();
12420edae87SJordan Rose         }
12520edae87SJordan Rose       }
126*412c0af2SDevin Coughlin     } else if (Optional<CFGInitializer> InitElem = Elem->getAs<CFGInitializer>()) {
12700be69abSDavid Blaikie       const CXXCtorInitializer *Init = InitElem->getInitializer();
12854529a34SJordan Rose       assert(Init->isAnyMemberInitializer());
12954529a34SJordan Rose       const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
130*412c0af2SDevin Coughlin       Loc ThisPtr =
131*412c0af2SDevin Coughlin       getSValBuilder().getCXXThis(CurCtor, LCtx->getCurrentStackFrame());
13254529a34SJordan Rose       SVal ThisVal = State->getSVal(ThisPtr);
13354529a34SJordan Rose 
134bc74eb1cSJordan Rose       const ValueDecl *Field;
135bc74eb1cSJordan Rose       SVal FieldVal;
13654529a34SJordan Rose       if (Init->isIndirectMemberInitializer()) {
137bc74eb1cSJordan Rose         Field = Init->getIndirectMember();
138bc74eb1cSJordan Rose         FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
13954529a34SJordan Rose       } else {
140bc74eb1cSJordan Rose         Field = Init->getMember();
141bc74eb1cSJordan Rose         FieldVal = State->getLValue(Init->getMember(), ThisVal);
14254529a34SJordan Rose       }
143bc74eb1cSJordan Rose 
144bc74eb1cSJordan Rose       QualType Ty = Field->getType();
145bc74eb1cSJordan Rose       FieldVal = makeZeroElementRegion(State, FieldVal, Ty);
14617f41608SJordan Rose       return FieldVal.getAsRegion();
14754529a34SJordan Rose     }
14854529a34SJordan Rose 
14905375eb4SJordan Rose     // FIXME: This will eventually need to handle new-expressions as well.
15017f41608SJordan Rose     // Don't forget to update the pre-constructor initialization code in
15117f41608SJordan Rose     // ExprEngine::VisitCXXConstructExpr.
15205375eb4SJordan Rose   }
153c9318304SJordan Rose   // If we couldn't find an existing region to construct into, assume we're
154c9318304SJordan Rose   // constructing a temporary.
155*412c0af2SDevin Coughlin   MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
15617f41608SJordan Rose   return MRMgr.getCXXTempObjectRegion(CE, LCtx);
157c9318304SJordan Rose }
15805375eb4SJordan Rose 
159*412c0af2SDevin Coughlin /// Returns true if the initializer for \Elem can be a direct
160*412c0af2SDevin Coughlin /// constructor.
161*412c0af2SDevin Coughlin static bool canHaveDirectConstructor(CFGElement Elem){
162*412c0af2SDevin Coughlin   // DeclStmts and CXXCtorInitializers for fields can be directly constructed.
163*412c0af2SDevin Coughlin 
164*412c0af2SDevin Coughlin   if (Optional<CFGStmt> StmtElem = Elem.getAs<CFGStmt>()) {
165*412c0af2SDevin Coughlin     if (isa<DeclStmt>(StmtElem->getStmt())) {
166*412c0af2SDevin Coughlin       return true;
167*412c0af2SDevin Coughlin     }
168*412c0af2SDevin Coughlin   }
169*412c0af2SDevin Coughlin 
170*412c0af2SDevin Coughlin   if (Elem.getKind() == CFGElement::Initializer) {
171*412c0af2SDevin Coughlin     return true;
172*412c0af2SDevin Coughlin   }
173*412c0af2SDevin Coughlin 
174*412c0af2SDevin Coughlin   return false;
175*412c0af2SDevin Coughlin }
176*412c0af2SDevin Coughlin 
177*412c0af2SDevin Coughlin Optional<CFGElement>
178*412c0af2SDevin Coughlin ExprEngine::findElementDirectlyInitializedByCurrentConstructor() {
179*412c0af2SDevin Coughlin   const NodeBuilderContext &CurrBldrCtx = getBuilderContext();
180*412c0af2SDevin Coughlin   // See if we're constructing an existing region by looking at the next
181*412c0af2SDevin Coughlin   // element in the CFG.
182*412c0af2SDevin Coughlin   const CFGBlock *B = CurrBldrCtx.getBlock();
183*412c0af2SDevin Coughlin   assert(isa<CXXConstructExpr>(((*B)[currStmtIdx]).castAs<CFGStmt>().getStmt()));
184*412c0af2SDevin Coughlin   unsigned int NextStmtIdx = currStmtIdx + 1;
185*412c0af2SDevin Coughlin   if (NextStmtIdx >= B->size())
186*412c0af2SDevin Coughlin     return None;
187*412c0af2SDevin Coughlin 
188*412c0af2SDevin Coughlin   CFGElement Next = (*B)[NextStmtIdx];
189*412c0af2SDevin Coughlin 
190*412c0af2SDevin Coughlin   // Is this a destructor? If so, we might be in the middle of an assignment
191*412c0af2SDevin Coughlin   // to a local or member: look ahead one more element to see what we find.
192*412c0af2SDevin Coughlin   while (Next.getAs<CFGImplicitDtor>() && NextStmtIdx + 1 < B->size()) {
193*412c0af2SDevin Coughlin     ++NextStmtIdx;
194*412c0af2SDevin Coughlin     Next = (*B)[NextStmtIdx];
195*412c0af2SDevin Coughlin   }
196*412c0af2SDevin Coughlin 
197*412c0af2SDevin Coughlin   if (canHaveDirectConstructor(Next))
198*412c0af2SDevin Coughlin     return Next;
199*412c0af2SDevin Coughlin 
200*412c0af2SDevin Coughlin   return None;
201*412c0af2SDevin Coughlin }
202*412c0af2SDevin Coughlin 
203*412c0af2SDevin Coughlin const CXXConstructExpr *
204*412c0af2SDevin Coughlin ExprEngine::findDirectConstructorForCurrentCFGElement() {
205*412c0af2SDevin Coughlin   // Go backward in the CFG to see if the previous element (ignoring
206*412c0af2SDevin Coughlin   // destructors) was a CXXConstructExpr. If so, that constructor
207*412c0af2SDevin Coughlin   // was constructed directly into an existing region.
208*412c0af2SDevin Coughlin   // This process is essentially the inverse of that performed in
209*412c0af2SDevin Coughlin   // findElementDirectlyInitializedByCurrentConstructor().
210*412c0af2SDevin Coughlin   if (currStmtIdx == 0)
211*412c0af2SDevin Coughlin     return nullptr;
212*412c0af2SDevin Coughlin 
213*412c0af2SDevin Coughlin   const CFGBlock *B = getBuilderContext().getBlock();
214*412c0af2SDevin Coughlin   assert(canHaveDirectConstructor((*B)[currStmtIdx]));
215*412c0af2SDevin Coughlin 
216*412c0af2SDevin Coughlin   unsigned int PreviousStmtIdx = currStmtIdx - 1;
217*412c0af2SDevin Coughlin   CFGElement Previous = (*B)[PreviousStmtIdx];
218*412c0af2SDevin Coughlin 
219*412c0af2SDevin Coughlin   while (Previous.getAs<CFGImplicitDtor>() && PreviousStmtIdx > 0) {
220*412c0af2SDevin Coughlin     --PreviousStmtIdx;
221*412c0af2SDevin Coughlin     Previous = (*B)[PreviousStmtIdx];
222*412c0af2SDevin Coughlin   }
223*412c0af2SDevin Coughlin 
224*412c0af2SDevin Coughlin   if (Optional<CFGStmt> PrevStmtElem = Previous.getAs<CFGStmt>()) {
225*412c0af2SDevin Coughlin     if (auto *CtorExpr = dyn_cast<CXXConstructExpr>(PrevStmtElem->getStmt())) {
226*412c0af2SDevin Coughlin       return CtorExpr;
227*412c0af2SDevin Coughlin     }
228*412c0af2SDevin Coughlin   }
229*412c0af2SDevin Coughlin 
230*412c0af2SDevin Coughlin   return nullptr;
231*412c0af2SDevin Coughlin }
232*412c0af2SDevin Coughlin 
23317f41608SJordan Rose void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
23417f41608SJordan Rose                                        ExplodedNode *Pred,
23517f41608SJordan Rose                                        ExplodedNodeSet &destNodes) {
23617f41608SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
23717f41608SJordan Rose   ProgramStateRef State = Pred->getState();
23817f41608SJordan Rose 
2390dbb783cSCraig Topper   const MemRegion *Target = nullptr;
24017f41608SJordan Rose 
24117f41608SJordan Rose   // FIXME: Handle arrays, which run the same constructor for every element.
24217f41608SJordan Rose   // For now, we just run the first constructor (which should still invalidate
24317f41608SJordan Rose   // the entire array).
24417f41608SJordan Rose 
24517f41608SJordan Rose   switch (CE->getConstructionKind()) {
24617f41608SJordan Rose   case CXXConstructExpr::CK_Complete: {
247*412c0af2SDevin Coughlin     Target = getRegionForConstructedObject(CE, Pred);
248b970505dSJordan Rose     break;
249b970505dSJordan Rose   }
250b3b976f0SJordan Rose   case CXXConstructExpr::CK_VirtualBase:
251b3b976f0SJordan Rose     // Make sure we are not calling virtual base class initializers twice.
252b3b976f0SJordan Rose     // Only the most-derived object should initialize virtual base classes.
253b3b976f0SJordan Rose     if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) {
254b3b976f0SJordan Rose       const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer);
255b3b976f0SJordan Rose       if (OuterCtor) {
256b3b976f0SJordan Rose         switch (OuterCtor->getConstructionKind()) {
257b970505dSJordan Rose         case CXXConstructExpr::CK_NonVirtualBase:
258b970505dSJordan Rose         case CXXConstructExpr::CK_VirtualBase:
259b3b976f0SJordan Rose           // Bail out!
260b3b976f0SJordan Rose           destNodes.Add(Pred);
261b3b976f0SJordan Rose           return;
262b3b976f0SJordan Rose         case CXXConstructExpr::CK_Complete:
263b3b976f0SJordan Rose         case CXXConstructExpr::CK_Delegating:
264b3b976f0SJordan Rose           break;
265b3b976f0SJordan Rose         }
266b3b976f0SJordan Rose       }
267b3b976f0SJordan Rose     }
268b3b976f0SJordan Rose     // FALLTHROUGH
269b3b976f0SJordan Rose   case CXXConstructExpr::CK_NonVirtualBase:
270b970505dSJordan Rose   case CXXConstructExpr::CK_Delegating: {
271b970505dSJordan Rose     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
272b970505dSJordan Rose     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
273b970505dSJordan Rose                                               LCtx->getCurrentStackFrame());
27405375eb4SJordan Rose     SVal ThisVal = State->getSVal(ThisPtr);
275b970505dSJordan Rose 
276b970505dSJordan Rose     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
277b970505dSJordan Rose       Target = ThisVal.getAsRegion();
278b970505dSJordan Rose     } else {
279b970505dSJordan Rose       // Cast to the base type.
280599f85abSJordan Rose       bool IsVirtual =
281599f85abSJordan Rose         (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
282599f85abSJordan Rose       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
283599f85abSJordan Rose                                                          IsVirtual);
28420edae87SJordan Rose       Target = BaseVal.getAsRegion();
285b970505dSJordan Rose     }
286b970505dSJordan Rose     break;
287b970505dSJordan Rose   }
288b970505dSJordan Rose   }
289b970505dSJordan Rose 
290fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
291fcd016e5SJordan Rose   CallEventRef<CXXConstructorCall> Call =
292fcd016e5SJordan Rose     CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
29310e25031STed Kremenek 
294f3c12ac3SJordan Rose   ExplodedNodeSet DstPreVisit;
295f3c12ac3SJordan Rose   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
296b8e28654SJordan Rose 
297b8e28654SJordan Rose   ExplodedNodeSet PreInitialized;
298b8e28654SJordan Rose   {
299b8e28654SJordan Rose     StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
300b8e28654SJordan Rose     if (CE->requiresZeroInitialization()) {
301b8e28654SJordan Rose       // Type of the zero doesn't matter.
302b8e28654SJordan Rose       SVal ZeroVal = svalBuilder.makeZeroVal(getContext().CharTy);
303b8e28654SJordan Rose 
304b8e28654SJordan Rose       for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
305b8e28654SJordan Rose                                      E = DstPreVisit.end();
306b8e28654SJordan Rose            I != E; ++I) {
307b8e28654SJordan Rose         ProgramStateRef State = (*I)->getState();
308b8e28654SJordan Rose         // FIXME: Once we properly handle constructors in new-expressions, we'll
309b8e28654SJordan Rose         // need to invalidate the region before setting a default value, to make
310b8e28654SJordan Rose         // sure there aren't any lingering bindings around. This probably needs
311b8e28654SJordan Rose         // to happen regardless of whether or not the object is zero-initialized
312b8e28654SJordan Rose         // to handle random fields of a placement-initialized object picking up
313b8e28654SJordan Rose         // old bindings. We might only want to do it when we need to, though.
314b8e28654SJordan Rose         // FIXME: This isn't actually correct for arrays -- we need to zero-
315b8e28654SJordan Rose         // initialize the entire array, not just the first element -- but our
316b8e28654SJordan Rose         // handling of arrays everywhere else is weak as well, so this shouldn't
317b8e28654SJordan Rose         // actually make things worse. Placement new makes this tricky as well,
318b8e28654SJordan Rose         // since it's then possible to be initializing one part of a multi-
319b8e28654SJordan Rose         // dimensional array.
320b8e28654SJordan Rose         State = State->bindDefault(loc::MemRegionVal(Target), ZeroVal);
3210dbb783cSCraig Topper         Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
3220dbb783cSCraig Topper                           ProgramPoint::PreStmtKind);
323b8e28654SJordan Rose       }
324b8e28654SJordan Rose     }
325b8e28654SJordan Rose   }
326b8e28654SJordan Rose 
327afe7c2c2SJordan Rose   ExplodedNodeSet DstPreCall;
328b8e28654SJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
329fcd016e5SJordan Rose                                             *Call, *this);
33010e25031STed Kremenek 
33188bb563cSJordan Rose   ExplodedNodeSet DstEvaluated;
33288bb563cSJordan Rose   StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
33388bb563cSJordan Rose 
334e83cb092SJordan Rose   bool IsArray = isa<ElementRegion>(Target);
335e83cb092SJordan Rose   if (CE->getConstructor()->isTrivial() &&
336e83cb092SJordan Rose       CE->getConstructor()->isCopyOrMoveConstructor() &&
337e83cb092SJordan Rose       !IsArray) {
338e83cb092SJordan Rose     // FIXME: Handle other kinds of trivial constructors as well.
339e83cb092SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
34088bb563cSJordan Rose          I != E; ++I)
34188bb563cSJordan Rose       performTrivialCopy(Bldr, *I, *Call);
34288bb563cSJordan Rose 
34388bb563cSJordan Rose   } else {
344afe7c2c2SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
345f3c12ac3SJordan Rose          I != E; ++I)
346fcd016e5SJordan Rose       defaultEvalCall(Bldr, *I, *Call);
34788bb563cSJordan Rose   }
34810e25031STed Kremenek 
349afe7c2c2SJordan Rose   ExplodedNodeSet DstPostCall;
35088bb563cSJordan Rose   getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
351fcd016e5SJordan Rose                                              *Call, *this);
352afe7c2c2SJordan Rose   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
35310e25031STed Kremenek }
35410e25031STed Kremenek 
355b970505dSJordan Rose void ExprEngine::VisitCXXDestructor(QualType ObjectType,
35610e25031STed Kremenek                                     const MemRegion *Dest,
35710e25031STed Kremenek                                     const Stmt *S,
3582bc9674bSJordan Rose                                     bool IsBaseDtor,
35910e25031STed Kremenek                                     ExplodedNode *Pred,
36010e25031STed Kremenek                                     ExplodedNodeSet &Dst) {
361fcd016e5SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
362fcd016e5SJordan Rose   ProgramStateRef State = Pred->getState();
363fcd016e5SJordan Rose 
36420edae87SJordan Rose   // FIXME: We need to run the same destructor on every element of the array.
36520edae87SJordan Rose   // This workaround will just run the first destructor (which will still
36620edae87SJordan Rose   // invalidate the entire array).
3671ccc43d5SJordan Rose   SVal DestVal = UnknownVal();
3681ccc43d5SJordan Rose   if (Dest)
3691ccc43d5SJordan Rose     DestVal = loc::MemRegionVal(Dest);
370bc74eb1cSJordan Rose   DestVal = makeZeroElementRegion(State, DestVal, ObjectType);
371bc74eb1cSJordan Rose   Dest = DestVal.getAsRegion();
37220edae87SJordan Rose 
373b970505dSJordan Rose   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
374b970505dSJordan Rose   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
375b970505dSJordan Rose   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
376b970505dSJordan Rose 
377fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
378fcd016e5SJordan Rose   CallEventRef<CXXDestructorCall> Call =
3792bc9674bSJordan Rose     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
380142adc49STed Kremenek 
38117a8757aSJordan Rose   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
38217a8757aSJordan Rose                                 Call->getSourceRange().getBegin(),
38317a8757aSJordan Rose                                 "Error evaluating destructor");
38417a8757aSJordan Rose 
3854ee71b8aSJordan Rose   ExplodedNodeSet DstPreCall;
3864ee71b8aSJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
387fcd016e5SJordan Rose                                             *Call, *this);
38810e25031STed Kremenek 
3894ee71b8aSJordan Rose   ExplodedNodeSet DstInvalidated;
390d94854a4STed Kremenek   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
3914ee71b8aSJordan Rose   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
3924ee71b8aSJordan Rose        I != E; ++I)
393fcd016e5SJordan Rose     defaultEvalCall(Bldr, *I, *Call);
3944ee71b8aSJordan Rose 
3954ee71b8aSJordan Rose   ExplodedNodeSet DstPostCall;
3964ee71b8aSJordan Rose   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
397fcd016e5SJordan Rose                                              *Call, *this);
39810e25031STed Kremenek }
39910e25031STed Kremenek 
4008b808d64SJordan Rose void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
4018b808d64SJordan Rose                                           ExplodedNode *Pred,
4028b808d64SJordan Rose                                           ExplodedNodeSet &Dst) {
4038b808d64SJordan Rose   ProgramStateRef State = Pred->getState();
4048b808d64SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
4058b808d64SJordan Rose   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
4068b808d64SJordan Rose                                 CNE->getStartLoc(),
4078b808d64SJordan Rose                                 "Error evaluating New Allocator Call");
4088b808d64SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
4098b808d64SJordan Rose   CallEventRef<CXXAllocatorCall> Call =
4108b808d64SJordan Rose     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
4118b808d64SJordan Rose 
4128b808d64SJordan Rose   ExplodedNodeSet DstPreCall;
4138b808d64SJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
4148b808d64SJordan Rose                                             *Call, *this);
4158b808d64SJordan Rose 
4168b808d64SJordan Rose   ExplodedNodeSet DstInvalidated;
4178b808d64SJordan Rose   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
4188b808d64SJordan Rose   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
4198b808d64SJordan Rose        I != E; ++I)
4208b808d64SJordan Rose     defaultEvalCall(Bldr, *I, *Call);
4218b808d64SJordan Rose   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
4228b808d64SJordan Rose                                              *Call, *this);
4238b808d64SJordan Rose }
4248b808d64SJordan Rose 
4258b808d64SJordan Rose 
42610e25031STed Kremenek void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
42710e25031STed Kremenek                                    ExplodedNodeSet &Dst) {
428a4ee064cSJordan Rose   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
429a4ee064cSJordan Rose   // Also, we need to decide how allocators actually work -- they're not
430a4ee064cSJordan Rose   // really part of the CXXNewExpr because they happen BEFORE the
431a4ee064cSJordan Rose   // CXXConstructExpr subexpression. See PR12014 for some discussion.
43210e25031STed Kremenek 
433d94854a4STed Kremenek   unsigned blockCount = currBldrCtx->blockCount();
434d519cae8STed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
4358b662704SAnton Yartsev   DefinedOrUnknownSVal symVal = UnknownVal();
4368b662704SAnton Yartsev   FunctionDecl *FD = CNE->getOperatorNew();
43710e25031STed Kremenek 
4388b662704SAnton Yartsev   bool IsStandardGlobalOpNewFunction = false;
4398b662704SAnton Yartsev   if (FD && !isa<CXXMethodDecl>(FD) && !FD->isVariadic()) {
4408b662704SAnton Yartsev     if (FD->getNumParams() == 2) {
4418b662704SAnton Yartsev       QualType T = FD->getParamDecl(1)->getType();
4428b662704SAnton Yartsev       if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
4438b662704SAnton Yartsev         // NoThrow placement new behaves as a standard new.
4448b662704SAnton Yartsev         IsStandardGlobalOpNewFunction = II->getName().equals("nothrow_t");
4458b662704SAnton Yartsev     }
4468b662704SAnton Yartsev     else
4478b662704SAnton Yartsev       // Placement forms are considered non-standard.
4488b662704SAnton Yartsev       IsStandardGlobalOpNewFunction = (FD->getNumParams() == 1);
4498b662704SAnton Yartsev   }
4508b662704SAnton Yartsev 
4518b662704SAnton Yartsev   // We assume all standard global 'operator new' functions allocate memory in
4528b662704SAnton Yartsev   // heap. We realize this is an approximation that might not correctly model
4538b662704SAnton Yartsev   // a custom global allocator.
4548b662704SAnton Yartsev   if (IsStandardGlobalOpNewFunction)
4558b662704SAnton Yartsev     symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
4568b662704SAnton Yartsev   else
4570dbb783cSCraig Topper     symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
4588b662704SAnton Yartsev                                           blockCount);
4598b662704SAnton Yartsev 
4608b662704SAnton Yartsev   ProgramStateRef State = Pred->getState();
461fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
462fcd016e5SJordan Rose   CallEventRef<CXXAllocatorCall> Call =
463fcd016e5SJordan Rose     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
464fcd016e5SJordan Rose 
465a4ee064cSJordan Rose   // Invalidate placement args.
466fcd016e5SJordan Rose   // FIXME: Once we figure out how we want allocators to work,
467fcd016e5SJordan Rose   // we should be using the usual pre-/(default-)eval-/post-call checks here.
468fcd016e5SJordan Rose   State = Call->invalidateRegions(blockCount);
469b8cb8359SJordan Rose   if (!State)
470b8cb8359SJordan Rose     return;
471a4ee064cSJordan Rose 
472fce1b03eSPavel Labath   // If this allocation function is not declared as non-throwing, failures
473fce1b03eSPavel Labath   // /must/ be signalled by exceptions, and thus the return value will never be
474fce1b03eSPavel Labath   // NULL. -fno-exceptions does not influence this semantics.
475fce1b03eSPavel Labath   // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
476fce1b03eSPavel Labath   // where new can return NULL. If we end up supporting that option, we can
477fce1b03eSPavel Labath   // consider adding a check for it here.
4783957fd58SJordan Rose   // C++11 [basic.stc.dynamic.allocation]p3.
479fce1b03eSPavel Labath   if (FD) {
4803957fd58SJordan Rose     QualType Ty = FD->getType();
4813957fd58SJordan Rose     if (const FunctionProtoType *ProtoType = Ty->getAs<FunctionProtoType>())
4823957fd58SJordan Rose       if (!ProtoType->isNothrow(getContext()))
4833957fd58SJordan Rose         State = State->assume(symVal, true);
4843957fd58SJordan Rose   }
4853957fd58SJordan Rose 
486b8cb8359SJordan Rose   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
487b8cb8359SJordan Rose 
48810e25031STed Kremenek   if (CNE->isArray()) {
48910e25031STed Kremenek     // FIXME: allocating an array requires simulating the constructors.
49010e25031STed Kremenek     // For now, just return a symbolicated region.
4912fdacbc5SDavid Blaikie     const MemRegion *NewReg = symVal.castAs<loc::MemRegionVal>().getRegion();
492a4ee064cSJordan Rose     QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
493a4ee064cSJordan Rose     const ElementRegion *EleReg =
494a4ee064cSJordan Rose       getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
49544320367SJordan Rose     State = State->BindExpr(CNE, Pred->getLocationContext(),
496632e3b7eSTed Kremenek                             loc::MemRegionVal(EleReg));
49744320367SJordan Rose     Bldr.generateNode(CNE, Pred, State);
49810e25031STed Kremenek     return;
49910e25031STed Kremenek   }
50010e25031STed Kremenek 
501a4ee064cSJordan Rose   // FIXME: Once we have proper support for CXXConstructExprs inside
502a4ee064cSJordan Rose   // CXXNewExpr, we need to make sure that the constructed object is not
503a4ee064cSJordan Rose   // immediately invalidated here. (The placement call should happen before
504a4ee064cSJordan Rose   // the constructor call anyway.)
505b8cb8359SJordan Rose   SVal Result = symVal;
50644320367SJordan Rose   if (FD && FD->isReservedGlobalPlacementOperator()) {
50744320367SJordan Rose     // Non-array placement new should always return the placement location.
50844320367SJordan Rose     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
509b8cb8359SJordan Rose     Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
510aaf83184SJordan Rose                                   CNE->getPlacementArg(0)->getType());
51144320367SJordan Rose   }
51244320367SJordan Rose 
513b8cb8359SJordan Rose   // Bind the address of the object, then check to see if we cached out.
514b8cb8359SJordan Rose   State = State->BindExpr(CNE, LCtx, Result);
5158f6b4b04SJordan Rose   ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
5168f6b4b04SJordan Rose   if (!NewN)
5178f6b4b04SJordan Rose     return;
5183503cb35SJordan Rose 
5195089f3b3SJordan Rose   // If the type is not a record, we won't have a CXXConstructExpr as an
5205089f3b3SJordan Rose   // initializer. Copy the value over.
5215089f3b3SJordan Rose   if (const Expr *Init = CNE->getInitializer()) {
5225089f3b3SJordan Rose     if (!isa<CXXConstructExpr>(Init)) {
5233503cb35SJordan Rose       assert(Bldr.getResults().size() == 1);
5248f6b4b04SJordan Rose       Bldr.takeNodes(NewN);
525b8cb8359SJordan Rose       evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
526b8cb8359SJordan Rose                /*FirstInit=*/IsStandardGlobalOpNewFunction);
5273503cb35SJordan Rose     }
5283503cb35SJordan Rose   }
52910e25031STed Kremenek }
53010e25031STed Kremenek 
53110e25031STed Kremenek void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
53210e25031STed Kremenek                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
533d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
53464aea652SErik Verbruggen   ProgramStateRef state = Pred->getState();
53564aea652SErik Verbruggen   Bldr.generateNode(CDE, Pred, state);
53610e25031STed Kremenek }
53710e25031STed Kremenek 
5388fdb59f9STed Kremenek void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
5398fdb59f9STed Kremenek                                    ExplodedNode *Pred,
5408fdb59f9STed Kremenek                                    ExplodedNodeSet &Dst) {
5418fdb59f9STed Kremenek   const VarDecl *VD = CS->getExceptionDecl();
542b1279b5cSTed Kremenek   if (!VD) {
543b1279b5cSTed Kremenek     Dst.Add(Pred);
544b1279b5cSTed Kremenek     return;
545b1279b5cSTed Kremenek   }
546b1279b5cSTed Kremenek 
5478fdb59f9STed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
548d227833cSTed Kremenek   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
549d94854a4STed Kremenek                                         currBldrCtx->blockCount());
5508fdb59f9STed Kremenek   ProgramStateRef state = Pred->getState();
5518fdb59f9STed Kremenek   state = state->bindLoc(state->getLValue(VD, LCtx), V);
5528fdb59f9STed Kremenek 
553d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
5548fdb59f9STed Kremenek   Bldr.generateNode(CS, Pred, state);
5558fdb59f9STed Kremenek }
5568fdb59f9STed Kremenek 
55710e25031STed Kremenek void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
55810e25031STed Kremenek                                     ExplodedNodeSet &Dst) {
559d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
560e594034fSAnna Zaks 
56110e25031STed Kremenek   // Get the this object region from StoreManager.
562632e3b7eSTed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
56310e25031STed Kremenek   const MemRegion *R =
56410e25031STed Kremenek     svalBuilder.getRegionManager().getCXXThisRegion(
56510e25031STed Kremenek                                   getContext().getCanonicalType(TE->getType()),
566632e3b7eSTed Kremenek                                                     LCtx);
56710e25031STed Kremenek 
56849b1e38eSTed Kremenek   ProgramStateRef state = Pred->getState();
56910e25031STed Kremenek   SVal V = state->getSVal(loc::MemRegionVal(R));
570632e3b7eSTed Kremenek   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
57110e25031STed Kremenek }
57215843343SGabor Horvath 
57315843343SGabor Horvath void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
57415843343SGabor Horvath                                  ExplodedNodeSet &Dst) {
57515843343SGabor Horvath   const LocationContext *LocCtxt = Pred->getLocationContext();
57615843343SGabor Horvath 
57715843343SGabor Horvath   // Get the region of the lambda itself.
57815843343SGabor Horvath   const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
57915843343SGabor Horvath       LE, LocCtxt);
58015843343SGabor Horvath   SVal V = loc::MemRegionVal(R);
58115843343SGabor Horvath 
58215843343SGabor Horvath   ProgramStateRef State = Pred->getState();
58315843343SGabor Horvath 
58415843343SGabor Horvath   // If we created a new MemRegion for the lambda, we should explicitly bind
58515843343SGabor Horvath   // the captures.
58615843343SGabor Horvath   CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
58715843343SGabor Horvath   for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
58815843343SGabor Horvath                                                e = LE->capture_init_end();
58915843343SGabor Horvath        i != e; ++i, ++CurField) {
5907bdca8b2SDevin Coughlin     FieldDecl *FieldForCapture = *CurField;
5917bdca8b2SDevin Coughlin     SVal FieldLoc = State->getLValue(FieldForCapture, V);
5927bdca8b2SDevin Coughlin 
5937bdca8b2SDevin Coughlin     SVal InitVal;
5947bdca8b2SDevin Coughlin     if (!FieldForCapture->hasCapturedVLAType()) {
5957bdca8b2SDevin Coughlin       Expr *InitExpr = *i;
5967bdca8b2SDevin Coughlin       assert(InitExpr && "Capture missing initialization expression");
5977bdca8b2SDevin Coughlin       InitVal = State->getSVal(InitExpr, LocCtxt);
5987bdca8b2SDevin Coughlin     } else {
5997bdca8b2SDevin Coughlin       // The field stores the length of a captured variable-length array.
6007bdca8b2SDevin Coughlin       // These captures don't have initialization expressions; instead we
6017bdca8b2SDevin Coughlin       // get the length from the VLAType size expression.
6027bdca8b2SDevin Coughlin       Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
6037bdca8b2SDevin Coughlin       InitVal = State->getSVal(SizeExpr, LocCtxt);
6047bdca8b2SDevin Coughlin     }
6057bdca8b2SDevin Coughlin 
6067bdca8b2SDevin Coughlin     State = State->bindLoc(FieldLoc, InitVal);
60715843343SGabor Horvath   }
60815843343SGabor Horvath 
60915843343SGabor Horvath   // Decay the Loc into an RValue, because there might be a
61015843343SGabor Horvath   // MaterializeTemporaryExpr node above this one which expects the bound value
61115843343SGabor Horvath   // to be an RValue.
61215843343SGabor Horvath   SVal LambdaRVal = State->getSVal(R);
61315843343SGabor Horvath 
61415843343SGabor Horvath   ExplodedNodeSet Tmp;
61515843343SGabor Horvath   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
61615843343SGabor Horvath   // FIXME: is this the right program point kind?
61715843343SGabor Horvath   Bldr.generateNode(LE, Pred,
61815843343SGabor Horvath                     State->BindExpr(LE, LocCtxt, LambdaRVal),
61915843343SGabor Horvath                     nullptr, ProgramPoint::PostLValueKind);
62015843343SGabor Horvath 
62115843343SGabor Horvath   // FIXME: Move all post/pre visits to ::Visit().
62215843343SGabor Horvath   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
62315843343SGabor Horvath }
624