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"
154068481bSArtem Dergachev #include "clang/Analysis/ConstructionContext.h"
1610e25031STed Kremenek #include "clang/AST/DeclCXX.h"
178fdb59f9STed Kremenek #include "clang/AST/StmtCXX.h"
18e8ba3ec4SArtem Dergachev #include "clang/AST/ParentMap.h"
1917a8757aSJordan Rose #include "clang/Basic/PrettyStackTrace.h"
203a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/CheckerManager.h"
213a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
223a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
2310e25031STed Kremenek 
2410e25031STed Kremenek using namespace clang;
2510e25031STed Kremenek using namespace ento;
2610e25031STed Kremenek 
2710e25031STed Kremenek void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
2810e25031STed Kremenek                                           ExplodedNode *Pred,
2910e25031STed Kremenek                                           ExplodedNodeSet &Dst) {
30d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
312a14c695STed Kremenek   const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
3249b1e38eSTed Kremenek   ProgramStateRef state = Pred->getState();
33632e3b7eSTed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
3410e25031STed Kremenek 
35861a1740SJordan Rose   state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
365772f82dSJordan Rose   Bldr.generateNode(ME, Pred, state);
3710e25031STed Kremenek }
3810e25031STed Kremenek 
393d7b7f52SJordan Rose // FIXME: This is the sort of code that should eventually live in a Core
403d7b7f52SJordan Rose // checker rather than as a special case in ExprEngine.
4188bb563cSJordan Rose void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
423d7b7f52SJordan Rose                                     const CallEvent &Call) {
433d7b7f52SJordan Rose   SVal ThisVal;
443d7b7f52SJordan Rose   bool AlwaysReturnsLValue;
454449e7f0SArtem Dergachev   const CXXRecordDecl *ThisRD = nullptr;
463d7b7f52SJordan Rose   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
473d7b7f52SJordan Rose     assert(Ctor->getDecl()->isTrivial());
483d7b7f52SJordan Rose     assert(Ctor->getDecl()->isCopyOrMoveConstructor());
493d7b7f52SJordan Rose     ThisVal = Ctor->getCXXThisVal();
504449e7f0SArtem Dergachev     ThisRD = Ctor->getDecl()->getParent();
513d7b7f52SJordan Rose     AlwaysReturnsLValue = false;
523d7b7f52SJordan Rose   } else {
533d7b7f52SJordan Rose     assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
543d7b7f52SJordan Rose     assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
553d7b7f52SJordan Rose            OO_Equal);
563d7b7f52SJordan Rose     ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
574449e7f0SArtem Dergachev     ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
583d7b7f52SJordan Rose     AlwaysReturnsLValue = true;
593d7b7f52SJordan Rose   }
6088bb563cSJordan Rose 
614449e7f0SArtem Dergachev   assert(ThisRD);
624449e7f0SArtem Dergachev   if (ThisRD->isEmpty()) {
634449e7f0SArtem Dergachev     // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal
644449e7f0SArtem Dergachev     // and bind it and RegionStore would think that the actual value
654449e7f0SArtem Dergachev     // in this region at this offset is unknown.
664449e7f0SArtem Dergachev     return;
674449e7f0SArtem Dergachev   }
684449e7f0SArtem Dergachev 
6988bb563cSJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
7088bb563cSJordan Rose 
7188bb563cSJordan Rose   ExplodedNodeSet Dst;
7288bb563cSJordan Rose   Bldr.takeNodes(Pred);
7388bb563cSJordan Rose 
7488bb563cSJordan Rose   SVal V = Call.getArgSVal(0);
7588bb563cSJordan Rose 
763d7b7f52SJordan Rose   // If the value being copied is not unknown, load from its location to get
773d7b7f52SJordan Rose   // an aggregate rvalue.
7805785d16SDavid Blaikie   if (Optional<Loc> L = V.getAs<Loc>())
7988bb563cSJordan Rose     V = Pred->getState()->getSVal(*L);
803d7b7f52SJordan Rose   else
8175f9d3acSArtem Dergachev     assert(V.isUnknownOrUndef());
8288bb563cSJordan Rose 
833d7b7f52SJordan Rose   const Expr *CallExpr = Call.getOriginExpr();
843d7b7f52SJordan Rose   evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
8588bb563cSJordan Rose 
863d7b7f52SJordan Rose   PostStmt PS(CallExpr, LCtx);
8788bb563cSJordan Rose   for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
8888bb563cSJordan Rose        I != E; ++I) {
8988bb563cSJordan Rose     ProgramStateRef State = (*I)->getState();
903d7b7f52SJordan Rose     if (AlwaysReturnsLValue)
913d7b7f52SJordan Rose       State = State->BindExpr(CallExpr, LCtx, ThisVal);
923d7b7f52SJordan Rose     else
9388bb563cSJordan Rose       State = bindReturnValue(Call, LCtx, State);
9488bb563cSJordan Rose     Bldr.generateNode(PS, State, *I);
9588bb563cSJordan Rose   }
9688bb563cSJordan Rose }
9788bb563cSJordan Rose 
98bc74eb1cSJordan Rose 
99168e29f6SArtem Dergachev SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue,
100690ab040SArtem Dergachev                                        QualType &Ty, bool &IsArray) {
101bc74eb1cSJordan Rose   SValBuilder &SVB = State->getStateManager().getSValBuilder();
102bc74eb1cSJordan Rose   ASTContext &Ctx = SVB.getContext();
103bc74eb1cSJordan Rose 
104bc74eb1cSJordan Rose   while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
105bc74eb1cSJordan Rose     Ty = AT->getElementType();
106bc74eb1cSJordan Rose     LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
107690ab040SArtem Dergachev     IsArray = true;
108bc74eb1cSJordan Rose   }
109bc74eb1cSJordan Rose 
110bc74eb1cSJordan Rose   return LValue;
111bc74eb1cSJordan Rose }
112bc74eb1cSJordan Rose 
113239452caSArtem Dergachev std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction(
114239452caSArtem Dergachev     const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
115239452caSArtem Dergachev     const ConstructionContext *CC, EvalCallOptions &CallOpts) {
11694020268SArtem Dergachev   MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
11705375eb4SJordan Rose 
118afb158c2SArtem Dergachev   // See if we're constructing an existing region by looking at the
119afb158c2SArtem Dergachev   // current construction context.
120661ab34aSArtem Dergachev   if (CC) {
1214068481bSArtem Dergachev     switch (CC->getKind()) {
1224068481bSArtem Dergachev     case ConstructionContext::SimpleVariableKind: {
1234068481bSArtem Dergachev       const auto *DSCC = cast<SimpleVariableConstructionContext>(CC);
1244068481bSArtem Dergachev       const auto *DS = DSCC->getDeclStmt();
125e231bd34SArtem Dergachev       const auto *Var = cast<VarDecl>(DS->getSingleDecl());
126bc74eb1cSJordan Rose       SVal LValue = State->getLValue(Var, LCtx);
12720edae87SJordan Rose       QualType Ty = Var->getType();
1281fe52474SArtem Dergachev       LValue =
1291fe52474SArtem Dergachev           makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor);
1301fe52474SArtem Dergachev       State =
1311fe52474SArtem Dergachev           addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, LValue);
1321fe52474SArtem Dergachev       return std::make_pair(State, LValue);
13320edae87SJordan Rose     }
134922455feSArtem Dergachev     case ConstructionContext::SimpleConstructorInitializerKind: {
1354068481bSArtem Dergachev       const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
1364068481bSArtem Dergachev       const auto *Init = ICC->getCXXCtorInitializer();
13754529a34SJordan Rose       assert(Init->isAnyMemberInitializer());
13854529a34SJordan Rose       const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
139412c0af2SDevin Coughlin       Loc ThisPtr =
140412c0af2SDevin Coughlin       getSValBuilder().getCXXThis(CurCtor, LCtx->getCurrentStackFrame());
14154529a34SJordan Rose       SVal ThisVal = State->getSVal(ThisPtr);
14254529a34SJordan Rose 
143bc74eb1cSJordan Rose       const ValueDecl *Field;
144bc74eb1cSJordan Rose       SVal FieldVal;
14554529a34SJordan Rose       if (Init->isIndirectMemberInitializer()) {
146bc74eb1cSJordan Rose         Field = Init->getIndirectMember();
147bc74eb1cSJordan Rose         FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
14854529a34SJordan Rose       } else {
149bc74eb1cSJordan Rose         Field = Init->getMember();
150bc74eb1cSJordan Rose         FieldVal = State->getLValue(Init->getMember(), ThisVal);
15154529a34SJordan Rose       }
152bc74eb1cSJordan Rose 
153bc74eb1cSJordan Rose       QualType Ty = Field->getType();
154690ab040SArtem Dergachev       FieldVal = makeZeroElementRegion(State, FieldVal, Ty,
155168e29f6SArtem Dergachev                                        CallOpts.IsArrayCtorOrDtor);
156*a84374dcSArtem Dergachev       State = addObjectUnderConstruction(State, Init, LCtx, FieldVal);
157239452caSArtem Dergachev       return std::make_pair(State, FieldVal);
15854529a34SJordan Rose     }
1594068481bSArtem Dergachev     case ConstructionContext::NewAllocatedObjectKind: {
1604068481bSArtem Dergachev       if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
1614068481bSArtem Dergachev         const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
1624068481bSArtem Dergachev         const auto *NE = NECC->getCXXNewExpr();
163f83d5479SArtem Dergachev         SVal V = *getObjectUnderConstruction(State, NE, LCtx);
164f83d5479SArtem Dergachev         if (const SubRegion *MR =
165f83d5479SArtem Dergachev                 dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
1664068481bSArtem Dergachev           if (NE->isArray()) {
1674068481bSArtem Dergachev             // TODO: In fact, we need to call the constructor for every
1684068481bSArtem Dergachev             // allocated element, not just the first one!
1694068481bSArtem Dergachev             CallOpts.IsArrayCtorOrDtor = true;
170239452caSArtem Dergachev             return std::make_pair(
171239452caSArtem Dergachev                 State, loc::MemRegionVal(getStoreManager().GetElementZeroRegion(
172239452caSArtem Dergachev                            MR, NE->getType()->getPointeeType())));
1734068481bSArtem Dergachev           }
174239452caSArtem Dergachev           return std::make_pair(State, V);
1754068481bSArtem Dergachev         }
176f83d5479SArtem Dergachev         // TODO: Detect when the allocator returns a null pointer.
177f83d5479SArtem Dergachev         // Constructor shall not be called in this case.
1784068481bSArtem Dergachev       }
1794068481bSArtem Dergachev       break;
1804068481bSArtem Dergachev     }
181239452caSArtem Dergachev     case ConstructionContext::SimpleReturnedValueKind: {
182239452caSArtem Dergachev       // The temporary is to be managed by the parent stack frame.
183239452caSArtem Dergachev       // So build it in the parent stack frame if we're not in the
184239452caSArtem Dergachev       // top frame of the analysis.
185239452caSArtem Dergachev       const StackFrameContext *SFC = LCtx->getCurrentStackFrame();
186239452caSArtem Dergachev       if (const LocationContext *CallerLCtx = SFC->getParent()) {
187239452caSArtem Dergachev         auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
188239452caSArtem Dergachev                        .getAs<CFGCXXRecordTypedCall>();
189239452caSArtem Dergachev         if (!RTC) {
190239452caSArtem Dergachev           // We were unable to find the correct construction context for the
191239452caSArtem Dergachev           // call in the parent stack frame. This is equivalent to not being
192239452caSArtem Dergachev           // able to find construction context at all.
193239452caSArtem Dergachev           break;
194239452caSArtem Dergachev         } else if (!isa<TemporaryObjectConstructionContext>(
195239452caSArtem Dergachev                        RTC->getConstructionContext())) {
196239452caSArtem Dergachev           // FIXME: The return value is constructed directly into a
197239452caSArtem Dergachev           // non-temporary due to C++17 mandatory copy elision. This is not
198239452caSArtem Dergachev           // implemented yet.
199239452caSArtem Dergachev           assert(getContext().getLangOpts().CPlusPlus17);
200239452caSArtem Dergachev           break;
201239452caSArtem Dergachev         }
202239452caSArtem Dergachev         CC = RTC->getConstructionContext();
203239452caSArtem Dergachev         LCtx = CallerLCtx;
204239452caSArtem Dergachev       } else {
205239452caSArtem Dergachev         // We are on the top frame of the analysis.
206239452caSArtem Dergachev         // TODO: What exactly happens when we are? Does the temporary object
207239452caSArtem Dergachev         // live long enough in the region store in this case? Would checkers
208239452caSArtem Dergachev         // think that this object immediately goes out of scope?
209239452caSArtem Dergachev         CallOpts.IsTemporaryCtorOrDtor = true;
210239452caSArtem Dergachev         SVal V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
211239452caSArtem Dergachev         return std::make_pair(State, V);
212239452caSArtem Dergachev       }
213239452caSArtem Dergachev 
214239452caSArtem Dergachev       // Continue as if we have a temporary with a different location context.
215239452caSArtem Dergachev       // FALLTHROUGH.
216239452caSArtem Dergachev     }
2174068481bSArtem Dergachev     case ConstructionContext::TemporaryObjectKind: {
218239452caSArtem Dergachev       const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
219239452caSArtem Dergachev       const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
220239452caSArtem Dergachev       const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
221239452caSArtem Dergachev 
222239452caSArtem Dergachev       if (!BTE) {
223239452caSArtem Dergachev         // FIXME: Lifetime extension for temporaries without destructors
224239452caSArtem Dergachev         // is not implemented yet.
225239452caSArtem Dergachev         MTE = nullptr;
226239452caSArtem Dergachev       }
227239452caSArtem Dergachev 
228239452caSArtem Dergachev       if (MTE) {
2298cd7961aSArtem Dergachev         if (const ValueDecl *VD = MTE->getExtendingDecl()) {
230643102dfSArtem Dergachev           assert(MTE->getStorageDuration() != SD_FullExpression);
231643102dfSArtem Dergachev           if (!VD->getType()->isReferenceType()) {
232643102dfSArtem Dergachev             // We're lifetime-extended by a surrounding aggregate.
233643102dfSArtem Dergachev             // Automatic destructors aren't quite working in this case
234643102dfSArtem Dergachev             // on the CFG side. We should warn the caller about that.
235310bca01SArtem Dergachev             // FIXME: Is there a better way to retrieve this information from
236310bca01SArtem Dergachev             // the MaterializeTemporaryExpr?
237310bca01SArtem Dergachev             CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true;
238310bca01SArtem Dergachev           }
2398cd7961aSArtem Dergachev         }
2408cd7961aSArtem Dergachev       }
241239452caSArtem Dergachev 
242239452caSArtem Dergachev       if (MTE && MTE->getStorageDuration() != SD_FullExpression) {
243239452caSArtem Dergachev         // If the temporary is lifetime-extended, don't save the BTE,
244239452caSArtem Dergachev         // because we don't need a temporary destructor, but an automatic
245239452caSArtem Dergachev         // destructor.
246239452caSArtem Dergachev         BTE = nullptr;
247239452caSArtem Dergachev       }
248239452caSArtem Dergachev 
249239452caSArtem Dergachev       // FIXME: Support temporaries lifetime-extended via static references.
2504068481bSArtem Dergachev       // They'd need a getCXXStaticTempObjectRegion().
251239452caSArtem Dergachev       SVal V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
252239452caSArtem Dergachev 
253239452caSArtem Dergachev       if (BTE)
254239452caSArtem Dergachev         State = addObjectUnderConstruction(State, BTE, LCtx, V);
255239452caSArtem Dergachev 
256239452caSArtem Dergachev       if (MTE)
257239452caSArtem Dergachev         State = addObjectUnderConstruction(State, MTE, LCtx, V);
258239452caSArtem Dergachev 
2594068481bSArtem Dergachev       CallOpts.IsTemporaryCtorOrDtor = true;
260239452caSArtem Dergachev       return std::make_pair(State, V);
2614068481bSArtem Dergachev     }
262317291e3SArtem Dergachev     case ConstructionContext::CXX17ElidedCopyVariableKind:
263317291e3SArtem Dergachev     case ConstructionContext::CXX17ElidedCopyReturnedValueKind:
264922455feSArtem Dergachev     case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
265317291e3SArtem Dergachev       // Not implemented yet.
266317291e3SArtem Dergachev       break;
2674068481bSArtem Dergachev     }
26805375eb4SJordan Rose   }
269c9318304SJordan Rose   // If we couldn't find an existing region to construct into, assume we're
270690ab040SArtem Dergachev   // constructing a temporary. Notify the caller of our failure.
271168e29f6SArtem Dergachev   CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
272239452caSArtem Dergachev   return std::make_pair(
273239452caSArtem Dergachev       State, loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)));
274c9318304SJordan Rose }
27505375eb4SJordan Rose 
27617f41608SJordan Rose void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
27717f41608SJordan Rose                                        ExplodedNode *Pred,
27817f41608SJordan Rose                                        ExplodedNodeSet &destNodes) {
27917f41608SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
28017f41608SJordan Rose   ProgramStateRef State = Pred->getState();
28117f41608SJordan Rose 
282f83d5479SArtem Dergachev   SVal Target = UnknownVal();
28317f41608SJordan Rose 
28417f41608SJordan Rose   // FIXME: Handle arrays, which run the same constructor for every element.
28517f41608SJordan Rose   // For now, we just run the first constructor (which should still invalidate
28617f41608SJordan Rose   // the entire array).
28717f41608SJordan Rose 
288690ab040SArtem Dergachev   EvalCallOptions CallOpts;
289661ab34aSArtem Dergachev   auto C = getCurrentCFGElement().getAs<CFGConstructor>();
2904068481bSArtem Dergachev   assert(C || getCurrentCFGElement().getAs<CFGStmt>());
291661ab34aSArtem Dergachev   const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
292661ab34aSArtem Dergachev 
29317f41608SJordan Rose   switch (CE->getConstructionKind()) {
29417f41608SJordan Rose   case CXXConstructExpr::CK_Complete: {
295239452caSArtem Dergachev     std::tie(State, Target) =
296239452caSArtem Dergachev         prepareForObjectConstruction(CE, State, LCtx, CC, CallOpts);
297b970505dSJordan Rose     break;
298b970505dSJordan Rose   }
299b3b976f0SJordan Rose   case CXXConstructExpr::CK_VirtualBase:
300b3b976f0SJordan Rose     // Make sure we are not calling virtual base class initializers twice.
301b3b976f0SJordan Rose     // Only the most-derived object should initialize virtual base classes.
302b3b976f0SJordan Rose     if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) {
303b3b976f0SJordan Rose       const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer);
304b3b976f0SJordan Rose       if (OuterCtor) {
305b3b976f0SJordan Rose         switch (OuterCtor->getConstructionKind()) {
306b970505dSJordan Rose         case CXXConstructExpr::CK_NonVirtualBase:
307b970505dSJordan Rose         case CXXConstructExpr::CK_VirtualBase:
308b3b976f0SJordan Rose           // Bail out!
309b3b976f0SJordan Rose           destNodes.Add(Pred);
310b3b976f0SJordan Rose           return;
311b3b976f0SJordan Rose         case CXXConstructExpr::CK_Complete:
312b3b976f0SJordan Rose         case CXXConstructExpr::CK_Delegating:
313b3b976f0SJordan Rose           break;
314b3b976f0SJordan Rose         }
315b3b976f0SJordan Rose       }
316b3b976f0SJordan Rose     }
317b3b976f0SJordan Rose     // FALLTHROUGH
318b3b976f0SJordan Rose   case CXXConstructExpr::CK_NonVirtualBase:
319e8ba3ec4SArtem Dergachev     // In C++17, classes with non-virtual bases may be aggregates, so they would
320e8ba3ec4SArtem Dergachev     // be initialized as aggregates without a constructor call, so we may have
321e8ba3ec4SArtem Dergachev     // a base class constructed directly into an initializer list without
322e8ba3ec4SArtem Dergachev     // having the derived-class constructor call on the previous stack frame.
323e8ba3ec4SArtem Dergachev     // Initializer lists may be nested into more initializer lists that
324e8ba3ec4SArtem Dergachev     // correspond to surrounding aggregate initializations.
325e8ba3ec4SArtem Dergachev     // FIXME: For now this code essentially bails out. We need to find the
326e8ba3ec4SArtem Dergachev     // correct target region and set it.
327e8ba3ec4SArtem Dergachev     // FIXME: Instead of relying on the ParentMap, we should have the
328e8ba3ec4SArtem Dergachev     // trigger-statement (InitListExpr in this case) passed down from CFG or
329e8ba3ec4SArtem Dergachev     // otherwise always available during construction.
330e8ba3ec4SArtem Dergachev     if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) {
331e8ba3ec4SArtem Dergachev       MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
332f83d5479SArtem Dergachev       Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(CE, LCtx));
333168e29f6SArtem Dergachev       CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
334e8ba3ec4SArtem Dergachev       break;
335e8ba3ec4SArtem Dergachev     }
336e8ba3ec4SArtem Dergachev     // FALLTHROUGH
337b970505dSJordan Rose   case CXXConstructExpr::CK_Delegating: {
338b970505dSJordan Rose     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
339b970505dSJordan Rose     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
340b970505dSJordan Rose                                               LCtx->getCurrentStackFrame());
34105375eb4SJordan Rose     SVal ThisVal = State->getSVal(ThisPtr);
342b970505dSJordan Rose 
343b970505dSJordan Rose     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
344f83d5479SArtem Dergachev       Target = ThisVal;
345b970505dSJordan Rose     } else {
346b970505dSJordan Rose       // Cast to the base type.
347599f85abSJordan Rose       bool IsVirtual =
348599f85abSJordan Rose         (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
349599f85abSJordan Rose       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
350599f85abSJordan Rose                                                          IsVirtual);
351f83d5479SArtem Dergachev       Target = BaseVal;
352b970505dSJordan Rose     }
353b970505dSJordan Rose     break;
354b970505dSJordan Rose   }
355b970505dSJordan Rose   }
356b970505dSJordan Rose 
357239452caSArtem Dergachev   if (State != Pred->getState()) {
358239452caSArtem Dergachev     static SimpleProgramPointTag T("ExprEngine",
359239452caSArtem Dergachev                                    "Prepare for object construction");
360239452caSArtem Dergachev     ExplodedNodeSet DstPrepare;
361239452caSArtem Dergachev     StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx);
362239452caSArtem Dergachev     BldrPrepare.generateNode(CE, Pred, State, &T, ProgramPoint::PreStmtKind);
363239452caSArtem Dergachev     assert(DstPrepare.size() <= 1);
364239452caSArtem Dergachev     if (DstPrepare.size() == 0)
365239452caSArtem Dergachev       return;
366239452caSArtem Dergachev     Pred = *BldrPrepare.begin();
367239452caSArtem Dergachev   }
368239452caSArtem Dergachev 
369fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
370fcd016e5SJordan Rose   CallEventRef<CXXConstructorCall> Call =
371f83d5479SArtem Dergachev     CEMgr.getCXXConstructorCall(CE, Target.getAsRegion(), State, LCtx);
37210e25031STed Kremenek 
373f3c12ac3SJordan Rose   ExplodedNodeSet DstPreVisit;
374f3c12ac3SJordan Rose   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
375b8e28654SJordan Rose 
376661ab34aSArtem Dergachev   // FIXME: Is it possible and/or useful to do this before PreStmt?
377b8e28654SJordan Rose   ExplodedNodeSet PreInitialized;
378b8e28654SJordan Rose   {
379b8e28654SJordan Rose     StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
380b8e28654SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
381b8e28654SJordan Rose                                    E = DstPreVisit.end();
382b8e28654SJordan Rose          I != E; ++I) {
383b8e28654SJordan Rose       ProgramStateRef State = (*I)->getState();
384661ab34aSArtem Dergachev       if (CE->requiresZeroInitialization()) {
385b8e28654SJordan Rose         // FIXME: Once we properly handle constructors in new-expressions, we'll
386b8e28654SJordan Rose         // need to invalidate the region before setting a default value, to make
387b8e28654SJordan Rose         // sure there aren't any lingering bindings around. This probably needs
388b8e28654SJordan Rose         // to happen regardless of whether or not the object is zero-initialized
389b8e28654SJordan Rose         // to handle random fields of a placement-initialized object picking up
390b8e28654SJordan Rose         // old bindings. We might only want to do it when we need to, though.
391b8e28654SJordan Rose         // FIXME: This isn't actually correct for arrays -- we need to zero-
392b8e28654SJordan Rose         // initialize the entire array, not just the first element -- but our
393b8e28654SJordan Rose         // handling of arrays everywhere else is weak as well, so this shouldn't
394b8e28654SJordan Rose         // actually make things worse. Placement new makes this tricky as well,
395b8e28654SJordan Rose         // since it's then possible to be initializing one part of a multi-
396b8e28654SJordan Rose         // dimensional array.
397f83d5479SArtem Dergachev         State = State->bindDefaultZero(Target, LCtx);
398661ab34aSArtem Dergachev       }
399661ab34aSArtem Dergachev 
4000dbb783cSCraig Topper       Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
4010dbb783cSCraig Topper                         ProgramPoint::PreStmtKind);
402b8e28654SJordan Rose     }
403b8e28654SJordan Rose   }
404b8e28654SJordan Rose 
405afe7c2c2SJordan Rose   ExplodedNodeSet DstPreCall;
406b8e28654SJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
407fcd016e5SJordan Rose                                             *Call, *this);
40810e25031STed Kremenek 
40988bb563cSJordan Rose   ExplodedNodeSet DstEvaluated;
41088bb563cSJordan Rose   StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
41188bb563cSJordan Rose 
412e83cb092SJordan Rose   if (CE->getConstructor()->isTrivial() &&
413e83cb092SJordan Rose       CE->getConstructor()->isCopyOrMoveConstructor() &&
414168e29f6SArtem Dergachev       !CallOpts.IsArrayCtorOrDtor) {
415e83cb092SJordan Rose     // FIXME: Handle other kinds of trivial constructors as well.
416e83cb092SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
41788bb563cSJordan Rose          I != E; ++I)
41888bb563cSJordan Rose       performTrivialCopy(Bldr, *I, *Call);
41988bb563cSJordan Rose 
42088bb563cSJordan Rose   } else {
421afe7c2c2SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
422f3c12ac3SJordan Rose          I != E; ++I)
423690ab040SArtem Dergachev       defaultEvalCall(Bldr, *I, *Call, CallOpts);
42488bb563cSJordan Rose   }
42510e25031STed Kremenek 
4262a8c18d9SAlexander Kornienko   // If the CFG was constructed without elements for temporary destructors
4275b1ee2faSDevin Coughlin   // and the just-called constructor created a temporary object then
4285b1ee2faSDevin Coughlin   // stop exploration if the temporary object has a noreturn constructor.
4295b1ee2faSDevin Coughlin   // This can lose coverage because the destructor, if it were present
4305b1ee2faSDevin Coughlin   // in the CFG, would be called at the end of the full expression or
4315b1ee2faSDevin Coughlin   // later (for life-time extended temporaries) -- but avoids infeasible
4325b1ee2faSDevin Coughlin   // paths when no-return temporary destructors are used for assertions.
4335b1ee2faSDevin Coughlin   const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
4345b1ee2faSDevin Coughlin   if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
4355b1ee2faSDevin Coughlin     const MemRegion *Target = Call->getCXXThisVal().getAsRegion();
4365b1ee2faSDevin Coughlin     if (Target && isa<CXXTempObjectRegion>(Target) &&
4375b1ee2faSDevin Coughlin         Call->getDecl()->getParent()->isAnyDestructorNoReturn()) {
4385b1ee2faSDevin Coughlin 
4393da72051SArtem Dergachev       // If we've inlined the constructor, then DstEvaluated would be empty.
4403da72051SArtem Dergachev       // In this case we still want a sink, which could be implemented
4413da72051SArtem Dergachev       // in processCallExit. But we don't have that implemented at the moment,
4423da72051SArtem Dergachev       // so if you hit this assertion, see if you can avoid inlining
4433da72051SArtem Dergachev       // the respective constructor when analyzer-config cfg-temporary-dtors
4443da72051SArtem Dergachev       // is set to false.
4453da72051SArtem Dergachev       // Otherwise there's nothing wrong with inlining such constructor.
4463da72051SArtem Dergachev       assert(!DstEvaluated.empty() &&
4473da72051SArtem Dergachev              "We should not have inlined this constructor!");
4483da72051SArtem Dergachev 
4495b1ee2faSDevin Coughlin       for (ExplodedNode *N : DstEvaluated) {
4505b1ee2faSDevin Coughlin         Bldr.generateSink(CE, N, N->getState());
4515b1ee2faSDevin Coughlin       }
4525b1ee2faSDevin Coughlin 
4535b1ee2faSDevin Coughlin       // There is no need to run the PostCall and PostStmt checker
4545b1ee2faSDevin Coughlin       // callbacks because we just generated sinks on all nodes in th
4555b1ee2faSDevin Coughlin       // frontier.
4565b1ee2faSDevin Coughlin       return;
4575b1ee2faSDevin Coughlin     }
4585b1ee2faSDevin Coughlin   }
4595b1ee2faSDevin Coughlin 
460afe7c2c2SJordan Rose   ExplodedNodeSet DstPostCall;
46188bb563cSJordan Rose   getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
462fcd016e5SJordan Rose                                              *Call, *this);
463afe7c2c2SJordan Rose   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
46410e25031STed Kremenek }
46510e25031STed Kremenek 
466b970505dSJordan Rose void ExprEngine::VisitCXXDestructor(QualType ObjectType,
46710e25031STed Kremenek                                     const MemRegion *Dest,
46810e25031STed Kremenek                                     const Stmt *S,
4692bc9674bSJordan Rose                                     bool IsBaseDtor,
47010e25031STed Kremenek                                     ExplodedNode *Pred,
471168e29f6SArtem Dergachev                                     ExplodedNodeSet &Dst,
472168e29f6SArtem Dergachev                                     const EvalCallOptions &CallOpts) {
473fcd016e5SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
474fcd016e5SJordan Rose   ProgramStateRef State = Pred->getState();
475fcd016e5SJordan Rose 
476b970505dSJordan Rose   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
477b970505dSJordan Rose   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
478b970505dSJordan Rose   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
479b970505dSJordan Rose 
480fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
481fcd016e5SJordan Rose   CallEventRef<CXXDestructorCall> Call =
4822bc9674bSJordan Rose     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
483142adc49STed Kremenek 
48417a8757aSJordan Rose   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
48517a8757aSJordan Rose                                 Call->getSourceRange().getBegin(),
48617a8757aSJordan Rose                                 "Error evaluating destructor");
48717a8757aSJordan Rose 
4884ee71b8aSJordan Rose   ExplodedNodeSet DstPreCall;
4894ee71b8aSJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
490fcd016e5SJordan Rose                                             *Call, *this);
49110e25031STed Kremenek 
4924ee71b8aSJordan Rose   ExplodedNodeSet DstInvalidated;
493d94854a4STed Kremenek   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
4944ee71b8aSJordan Rose   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
4954ee71b8aSJordan Rose        I != E; ++I)
496690ab040SArtem Dergachev     defaultEvalCall(Bldr, *I, *Call, CallOpts);
4974ee71b8aSJordan Rose 
4984ee71b8aSJordan Rose   ExplodedNodeSet DstPostCall;
4994ee71b8aSJordan Rose   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
500fcd016e5SJordan Rose                                              *Call, *this);
50110e25031STed Kremenek }
50210e25031STed Kremenek 
5038b808d64SJordan Rose void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
5048b808d64SJordan Rose                                           ExplodedNode *Pred,
5058b808d64SJordan Rose                                           ExplodedNodeSet &Dst) {
5068b808d64SJordan Rose   ProgramStateRef State = Pred->getState();
5078b808d64SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
5088b808d64SJordan Rose   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
5098b808d64SJordan Rose                                 CNE->getStartLoc(),
5108b808d64SJordan Rose                                 "Error evaluating New Allocator Call");
5118b808d64SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
5128b808d64SJordan Rose   CallEventRef<CXXAllocatorCall> Call =
5138b808d64SJordan Rose     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
5148b808d64SJordan Rose 
5158b808d64SJordan Rose   ExplodedNodeSet DstPreCall;
5168b808d64SJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
5178b808d64SJordan Rose                                             *Call, *this);
5188b808d64SJordan Rose 
51955796302SArtem Dergachev   ExplodedNodeSet DstPostCall;
52055796302SArtem Dergachev   StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
5211084de52SArtem Dergachev   for (auto I : DstPreCall) {
5221084de52SArtem Dergachev     // FIXME: Provide evalCall for checkers?
52355796302SArtem Dergachev     defaultEvalCall(CallBldr, I, *Call);
5241084de52SArtem Dergachev   }
525beba5307SArtem Dergachev   // If the call is inlined, DstPostCall will be empty and we bail out now.
52655796302SArtem Dergachev 
52755796302SArtem Dergachev   // Store return value of operator new() for future use, until the actual
52855796302SArtem Dergachev   // CXXNewExpr gets processed.
52955796302SArtem Dergachev   ExplodedNodeSet DstPostValue;
53055796302SArtem Dergachev   StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
53155796302SArtem Dergachev   for (auto I : DstPostCall) {
532beba5307SArtem Dergachev     // FIXME: Because CNE serves as the "call site" for the allocator (due to
533beba5307SArtem Dergachev     // lack of a better expression in the AST), the conjured return value symbol
534beba5307SArtem Dergachev     // is going to be of the same type (C++ object pointer type). Technically
535beba5307SArtem Dergachev     // this is not correct because the operator new's prototype always says that
536beba5307SArtem Dergachev     // it returns a 'void *'. So we should change the type of the symbol,
537beba5307SArtem Dergachev     // and then evaluate the cast over the symbolic pointer from 'void *' to
538beba5307SArtem Dergachev     // the object pointer type. But without changing the symbol's type it
539beba5307SArtem Dergachev     // is breaking too much to evaluate the no-op symbolic cast over it, so we
540beba5307SArtem Dergachev     // skip it for now.
54155796302SArtem Dergachev     ProgramStateRef State = I->getState();
54250e0372fSArtem Dergachev     SVal RetVal = State->getSVal(CNE, LCtx);
54350e0372fSArtem Dergachev 
54450e0372fSArtem Dergachev     // If this allocation function is not declared as non-throwing, failures
54550e0372fSArtem Dergachev     // /must/ be signalled by exceptions, and thus the return value will never
54650e0372fSArtem Dergachev     // be NULL. -fno-exceptions does not influence this semantics.
54750e0372fSArtem Dergachev     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
54850e0372fSArtem Dergachev     // where new can return NULL. If we end up supporting that option, we can
54950e0372fSArtem Dergachev     // consider adding a check for it here.
55050e0372fSArtem Dergachev     // C++11 [basic.stc.dynamic.allocation]p3.
55150e0372fSArtem Dergachev     if (const FunctionDecl *FD = CNE->getOperatorNew()) {
55250e0372fSArtem Dergachev       QualType Ty = FD->getType();
55350e0372fSArtem Dergachev       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
554eaf11ad7SRichard Smith         if (!ProtoType->isNothrow())
55550e0372fSArtem Dergachev           State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
55650e0372fSArtem Dergachev     }
55750e0372fSArtem Dergachev 
558f83d5479SArtem Dergachev     ValueBldr.generateNode(
559f83d5479SArtem Dergachev         CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
56055796302SArtem Dergachev   }
56155796302SArtem Dergachev 
56213b2026bSArtem Dergachev   ExplodedNodeSet DstPostPostCallCallback;
56313b2026bSArtem Dergachev   getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
56413b2026bSArtem Dergachev                                              DstPostValue, *Call, *this);
56513b2026bSArtem Dergachev   for (auto I : DstPostPostCallCallback) {
56613b2026bSArtem Dergachev     getCheckerManager().runCheckersForNewAllocator(
567f83d5479SArtem Dergachev         CNE, *getObjectUnderConstruction(I->getState(), CNE, LCtx), Dst, I,
568f83d5479SArtem Dergachev         *this);
56913b2026bSArtem Dergachev   }
5708b808d64SJordan Rose }
5718b808d64SJordan Rose 
57210e25031STed Kremenek void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
57310e25031STed Kremenek                                    ExplodedNodeSet &Dst) {
574a4ee064cSJordan Rose   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
575a4ee064cSJordan Rose   // Also, we need to decide how allocators actually work -- they're not
576a4ee064cSJordan Rose   // really part of the CXXNewExpr because they happen BEFORE the
577a4ee064cSJordan Rose   // CXXConstructExpr subexpression. See PR12014 for some discussion.
57810e25031STed Kremenek 
579d94854a4STed Kremenek   unsigned blockCount = currBldrCtx->blockCount();
580d519cae8STed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
58155796302SArtem Dergachev   SVal symVal = UnknownVal();
5828b662704SAnton Yartsev   FunctionDecl *FD = CNE->getOperatorNew();
58310e25031STed Kremenek 
5841084de52SArtem Dergachev   bool IsStandardGlobalOpNewFunction =
5851084de52SArtem Dergachev       FD->isReplaceableGlobalAllocationFunction();
5868b662704SAnton Yartsev 
58755796302SArtem Dergachev   ProgramStateRef State = Pred->getState();
58855796302SArtem Dergachev 
58955796302SArtem Dergachev   // Retrieve the stored operator new() return value.
59055796302SArtem Dergachev   if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
591f83d5479SArtem Dergachev     symVal = *getObjectUnderConstruction(State, CNE, LCtx);
592f83d5479SArtem Dergachev     State = finishObjectConstruction(State, CNE, LCtx);
59355796302SArtem Dergachev   }
59455796302SArtem Dergachev 
5958b662704SAnton Yartsev   // We assume all standard global 'operator new' functions allocate memory in
5968b662704SAnton Yartsev   // heap. We realize this is an approximation that might not correctly model
5978b662704SAnton Yartsev   // a custom global allocator.
59855796302SArtem Dergachev   if (symVal.isUnknown()) {
5998b662704SAnton Yartsev     if (IsStandardGlobalOpNewFunction)
6008b662704SAnton Yartsev       symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
6018b662704SAnton Yartsev     else
6020dbb783cSCraig Topper       symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
6038b662704SAnton Yartsev                                             blockCount);
60455796302SArtem Dergachev   }
6058b662704SAnton Yartsev 
606fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
607fcd016e5SJordan Rose   CallEventRef<CXXAllocatorCall> Call =
608fcd016e5SJordan Rose     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
609fcd016e5SJordan Rose 
61055796302SArtem Dergachev   if (!AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
611a4ee064cSJordan Rose     // Invalidate placement args.
612fcd016e5SJordan Rose     // FIXME: Once we figure out how we want allocators to work,
613fcd016e5SJordan Rose     // we should be using the usual pre-/(default-)eval-/post-call checks here.
614fcd016e5SJordan Rose     State = Call->invalidateRegions(blockCount);
615b8cb8359SJordan Rose     if (!State)
616b8cb8359SJordan Rose       return;
617a4ee064cSJordan Rose 
618fce1b03eSPavel Labath     // If this allocation function is not declared as non-throwing, failures
61950e0372fSArtem Dergachev     // /must/ be signalled by exceptions, and thus the return value will never
62050e0372fSArtem Dergachev     // be NULL. -fno-exceptions does not influence this semantics.
621fce1b03eSPavel Labath     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
622fce1b03eSPavel Labath     // where new can return NULL. If we end up supporting that option, we can
623fce1b03eSPavel Labath     // consider adding a check for it here.
6243957fd58SJordan Rose     // C++11 [basic.stc.dynamic.allocation]p3.
625fce1b03eSPavel Labath     if (FD) {
6263957fd58SJordan Rose       QualType Ty = FD->getType();
62750e0372fSArtem Dergachev       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
628eaf11ad7SRichard Smith         if (!ProtoType->isNothrow())
62955796302SArtem Dergachev           if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
63055796302SArtem Dergachev             State = State->assume(*dSymVal, true);
6313957fd58SJordan Rose     }
63250e0372fSArtem Dergachev   }
6333957fd58SJordan Rose 
634b8cb8359SJordan Rose   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
635b8cb8359SJordan Rose 
636beba5307SArtem Dergachev   SVal Result = symVal;
637beba5307SArtem Dergachev 
63810e25031STed Kremenek   if (CNE->isArray()) {
63910e25031STed Kremenek     // FIXME: allocating an array requires simulating the constructors.
64010e25031STed Kremenek     // For now, just return a symbolicated region.
6411084de52SArtem Dergachev     if (const SubRegion *NewReg =
6421084de52SArtem Dergachev             dyn_cast_or_null<SubRegion>(symVal.getAsRegion())) {
643a4ee064cSJordan Rose       QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
644a4ee064cSJordan Rose       const ElementRegion *EleReg =
645a4ee064cSJordan Rose           getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
646beba5307SArtem Dergachev       Result = loc::MemRegionVal(EleReg);
647beba5307SArtem Dergachev     }
648beba5307SArtem Dergachev     State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
64944320367SJordan Rose     Bldr.generateNode(CNE, Pred, State);
65010e25031STed Kremenek     return;
65110e25031STed Kremenek   }
65210e25031STed Kremenek 
653a4ee064cSJordan Rose   // FIXME: Once we have proper support for CXXConstructExprs inside
654a4ee064cSJordan Rose   // CXXNewExpr, we need to make sure that the constructed object is not
655a4ee064cSJordan Rose   // immediately invalidated here. (The placement call should happen before
656a4ee064cSJordan Rose   // the constructor call anyway.)
65744320367SJordan Rose   if (FD && FD->isReservedGlobalPlacementOperator()) {
65844320367SJordan Rose     // Non-array placement new should always return the placement location.
65944320367SJordan Rose     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
660b8cb8359SJordan Rose     Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
661aaf83184SJordan Rose                                   CNE->getPlacementArg(0)->getType());
66244320367SJordan Rose   }
66344320367SJordan Rose 
664b8cb8359SJordan Rose   // Bind the address of the object, then check to see if we cached out.
665b8cb8359SJordan Rose   State = State->BindExpr(CNE, LCtx, Result);
6668f6b4b04SJordan Rose   ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
6678f6b4b04SJordan Rose   if (!NewN)
6688f6b4b04SJordan Rose     return;
6693503cb35SJordan Rose 
6705089f3b3SJordan Rose   // If the type is not a record, we won't have a CXXConstructExpr as an
6715089f3b3SJordan Rose   // initializer. Copy the value over.
6725089f3b3SJordan Rose   if (const Expr *Init = CNE->getInitializer()) {
6735089f3b3SJordan Rose     if (!isa<CXXConstructExpr>(Init)) {
6743503cb35SJordan Rose       assert(Bldr.getResults().size() == 1);
6758f6b4b04SJordan Rose       Bldr.takeNodes(NewN);
676b8cb8359SJordan Rose       evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
677b8cb8359SJordan Rose                /*FirstInit=*/IsStandardGlobalOpNewFunction);
6783503cb35SJordan Rose     }
6793503cb35SJordan Rose   }
68010e25031STed Kremenek }
68110e25031STed Kremenek 
68210e25031STed Kremenek void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
68310e25031STed Kremenek                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
684d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
68564aea652SErik Verbruggen   ProgramStateRef state = Pred->getState();
68664aea652SErik Verbruggen   Bldr.generateNode(CDE, Pred, state);
68710e25031STed Kremenek }
68810e25031STed Kremenek 
6898fdb59f9STed Kremenek void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
6908fdb59f9STed Kremenek                                    ExplodedNode *Pred,
6918fdb59f9STed Kremenek                                    ExplodedNodeSet &Dst) {
6928fdb59f9STed Kremenek   const VarDecl *VD = CS->getExceptionDecl();
693b1279b5cSTed Kremenek   if (!VD) {
694b1279b5cSTed Kremenek     Dst.Add(Pred);
695b1279b5cSTed Kremenek     return;
696b1279b5cSTed Kremenek   }
697b1279b5cSTed Kremenek 
6988fdb59f9STed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
699d227833cSTed Kremenek   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
700d94854a4STed Kremenek                                         currBldrCtx->blockCount());
7018fdb59f9STed Kremenek   ProgramStateRef state = Pred->getState();
702b570195cSAnna Zaks   state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
7038fdb59f9STed Kremenek 
704d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
7058fdb59f9STed Kremenek   Bldr.generateNode(CS, Pred, state);
7068fdb59f9STed Kremenek }
7078fdb59f9STed Kremenek 
70810e25031STed Kremenek void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
70910e25031STed Kremenek                                     ExplodedNodeSet &Dst) {
710d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
711e594034fSAnna Zaks 
71210e25031STed Kremenek   // Get the this object region from StoreManager.
713632e3b7eSTed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
71410e25031STed Kremenek   const MemRegion *R =
71510e25031STed Kremenek     svalBuilder.getRegionManager().getCXXThisRegion(
71610e25031STed Kremenek                                   getContext().getCanonicalType(TE->getType()),
717632e3b7eSTed Kremenek                                                     LCtx);
71810e25031STed Kremenek 
71949b1e38eSTed Kremenek   ProgramStateRef state = Pred->getState();
72010e25031STed Kremenek   SVal V = state->getSVal(loc::MemRegionVal(R));
721632e3b7eSTed Kremenek   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
72210e25031STed Kremenek }
72315843343SGabor Horvath 
72415843343SGabor Horvath void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
72515843343SGabor Horvath                                  ExplodedNodeSet &Dst) {
72615843343SGabor Horvath   const LocationContext *LocCtxt = Pred->getLocationContext();
72715843343SGabor Horvath 
72815843343SGabor Horvath   // Get the region of the lambda itself.
72915843343SGabor Horvath   const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
73015843343SGabor Horvath       LE, LocCtxt);
73115843343SGabor Horvath   SVal V = loc::MemRegionVal(R);
73215843343SGabor Horvath 
73315843343SGabor Horvath   ProgramStateRef State = Pred->getState();
73415843343SGabor Horvath 
73515843343SGabor Horvath   // If we created a new MemRegion for the lambda, we should explicitly bind
73615843343SGabor Horvath   // the captures.
73715843343SGabor Horvath   CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
73815843343SGabor Horvath   for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
73915843343SGabor Horvath                                                e = LE->capture_init_end();
74015843343SGabor Horvath        i != e; ++i, ++CurField) {
7417bdca8b2SDevin Coughlin     FieldDecl *FieldForCapture = *CurField;
7427bdca8b2SDevin Coughlin     SVal FieldLoc = State->getLValue(FieldForCapture, V);
7437bdca8b2SDevin Coughlin 
7447bdca8b2SDevin Coughlin     SVal InitVal;
7457bdca8b2SDevin Coughlin     if (!FieldForCapture->hasCapturedVLAType()) {
7467bdca8b2SDevin Coughlin       Expr *InitExpr = *i;
7477bdca8b2SDevin Coughlin       assert(InitExpr && "Capture missing initialization expression");
7487bdca8b2SDevin Coughlin       InitVal = State->getSVal(InitExpr, LocCtxt);
7497bdca8b2SDevin Coughlin     } else {
7507bdca8b2SDevin Coughlin       // The field stores the length of a captured variable-length array.
7517bdca8b2SDevin Coughlin       // These captures don't have initialization expressions; instead we
7527bdca8b2SDevin Coughlin       // get the length from the VLAType size expression.
7537bdca8b2SDevin Coughlin       Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
7547bdca8b2SDevin Coughlin       InitVal = State->getSVal(SizeExpr, LocCtxt);
7557bdca8b2SDevin Coughlin     }
7567bdca8b2SDevin Coughlin 
757b570195cSAnna Zaks     State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
75815843343SGabor Horvath   }
75915843343SGabor Horvath 
76015843343SGabor Horvath   // Decay the Loc into an RValue, because there might be a
76115843343SGabor Horvath   // MaterializeTemporaryExpr node above this one which expects the bound value
76215843343SGabor Horvath   // to be an RValue.
76315843343SGabor Horvath   SVal LambdaRVal = State->getSVal(R);
76415843343SGabor Horvath 
76515843343SGabor Horvath   ExplodedNodeSet Tmp;
76615843343SGabor Horvath   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
76715843343SGabor Horvath   // FIXME: is this the right program point kind?
76815843343SGabor Horvath   Bldr.generateNode(LE, Pred,
76915843343SGabor Horvath                     State->BindExpr(LE, LocCtxt, LambdaRVal),
77015843343SGabor Horvath                     nullptr, ProgramPoint::PostLValueKind);
77115843343SGabor Horvath 
77215843343SGabor Horvath   // FIXME: Move all post/pre visits to ::Visit().
77315843343SGabor Horvath   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
77415843343SGabor Horvath }
775