1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines a meta-engine for path-sensitive dataflow analysis that
11 //  is built on GREngine, but provides the boilerplate to execute transfer
12 //  functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/PrettyStackTrace.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
30 #include "llvm/ADT/ImmutableList.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/SaveAndRestore.h"
34 
35 #ifndef NDEBUG
36 #include "llvm/Support/GraphWriter.h"
37 #endif
38 
39 using namespace clang;
40 using namespace ento;
41 using llvm::APSInt;
42 
43 #define DEBUG_TYPE "ExprEngine"
44 
45 STATISTIC(NumRemoveDeadBindings,
46             "The # of times RemoveDeadBindings is called");
47 STATISTIC(NumMaxBlockCountReached,
48             "The # of aborted paths due to reaching the maximum block count in "
49             "a top level function");
50 STATISTIC(NumMaxBlockCountReachedInInlined,
51             "The # of aborted paths due to reaching the maximum block count in "
52             "an inlined function");
53 STATISTIC(NumTimesRetriedWithoutInlining,
54             "The # of times we re-evaluated a call without inlining");
55 
56 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
57     CXXBindTemporaryContext;
58 
59 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated.
60 // The StackFrameContext assures that nested calls due to inlined recursive
61 // functions do not interfere.
62 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet,
63                                  llvm::ImmutableSet<CXXBindTemporaryContext>)
64 
65 //===----------------------------------------------------------------------===//
66 // Engine construction and deletion.
67 //===----------------------------------------------------------------------===//
68 
69 static const char* TagProviderName = "ExprEngine";
70 
71 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
72                        SetOfConstDecls *VisitedCalleesIn,
73                        FunctionSummariesTy *FS,
74                        InliningModes HowToInlineIn)
75   : AMgr(mgr),
76     AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
77     Engine(*this, FS),
78     G(Engine.getGraph()),
79     StateMgr(getContext(), mgr.getStoreManagerCreator(),
80              mgr.getConstraintManagerCreator(), G.getAllocator(),
81              this),
82     SymMgr(StateMgr.getSymbolManager()),
83     svalBuilder(StateMgr.getSValBuilder()),
84     currStmtIdx(0), currBldrCtx(nullptr),
85     ObjCNoRet(mgr.getASTContext()),
86     ObjCGCEnabled(gcEnabled), BR(mgr, *this),
87     VisitedCallees(VisitedCalleesIn),
88     HowToInline(HowToInlineIn)
89 {
90   unsigned TrimInterval = mgr.options.getGraphTrimInterval();
91   if (TrimInterval != 0) {
92     // Enable eager node reclaimation when constructing the ExplodedGraph.
93     G.enableNodeReclamation(TrimInterval);
94   }
95 }
96 
97 ExprEngine::~ExprEngine() {
98   BR.FlushReports();
99 }
100 
101 //===----------------------------------------------------------------------===//
102 // Utility methods.
103 //===----------------------------------------------------------------------===//
104 
105 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
106   ProgramStateRef state = StateMgr.getInitialState(InitLoc);
107   const Decl *D = InitLoc->getDecl();
108 
109   // Preconditions.
110   // FIXME: It would be nice if we had a more general mechanism to add
111   // such preconditions.  Some day.
112   do {
113 
114     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
115       // Precondition: the first argument of 'main' is an integer guaranteed
116       //  to be > 0.
117       const IdentifierInfo *II = FD->getIdentifier();
118       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
119         break;
120 
121       const ParmVarDecl *PD = FD->getParamDecl(0);
122       QualType T = PD->getType();
123       const BuiltinType *BT = dyn_cast<BuiltinType>(T);
124       if (!BT || !BT->isInteger())
125         break;
126 
127       const MemRegion *R = state->getRegion(PD, InitLoc);
128       if (!R)
129         break;
130 
131       SVal V = state->getSVal(loc::MemRegionVal(R));
132       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
133                                            svalBuilder.makeZeroVal(T),
134                                            svalBuilder.getConditionType());
135 
136       Optional<DefinedOrUnknownSVal> Constraint =
137           Constraint_untested.getAs<DefinedOrUnknownSVal>();
138 
139       if (!Constraint)
140         break;
141 
142       if (ProgramStateRef newState = state->assume(*Constraint, true))
143         state = newState;
144     }
145     break;
146   }
147   while (0);
148 
149   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
150     // Precondition: 'self' is always non-null upon entry to an Objective-C
151     // method.
152     const ImplicitParamDecl *SelfD = MD->getSelfDecl();
153     const MemRegion *R = state->getRegion(SelfD, InitLoc);
154     SVal V = state->getSVal(loc::MemRegionVal(R));
155 
156     if (Optional<Loc> LV = V.getAs<Loc>()) {
157       // Assume that the pointer value in 'self' is non-null.
158       state = state->assume(*LV, true);
159       assert(state && "'self' cannot be null");
160     }
161   }
162 
163   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
164     if (!MD->isStatic()) {
165       // Precondition: 'this' is always non-null upon entry to the
166       // top-level function.  This is our starting assumption for
167       // analyzing an "open" program.
168       const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
169       if (SFC->getParent() == nullptr) {
170         loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
171         SVal V = state->getSVal(L);
172         if (Optional<Loc> LV = V.getAs<Loc>()) {
173           state = state->assume(*LV, true);
174           assert(state && "'this' cannot be null");
175         }
176       }
177     }
178   }
179 
180   return state;
181 }
182 
183 ProgramStateRef
184 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
185                                           const LocationContext *LC,
186                                           const Expr *Ex,
187                                           const Expr *Result) {
188   SVal V = State->getSVal(Ex, LC);
189   if (!Result) {
190     // If we don't have an explicit result expression, we're in "if needed"
191     // mode. Only create a region if the current value is a NonLoc.
192     if (!V.getAs<NonLoc>())
193       return State;
194     Result = Ex;
195   } else {
196     // We need to create a region no matter what. For sanity, make sure we don't
197     // try to stuff a Loc into a non-pointer temporary region.
198     assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) ||
199            Result->getType()->isMemberPointerType());
200   }
201 
202   ProgramStateManager &StateMgr = State->getStateManager();
203   MemRegionManager &MRMgr = StateMgr.getRegionManager();
204   StoreManager &StoreMgr = StateMgr.getStoreManager();
205 
206   // We need to be careful about treating a derived type's value as
207   // bindings for a base type. Unless we're creating a temporary pointer region,
208   // start by stripping and recording base casts.
209   SmallVector<const CastExpr *, 4> Casts;
210   const Expr *Inner = Ex->IgnoreParens();
211   if (!Loc::isLocType(Result->getType())) {
212     while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) {
213       if (CE->getCastKind() == CK_DerivedToBase ||
214           CE->getCastKind() == CK_UncheckedDerivedToBase)
215         Casts.push_back(CE);
216       else if (CE->getCastKind() != CK_NoOp)
217         break;
218 
219       Inner = CE->getSubExpr()->IgnoreParens();
220     }
221   }
222 
223   // Create a temporary object region for the inner expression (which may have
224   // a more derived type) and bind the value into it.
225   const TypedValueRegion *TR = nullptr;
226   if (const MaterializeTemporaryExpr *MT =
227           dyn_cast<MaterializeTemporaryExpr>(Result)) {
228     StorageDuration SD = MT->getStorageDuration();
229     // If this object is bound to a reference with static storage duration, we
230     // put it in a different region to prevent "address leakage" warnings.
231     if (SD == SD_Static || SD == SD_Thread)
232         TR = MRMgr.getCXXStaticTempObjectRegion(Inner);
233   }
234   if (!TR)
235     TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
236 
237   SVal Reg = loc::MemRegionVal(TR);
238 
239   if (V.isUnknown())
240     V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
241                                           currBldrCtx->blockCount());
242   State = State->bindLoc(Reg, V);
243 
244   // Re-apply the casts (from innermost to outermost) for type sanity.
245   for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(),
246                                                            E = Casts.rend();
247        I != E; ++I) {
248     Reg = StoreMgr.evalDerivedToBase(Reg, *I);
249   }
250 
251   State = State->BindExpr(Result, LC, Reg);
252   return State;
253 }
254 
255 //===----------------------------------------------------------------------===//
256 // Top-level transfer function logic (Dispatcher).
257 //===----------------------------------------------------------------------===//
258 
259 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
260 ///  logic for handling assumptions on symbolic values.
261 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
262                                               SVal cond, bool assumption) {
263   return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
264 }
265 
266 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
267   return getCheckerManager().wantsRegionChangeUpdate(state);
268 }
269 
270 ProgramStateRef
271 ExprEngine::processRegionChanges(ProgramStateRef state,
272                                  const InvalidatedSymbols *invalidated,
273                                  ArrayRef<const MemRegion *> Explicits,
274                                  ArrayRef<const MemRegion *> Regions,
275                                  const CallEvent *Call) {
276   return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
277                                                       Explicits, Regions, Call);
278 }
279 
280 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
281                             const char *NL, const char *Sep) {
282   getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
283 }
284 
285 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
286   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
287 }
288 
289 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
290                                    unsigned StmtIdx, NodeBuilderContext *Ctx) {
291   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
292   currStmtIdx = StmtIdx;
293   currBldrCtx = Ctx;
294 
295   switch (E.getKind()) {
296     case CFGElement::Statement:
297       ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
298       return;
299     case CFGElement::Initializer:
300       ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
301       return;
302     case CFGElement::NewAllocator:
303       ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
304                           Pred);
305       return;
306     case CFGElement::AutomaticObjectDtor:
307     case CFGElement::DeleteDtor:
308     case CFGElement::BaseDtor:
309     case CFGElement::MemberDtor:
310     case CFGElement::TemporaryDtor:
311       ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
312       return;
313   }
314 }
315 
316 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
317                                      const CFGStmt S,
318                                      const ExplodedNode *Pred,
319                                      const LocationContext *LC) {
320 
321   // Are we never purging state values?
322   if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
323     return false;
324 
325   // Is this the beginning of a basic block?
326   if (Pred->getLocation().getAs<BlockEntrance>())
327     return true;
328 
329   // Is this on a non-expression?
330   if (!isa<Expr>(S.getStmt()))
331     return true;
332 
333   // Run before processing a call.
334   if (CallEvent::isCallStmt(S.getStmt()))
335     return true;
336 
337   // Is this an expression that is consumed by another expression?  If so,
338   // postpone cleaning out the state.
339   ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
340   return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
341 }
342 
343 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
344                             const Stmt *ReferenceStmt,
345                             const LocationContext *LC,
346                             const Stmt *DiagnosticStmt,
347                             ProgramPoint::Kind K) {
348   assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
349           ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
350           && "PostStmt is not generally supported by the SymbolReaper yet");
351   assert(LC && "Must pass the current (or expiring) LocationContext");
352 
353   if (!DiagnosticStmt) {
354     DiagnosticStmt = ReferenceStmt;
355     assert(DiagnosticStmt && "Required for clearing a LocationContext");
356   }
357 
358   NumRemoveDeadBindings++;
359   ProgramStateRef CleanedState = Pred->getState();
360 
361   // LC is the location context being destroyed, but SymbolReaper wants a
362   // location context that is still live. (If this is the top-level stack
363   // frame, this will be null.)
364   if (!ReferenceStmt) {
365     assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
366            "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
367     LC = LC->getParent();
368   }
369 
370   const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
371   SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
372 
373   getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
374 
375   // Create a state in which dead bindings are removed from the environment
376   // and the store. TODO: The function should just return new env and store,
377   // not a new state.
378   CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
379 
380   // Process any special transfer function for dead symbols.
381   // A tag to track convenience transitions, which can be removed at cleanup.
382   static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
383   if (!SymReaper.hasDeadSymbols()) {
384     // Generate a CleanedNode that has the environment and store cleaned
385     // up. Since no symbols are dead, we can optimize and not clean out
386     // the constraint manager.
387     StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
388     Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
389 
390   } else {
391     // Call checkers with the non-cleaned state so that they could query the
392     // values of the soon to be dead symbols.
393     ExplodedNodeSet CheckedSet;
394     getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
395                                                   DiagnosticStmt, *this, K);
396 
397     // For each node in CheckedSet, generate CleanedNodes that have the
398     // environment, the store, and the constraints cleaned up but have the
399     // user-supplied states as the predecessors.
400     StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
401     for (ExplodedNodeSet::const_iterator
402           I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
403       ProgramStateRef CheckerState = (*I)->getState();
404 
405       // The constraint manager has not been cleaned up yet, so clean up now.
406       CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
407                                                                SymReaper);
408 
409       assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
410         "Checkers are not allowed to modify the Environment as a part of "
411         "checkDeadSymbols processing.");
412       assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
413         "Checkers are not allowed to modify the Store as a part of "
414         "checkDeadSymbols processing.");
415 
416       // Create a state based on CleanedState with CheckerState GDM and
417       // generate a transition to that state.
418       ProgramStateRef CleanedCheckerSt =
419         StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
420       Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
421     }
422   }
423 }
424 
425 void ExprEngine::ProcessStmt(const CFGStmt S,
426                              ExplodedNode *Pred) {
427   // Reclaim any unnecessary nodes in the ExplodedGraph.
428   G.reclaimRecentlyAllocatedNodes();
429 
430   const Stmt *currStmt = S.getStmt();
431   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
432                                 currStmt->getLocStart(),
433                                 "Error evaluating statement");
434 
435   // Remove dead bindings and symbols.
436   ExplodedNodeSet CleanedStates;
437   if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
438     removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
439   } else
440     CleanedStates.Add(Pred);
441 
442   // Visit the statement.
443   ExplodedNodeSet Dst;
444   for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
445                                  E = CleanedStates.end(); I != E; ++I) {
446     ExplodedNodeSet DstI;
447     // Visit the statement.
448     Visit(currStmt, *I, DstI);
449     Dst.insert(DstI);
450   }
451 
452   // Enqueue the new nodes onto the work list.
453   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
454 }
455 
456 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
457                                     ExplodedNode *Pred) {
458   const CXXCtorInitializer *BMI = Init.getInitializer();
459 
460   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
461                                 BMI->getSourceLocation(),
462                                 "Error evaluating initializer");
463 
464   // We don't clean up dead bindings here.
465   const StackFrameContext *stackFrame =
466                            cast<StackFrameContext>(Pred->getLocationContext());
467   const CXXConstructorDecl *decl =
468                            cast<CXXConstructorDecl>(stackFrame->getDecl());
469 
470   ProgramStateRef State = Pred->getState();
471   SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
472 
473   ExplodedNodeSet Tmp(Pred);
474   SVal FieldLoc;
475 
476   // Evaluate the initializer, if necessary
477   if (BMI->isAnyMemberInitializer()) {
478     // Constructors build the object directly in the field,
479     // but non-objects must be copied in from the initializer.
480     if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
481       assert(BMI->getInit()->IgnoreImplicit() == CtorExpr);
482       (void)CtorExpr;
483       // The field was directly constructed, so there is no need to bind.
484     } else {
485       const Expr *Init = BMI->getInit()->IgnoreImplicit();
486       const ValueDecl *Field;
487       if (BMI->isIndirectMemberInitializer()) {
488         Field = BMI->getIndirectMember();
489         FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
490       } else {
491         Field = BMI->getMember();
492         FieldLoc = State->getLValue(BMI->getMember(), thisVal);
493       }
494 
495       SVal InitVal;
496       if (BMI->getNumArrayIndices() > 0) {
497         // Handle arrays of trivial type. We can represent this with a
498         // primitive load/copy from the base array region.
499         const ArraySubscriptExpr *ASE;
500         while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
501           Init = ASE->getBase()->IgnoreImplicit();
502 
503         SVal LValue = State->getSVal(Init, stackFrame);
504         if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
505           InitVal = State->getSVal(*LValueLoc);
506 
507         // If we fail to get the value for some reason, use a symbolic value.
508         if (InitVal.isUnknownOrUndef()) {
509           SValBuilder &SVB = getSValBuilder();
510           InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
511                                          Field->getType(),
512                                          currBldrCtx->blockCount());
513         }
514       } else {
515         InitVal = State->getSVal(BMI->getInit(), stackFrame);
516       }
517 
518       assert(Tmp.size() == 1 && "have not generated any new nodes yet");
519       assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
520       Tmp.clear();
521 
522       PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
523       evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
524     }
525   } else {
526     assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
527     // We already did all the work when visiting the CXXConstructExpr.
528   }
529 
530   // Construct PostInitializer nodes whether the state changed or not,
531   // so that the diagnostics don't get confused.
532   PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
533   ExplodedNodeSet Dst;
534   NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
535   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
536     ExplodedNode *N = *I;
537     Bldr.generateNode(PP, N->getState(), N);
538   }
539 
540   // Enqueue the new nodes onto the work list.
541   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
542 }
543 
544 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
545                                      ExplodedNode *Pred) {
546   ExplodedNodeSet Dst;
547   switch (D.getKind()) {
548   case CFGElement::AutomaticObjectDtor:
549     ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
550     break;
551   case CFGElement::BaseDtor:
552     ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
553     break;
554   case CFGElement::MemberDtor:
555     ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
556     break;
557   case CFGElement::TemporaryDtor:
558     ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
559     break;
560   case CFGElement::DeleteDtor:
561     ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
562     break;
563   default:
564     llvm_unreachable("Unexpected dtor kind.");
565   }
566 
567   // Enqueue the new nodes onto the work list.
568   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
569 }
570 
571 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
572                                      ExplodedNode *Pred) {
573   ExplodedNodeSet Dst;
574   AnalysisManager &AMgr = getAnalysisManager();
575   AnalyzerOptions &Opts = AMgr.options;
576   // TODO: We're not evaluating allocators for all cases just yet as
577   // we're not handling the return value correctly, which causes false
578   // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
579   if (Opts.mayInlineCXXAllocator())
580     VisitCXXNewAllocatorCall(NE, Pred, Dst);
581   else {
582     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
583     const LocationContext *LCtx = Pred->getLocationContext();
584     PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
585     Bldr.generateNode(PP, Pred->getState(), Pred);
586   }
587   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
588 }
589 
590 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
591                                          ExplodedNode *Pred,
592                                          ExplodedNodeSet &Dst) {
593   const VarDecl *varDecl = Dtor.getVarDecl();
594   QualType varType = varDecl->getType();
595 
596   ProgramStateRef state = Pred->getState();
597   SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
598   const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
599 
600   if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
601     varType = refType->getPointeeType();
602     Region = state->getSVal(Region).getAsRegion();
603   }
604 
605   VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
606                      Pred, Dst);
607 }
608 
609 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
610                                    ExplodedNode *Pred,
611                                    ExplodedNodeSet &Dst) {
612   ProgramStateRef State = Pred->getState();
613   const LocationContext *LCtx = Pred->getLocationContext();
614   const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
615   const Stmt *Arg = DE->getArgument();
616   SVal ArgVal = State->getSVal(Arg, LCtx);
617 
618   // If the argument to delete is known to be a null value,
619   // don't run destructor.
620   if (State->isNull(ArgVal).isConstrainedTrue()) {
621     QualType DTy = DE->getDestroyedType();
622     QualType BTy = getContext().getBaseElementType(DTy);
623     const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
624     const CXXDestructorDecl *Dtor = RD->getDestructor();
625 
626     PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
627     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
628     Bldr.generateNode(PP, Pred->getState(), Pred);
629     return;
630   }
631 
632   VisitCXXDestructor(DE->getDestroyedType(),
633                      ArgVal.getAsRegion(),
634                      DE, /*IsBase=*/ false,
635                      Pred, Dst);
636 }
637 
638 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
639                                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
640   const LocationContext *LCtx = Pred->getLocationContext();
641 
642   const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
643   Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
644                                             LCtx->getCurrentStackFrame());
645   SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
646 
647   // Create the base object region.
648   const CXXBaseSpecifier *Base = D.getBaseSpecifier();
649   QualType BaseTy = Base->getType();
650   SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
651                                                      Base->isVirtual());
652 
653   VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
654                      CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
655 }
656 
657 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
658                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
659   const FieldDecl *Member = D.getFieldDecl();
660   ProgramStateRef State = Pred->getState();
661   const LocationContext *LCtx = Pred->getLocationContext();
662 
663   const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
664   Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
665                                             LCtx->getCurrentStackFrame());
666   SVal FieldVal =
667       State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
668 
669   VisitCXXDestructor(Member->getType(),
670                      FieldVal.castAs<loc::MemRegionVal>().getRegion(),
671                      CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
672 }
673 
674 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
675                                       ExplodedNode *Pred,
676                                       ExplodedNodeSet &Dst) {
677   ExplodedNodeSet CleanDtorState;
678   StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
679   ProgramStateRef State = Pred->getState();
680   if (State->contains<InitializedTemporariesSet>(
681       std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) {
682     // FIXME: Currently we insert temporary destructors for default parameters,
683     // but we don't insert the constructors.
684     State = State->remove<InitializedTemporariesSet>(
685         std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()));
686   }
687   StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
688 
689   QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
690   // FIXME: Currently CleanDtorState can be empty here due to temporaries being
691   // bound to default parameters.
692   assert(CleanDtorState.size() <= 1);
693   ExplodedNode *CleanPred =
694       CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
695   // FIXME: Inlining of temporary destructors is not supported yet anyway, so
696   // we just put a NULL region for now. This will need to be changed later.
697   VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
698                      /*IsBase=*/false, CleanPred, Dst);
699 }
700 
701 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
702                                                NodeBuilderContext &BldCtx,
703                                                ExplodedNode *Pred,
704                                                ExplodedNodeSet &Dst,
705                                                const CFGBlock *DstT,
706                                                const CFGBlock *DstF) {
707   BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
708   if (Pred->getState()->contains<InitializedTemporariesSet>(
709           std::make_pair(BTE, Pred->getStackFrame()))) {
710     TempDtorBuilder.markInfeasible(false);
711     TempDtorBuilder.generateNode(Pred->getState(), true, Pred);
712   } else {
713     TempDtorBuilder.markInfeasible(true);
714     TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
715   }
716 }
717 
718 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
719                                            ExplodedNodeSet &PreVisit,
720                                            ExplodedNodeSet &Dst) {
721   if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
722     // In case we don't have temporary destructors in the CFG, do not mark
723     // the initialization - we would otherwise never clean it up.
724     Dst = PreVisit;
725     return;
726   }
727   StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
728   for (ExplodedNode *Node : PreVisit) {
729     ProgramStateRef State = Node->getState();
730 
731     if (!State->contains<InitializedTemporariesSet>(
732             std::make_pair(BTE, Node->getStackFrame()))) {
733       // FIXME: Currently the state might already contain the marker due to
734       // incorrect handling of temporaries bound to default parameters; for
735       // those, we currently skip the CXXBindTemporaryExpr but rely on adding
736       // temporary destructor nodes.
737       State = State->add<InitializedTemporariesSet>(
738           std::make_pair(BTE, Node->getStackFrame()));
739     }
740     StmtBldr.generateNode(BTE, Node, State);
741   }
742 }
743 
744 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
745                        ExplodedNodeSet &DstTop) {
746   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
747                                 S->getLocStart(),
748                                 "Error evaluating statement");
749   ExplodedNodeSet Dst;
750   StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
751 
752   assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
753 
754   switch (S->getStmtClass()) {
755     // C++ and ARC stuff we don't support yet.
756     case Expr::ObjCIndirectCopyRestoreExprClass:
757     case Stmt::CXXDependentScopeMemberExprClass:
758     case Stmt::CXXInheritedCtorInitExprClass:
759     case Stmt::CXXTryStmtClass:
760     case Stmt::CXXTypeidExprClass:
761     case Stmt::CXXUuidofExprClass:
762     case Stmt::CXXFoldExprClass:
763     case Stmt::MSPropertyRefExprClass:
764     case Stmt::MSPropertySubscriptExprClass:
765     case Stmt::CXXUnresolvedConstructExprClass:
766     case Stmt::DependentScopeDeclRefExprClass:
767     case Stmt::ArrayTypeTraitExprClass:
768     case Stmt::ExpressionTraitExprClass:
769     case Stmt::UnresolvedLookupExprClass:
770     case Stmt::UnresolvedMemberExprClass:
771     case Stmt::TypoExprClass:
772     case Stmt::CXXNoexceptExprClass:
773     case Stmt::PackExpansionExprClass:
774     case Stmt::SubstNonTypeTemplateParmPackExprClass:
775     case Stmt::FunctionParmPackExprClass:
776     case Stmt::CoroutineBodyStmtClass:
777     case Stmt::CoawaitExprClass:
778     case Stmt::CoreturnStmtClass:
779     case Stmt::CoyieldExprClass:
780     case Stmt::SEHTryStmtClass:
781     case Stmt::SEHExceptStmtClass:
782     case Stmt::SEHLeaveStmtClass:
783     case Stmt::SEHFinallyStmtClass: {
784       const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
785       Engine.addAbortedBlock(node, currBldrCtx->getBlock());
786       break;
787     }
788 
789     case Stmt::ParenExprClass:
790       llvm_unreachable("ParenExprs already handled.");
791     case Stmt::GenericSelectionExprClass:
792       llvm_unreachable("GenericSelectionExprs already handled.");
793     // Cases that should never be evaluated simply because they shouldn't
794     // appear in the CFG.
795     case Stmt::BreakStmtClass:
796     case Stmt::CaseStmtClass:
797     case Stmt::CompoundStmtClass:
798     case Stmt::ContinueStmtClass:
799     case Stmt::CXXForRangeStmtClass:
800     case Stmt::DefaultStmtClass:
801     case Stmt::DoStmtClass:
802     case Stmt::ForStmtClass:
803     case Stmt::GotoStmtClass:
804     case Stmt::IfStmtClass:
805     case Stmt::IndirectGotoStmtClass:
806     case Stmt::LabelStmtClass:
807     case Stmt::NoStmtClass:
808     case Stmt::NullStmtClass:
809     case Stmt::SwitchStmtClass:
810     case Stmt::WhileStmtClass:
811     case Expr::MSDependentExistsStmtClass:
812     case Stmt::CapturedStmtClass:
813     case Stmt::OMPParallelDirectiveClass:
814     case Stmt::OMPSimdDirectiveClass:
815     case Stmt::OMPForDirectiveClass:
816     case Stmt::OMPForSimdDirectiveClass:
817     case Stmt::OMPSectionsDirectiveClass:
818     case Stmt::OMPSectionDirectiveClass:
819     case Stmt::OMPSingleDirectiveClass:
820     case Stmt::OMPMasterDirectiveClass:
821     case Stmt::OMPCriticalDirectiveClass:
822     case Stmt::OMPParallelForDirectiveClass:
823     case Stmt::OMPParallelForSimdDirectiveClass:
824     case Stmt::OMPParallelSectionsDirectiveClass:
825     case Stmt::OMPTaskDirectiveClass:
826     case Stmt::OMPTaskyieldDirectiveClass:
827     case Stmt::OMPBarrierDirectiveClass:
828     case Stmt::OMPTaskwaitDirectiveClass:
829     case Stmt::OMPTaskgroupDirectiveClass:
830     case Stmt::OMPFlushDirectiveClass:
831     case Stmt::OMPOrderedDirectiveClass:
832     case Stmt::OMPAtomicDirectiveClass:
833     case Stmt::OMPTargetDirectiveClass:
834     case Stmt::OMPTargetDataDirectiveClass:
835     case Stmt::OMPTargetEnterDataDirectiveClass:
836     case Stmt::OMPTargetExitDataDirectiveClass:
837     case Stmt::OMPTargetParallelDirectiveClass:
838     case Stmt::OMPTargetParallelForDirectiveClass:
839     case Stmt::OMPTargetUpdateDirectiveClass:
840     case Stmt::OMPTeamsDirectiveClass:
841     case Stmt::OMPCancellationPointDirectiveClass:
842     case Stmt::OMPCancelDirectiveClass:
843     case Stmt::OMPTaskLoopDirectiveClass:
844     case Stmt::OMPTaskLoopSimdDirectiveClass:
845     case Stmt::OMPDistributeDirectiveClass:
846     case Stmt::OMPDistributeParallelForDirectiveClass:
847       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
848 
849     case Stmt::ObjCSubscriptRefExprClass:
850     case Stmt::ObjCPropertyRefExprClass:
851       llvm_unreachable("These are handled by PseudoObjectExpr");
852 
853     case Stmt::GNUNullExprClass: {
854       // GNU __null is a pointer-width integer, not an actual pointer.
855       ProgramStateRef state = Pred->getState();
856       state = state->BindExpr(S, Pred->getLocationContext(),
857                               svalBuilder.makeIntValWithPtrWidth(0, false));
858       Bldr.generateNode(S, Pred, state);
859       break;
860     }
861 
862     case Stmt::ObjCAtSynchronizedStmtClass:
863       Bldr.takeNodes(Pred);
864       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
865       Bldr.addNodes(Dst);
866       break;
867 
868     case Stmt::ExprWithCleanupsClass:
869       // Handled due to fully linearised CFG.
870       break;
871 
872     case Stmt::CXXBindTemporaryExprClass: {
873       Bldr.takeNodes(Pred);
874       ExplodedNodeSet PreVisit;
875       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
876       ExplodedNodeSet Next;
877       VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
878       getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
879       Bldr.addNodes(Dst);
880       break;
881     }
882 
883     // Cases not handled yet; but will handle some day.
884     case Stmt::DesignatedInitExprClass:
885     case Stmt::DesignatedInitUpdateExprClass:
886     case Stmt::ExtVectorElementExprClass:
887     case Stmt::ImaginaryLiteralClass:
888     case Stmt::ObjCAtCatchStmtClass:
889     case Stmt::ObjCAtFinallyStmtClass:
890     case Stmt::ObjCAtTryStmtClass:
891     case Stmt::ObjCAutoreleasePoolStmtClass:
892     case Stmt::ObjCEncodeExprClass:
893     case Stmt::ObjCIsaExprClass:
894     case Stmt::ObjCProtocolExprClass:
895     case Stmt::ObjCSelectorExprClass:
896     case Stmt::ParenListExprClass:
897     case Stmt::ShuffleVectorExprClass:
898     case Stmt::ConvertVectorExprClass:
899     case Stmt::VAArgExprClass:
900     case Stmt::CUDAKernelCallExprClass:
901     case Stmt::OpaqueValueExprClass:
902     case Stmt::AsTypeExprClass:
903     case Stmt::AtomicExprClass:
904       // Fall through.
905 
906     // Cases we intentionally don't evaluate, since they don't need
907     // to be explicitly evaluated.
908     case Stmt::PredefinedExprClass:
909     case Stmt::AddrLabelExprClass:
910     case Stmt::AttributedStmtClass:
911     case Stmt::IntegerLiteralClass:
912     case Stmt::CharacterLiteralClass:
913     case Stmt::ImplicitValueInitExprClass:
914     case Stmt::CXXScalarValueInitExprClass:
915     case Stmt::CXXBoolLiteralExprClass:
916     case Stmt::ObjCBoolLiteralExprClass:
917     case Stmt::FloatingLiteralClass:
918     case Stmt::NoInitExprClass:
919     case Stmt::SizeOfPackExprClass:
920     case Stmt::StringLiteralClass:
921     case Stmt::ObjCStringLiteralClass:
922     case Stmt::CXXPseudoDestructorExprClass:
923     case Stmt::SubstNonTypeTemplateParmExprClass:
924     case Stmt::CXXNullPtrLiteralExprClass:
925     case Stmt::OMPArraySectionExprClass:
926     case Stmt::TypeTraitExprClass: {
927       Bldr.takeNodes(Pred);
928       ExplodedNodeSet preVisit;
929       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
930       getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
931       Bldr.addNodes(Dst);
932       break;
933     }
934 
935     case Stmt::CXXDefaultArgExprClass:
936     case Stmt::CXXDefaultInitExprClass: {
937       Bldr.takeNodes(Pred);
938       ExplodedNodeSet PreVisit;
939       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
940 
941       ExplodedNodeSet Tmp;
942       StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
943 
944       const Expr *ArgE;
945       if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
946         ArgE = DefE->getExpr();
947       else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
948         ArgE = DefE->getExpr();
949       else
950         llvm_unreachable("unknown constant wrapper kind");
951 
952       bool IsTemporary = false;
953       if (const MaterializeTemporaryExpr *MTE =
954             dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
955         ArgE = MTE->GetTemporaryExpr();
956         IsTemporary = true;
957       }
958 
959       Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
960       if (!ConstantVal)
961         ConstantVal = UnknownVal();
962 
963       const LocationContext *LCtx = Pred->getLocationContext();
964       for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
965            I != E; ++I) {
966         ProgramStateRef State = (*I)->getState();
967         State = State->BindExpr(S, LCtx, *ConstantVal);
968         if (IsTemporary)
969           State = createTemporaryRegionIfNeeded(State, LCtx,
970                                                 cast<Expr>(S),
971                                                 cast<Expr>(S));
972         Bldr2.generateNode(S, *I, State);
973       }
974 
975       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
976       Bldr.addNodes(Dst);
977       break;
978     }
979 
980     // Cases we evaluate as opaque expressions, conjuring a symbol.
981     case Stmt::CXXStdInitializerListExprClass:
982     case Expr::ObjCArrayLiteralClass:
983     case Expr::ObjCDictionaryLiteralClass:
984     case Expr::ObjCBoxedExprClass: {
985       Bldr.takeNodes(Pred);
986 
987       ExplodedNodeSet preVisit;
988       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
989 
990       ExplodedNodeSet Tmp;
991       StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
992 
993       const Expr *Ex = cast<Expr>(S);
994       QualType resultType = Ex->getType();
995 
996       for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
997            it != et; ++it) {
998         ExplodedNode *N = *it;
999         const LocationContext *LCtx = N->getLocationContext();
1000         SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1001                                                    resultType,
1002                                                    currBldrCtx->blockCount());
1003         ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
1004         Bldr2.generateNode(S, N, state);
1005       }
1006 
1007       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1008       Bldr.addNodes(Dst);
1009       break;
1010     }
1011 
1012     case Stmt::ArraySubscriptExprClass:
1013       Bldr.takeNodes(Pred);
1014       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1015       Bldr.addNodes(Dst);
1016       break;
1017 
1018     case Stmt::GCCAsmStmtClass:
1019       Bldr.takeNodes(Pred);
1020       VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1021       Bldr.addNodes(Dst);
1022       break;
1023 
1024     case Stmt::MSAsmStmtClass:
1025       Bldr.takeNodes(Pred);
1026       VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1027       Bldr.addNodes(Dst);
1028       break;
1029 
1030     case Stmt::BlockExprClass:
1031       Bldr.takeNodes(Pred);
1032       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1033       Bldr.addNodes(Dst);
1034       break;
1035 
1036     case Stmt::LambdaExprClass:
1037       if (AMgr.options.shouldInlineLambdas()) {
1038         Bldr.takeNodes(Pred);
1039         VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1040         Bldr.addNodes(Dst);
1041       } else {
1042         const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1043         Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1044       }
1045       break;
1046 
1047     case Stmt::BinaryOperatorClass: {
1048       const BinaryOperator* B = cast<BinaryOperator>(S);
1049       if (B->isLogicalOp()) {
1050         Bldr.takeNodes(Pred);
1051         VisitLogicalExpr(B, Pred, Dst);
1052         Bldr.addNodes(Dst);
1053         break;
1054       }
1055       else if (B->getOpcode() == BO_Comma) {
1056         ProgramStateRef state = Pred->getState();
1057         Bldr.generateNode(B, Pred,
1058                           state->BindExpr(B, Pred->getLocationContext(),
1059                                           state->getSVal(B->getRHS(),
1060                                                   Pred->getLocationContext())));
1061         break;
1062       }
1063 
1064       Bldr.takeNodes(Pred);
1065 
1066       if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1067           (B->isRelationalOp() || B->isEqualityOp())) {
1068         ExplodedNodeSet Tmp;
1069         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1070         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1071       }
1072       else
1073         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1074 
1075       Bldr.addNodes(Dst);
1076       break;
1077     }
1078 
1079     case Stmt::CXXOperatorCallExprClass: {
1080       const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1081 
1082       // For instance method operators, make sure the 'this' argument has a
1083       // valid region.
1084       const Decl *Callee = OCE->getCalleeDecl();
1085       if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1086         if (MD->isInstance()) {
1087           ProgramStateRef State = Pred->getState();
1088           const LocationContext *LCtx = Pred->getLocationContext();
1089           ProgramStateRef NewState =
1090             createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1091           if (NewState != State) {
1092             Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1093                                      ProgramPoint::PreStmtKind);
1094             // Did we cache out?
1095             if (!Pred)
1096               break;
1097           }
1098         }
1099       }
1100       // FALLTHROUGH
1101     }
1102     case Stmt::CallExprClass:
1103     case Stmt::CXXMemberCallExprClass:
1104     case Stmt::UserDefinedLiteralClass: {
1105       Bldr.takeNodes(Pred);
1106       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1107       Bldr.addNodes(Dst);
1108       break;
1109     }
1110 
1111     case Stmt::CXXCatchStmtClass: {
1112       Bldr.takeNodes(Pred);
1113       VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1114       Bldr.addNodes(Dst);
1115       break;
1116     }
1117 
1118     case Stmt::CXXTemporaryObjectExprClass:
1119     case Stmt::CXXConstructExprClass: {
1120       Bldr.takeNodes(Pred);
1121       VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1122       Bldr.addNodes(Dst);
1123       break;
1124     }
1125 
1126     case Stmt::CXXNewExprClass: {
1127       Bldr.takeNodes(Pred);
1128       ExplodedNodeSet PostVisit;
1129       VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1130       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1131       Bldr.addNodes(Dst);
1132       break;
1133     }
1134 
1135     case Stmt::CXXDeleteExprClass: {
1136       Bldr.takeNodes(Pred);
1137       ExplodedNodeSet PreVisit;
1138       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1139       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1140 
1141       for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1142                                      e = PreVisit.end(); i != e ; ++i)
1143         VisitCXXDeleteExpr(CDE, *i, Dst);
1144 
1145       Bldr.addNodes(Dst);
1146       break;
1147     }
1148       // FIXME: ChooseExpr is really a constant.  We need to fix
1149       //        the CFG do not model them as explicit control-flow.
1150 
1151     case Stmt::ChooseExprClass: { // __builtin_choose_expr
1152       Bldr.takeNodes(Pred);
1153       const ChooseExpr *C = cast<ChooseExpr>(S);
1154       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1155       Bldr.addNodes(Dst);
1156       break;
1157     }
1158 
1159     case Stmt::CompoundAssignOperatorClass:
1160       Bldr.takeNodes(Pred);
1161       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1162       Bldr.addNodes(Dst);
1163       break;
1164 
1165     case Stmt::CompoundLiteralExprClass:
1166       Bldr.takeNodes(Pred);
1167       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1168       Bldr.addNodes(Dst);
1169       break;
1170 
1171     case Stmt::BinaryConditionalOperatorClass:
1172     case Stmt::ConditionalOperatorClass: { // '?' operator
1173       Bldr.takeNodes(Pred);
1174       const AbstractConditionalOperator *C
1175         = cast<AbstractConditionalOperator>(S);
1176       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1177       Bldr.addNodes(Dst);
1178       break;
1179     }
1180 
1181     case Stmt::CXXThisExprClass:
1182       Bldr.takeNodes(Pred);
1183       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1184       Bldr.addNodes(Dst);
1185       break;
1186 
1187     case Stmt::DeclRefExprClass: {
1188       Bldr.takeNodes(Pred);
1189       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1190       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1191       Bldr.addNodes(Dst);
1192       break;
1193     }
1194 
1195     case Stmt::DeclStmtClass:
1196       Bldr.takeNodes(Pred);
1197       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1198       Bldr.addNodes(Dst);
1199       break;
1200 
1201     case Stmt::ImplicitCastExprClass:
1202     case Stmt::CStyleCastExprClass:
1203     case Stmt::CXXStaticCastExprClass:
1204     case Stmt::CXXDynamicCastExprClass:
1205     case Stmt::CXXReinterpretCastExprClass:
1206     case Stmt::CXXConstCastExprClass:
1207     case Stmt::CXXFunctionalCastExprClass:
1208     case Stmt::ObjCBridgedCastExprClass: {
1209       Bldr.takeNodes(Pred);
1210       const CastExpr *C = cast<CastExpr>(S);
1211       // Handle the previsit checks.
1212       ExplodedNodeSet dstPrevisit;
1213       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1214 
1215       // Handle the expression itself.
1216       ExplodedNodeSet dstExpr;
1217       for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1218                                      e = dstPrevisit.end(); i != e ; ++i) {
1219         VisitCast(C, C->getSubExpr(), *i, dstExpr);
1220       }
1221 
1222       // Handle the postvisit checks.
1223       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1224       Bldr.addNodes(Dst);
1225       break;
1226     }
1227 
1228     case Expr::MaterializeTemporaryExprClass: {
1229       Bldr.takeNodes(Pred);
1230       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1231       CreateCXXTemporaryObject(MTE, Pred, Dst);
1232       Bldr.addNodes(Dst);
1233       break;
1234     }
1235 
1236     case Stmt::InitListExprClass:
1237       Bldr.takeNodes(Pred);
1238       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1239       Bldr.addNodes(Dst);
1240       break;
1241 
1242     case Stmt::MemberExprClass:
1243       Bldr.takeNodes(Pred);
1244       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1245       Bldr.addNodes(Dst);
1246       break;
1247 
1248     case Stmt::ObjCIvarRefExprClass:
1249       Bldr.takeNodes(Pred);
1250       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1251       Bldr.addNodes(Dst);
1252       break;
1253 
1254     case Stmt::ObjCForCollectionStmtClass:
1255       Bldr.takeNodes(Pred);
1256       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1257       Bldr.addNodes(Dst);
1258       break;
1259 
1260     case Stmt::ObjCMessageExprClass:
1261       Bldr.takeNodes(Pred);
1262       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1263       Bldr.addNodes(Dst);
1264       break;
1265 
1266     case Stmt::ObjCAtThrowStmtClass:
1267     case Stmt::CXXThrowExprClass:
1268       // FIXME: This is not complete.  We basically treat @throw as
1269       // an abort.
1270       Bldr.generateSink(S, Pred, Pred->getState());
1271       break;
1272 
1273     case Stmt::ReturnStmtClass:
1274       Bldr.takeNodes(Pred);
1275       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1276       Bldr.addNodes(Dst);
1277       break;
1278 
1279     case Stmt::OffsetOfExprClass:
1280       Bldr.takeNodes(Pred);
1281       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1282       Bldr.addNodes(Dst);
1283       break;
1284 
1285     case Stmt::UnaryExprOrTypeTraitExprClass:
1286       Bldr.takeNodes(Pred);
1287       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1288                                     Pred, Dst);
1289       Bldr.addNodes(Dst);
1290       break;
1291 
1292     case Stmt::StmtExprClass: {
1293       const StmtExpr *SE = cast<StmtExpr>(S);
1294 
1295       if (SE->getSubStmt()->body_empty()) {
1296         // Empty statement expression.
1297         assert(SE->getType() == getContext().VoidTy
1298                && "Empty statement expression must have void type.");
1299         break;
1300       }
1301 
1302       if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1303         ProgramStateRef state = Pred->getState();
1304         Bldr.generateNode(SE, Pred,
1305                           state->BindExpr(SE, Pred->getLocationContext(),
1306                                           state->getSVal(LastExpr,
1307                                                   Pred->getLocationContext())));
1308       }
1309       break;
1310     }
1311 
1312     case Stmt::UnaryOperatorClass: {
1313       Bldr.takeNodes(Pred);
1314       const UnaryOperator *U = cast<UnaryOperator>(S);
1315       if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1316         ExplodedNodeSet Tmp;
1317         VisitUnaryOperator(U, Pred, Tmp);
1318         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1319       }
1320       else
1321         VisitUnaryOperator(U, Pred, Dst);
1322       Bldr.addNodes(Dst);
1323       break;
1324     }
1325 
1326     case Stmt::PseudoObjectExprClass: {
1327       Bldr.takeNodes(Pred);
1328       ProgramStateRef state = Pred->getState();
1329       const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1330       if (const Expr *Result = PE->getResultExpr()) {
1331         SVal V = state->getSVal(Result, Pred->getLocationContext());
1332         Bldr.generateNode(S, Pred,
1333                           state->BindExpr(S, Pred->getLocationContext(), V));
1334       }
1335       else
1336         Bldr.generateNode(S, Pred,
1337                           state->BindExpr(S, Pred->getLocationContext(),
1338                                                    UnknownVal()));
1339 
1340       Bldr.addNodes(Dst);
1341       break;
1342     }
1343   }
1344 }
1345 
1346 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1347                                        const LocationContext *CalleeLC) {
1348   const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1349   const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1350   assert(CalleeSF && CallerSF);
1351   ExplodedNode *BeforeProcessingCall = nullptr;
1352   const Stmt *CE = CalleeSF->getCallSite();
1353 
1354   // Find the first node before we started processing the call expression.
1355   while (N) {
1356     ProgramPoint L = N->getLocation();
1357     BeforeProcessingCall = N;
1358     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1359 
1360     // Skip the nodes corresponding to the inlined code.
1361     if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1362       continue;
1363     // We reached the caller. Find the node right before we started
1364     // processing the call.
1365     if (L.isPurgeKind())
1366       continue;
1367     if (L.getAs<PreImplicitCall>())
1368       continue;
1369     if (L.getAs<CallEnter>())
1370       continue;
1371     if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1372       if (SP->getStmt() == CE)
1373         continue;
1374     break;
1375   }
1376 
1377   if (!BeforeProcessingCall)
1378     return false;
1379 
1380   // TODO: Clean up the unneeded nodes.
1381 
1382   // Build an Epsilon node from which we will restart the analyzes.
1383   // Note that CE is permitted to be NULL!
1384   ProgramPoint NewNodeLoc =
1385                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1386   // Add the special flag to GDM to signal retrying with no inlining.
1387   // Note, changing the state ensures that we are not going to cache out.
1388   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1389   NewNodeState =
1390     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1391 
1392   // Make the new node a successor of BeforeProcessingCall.
1393   bool IsNew = false;
1394   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1395   // We cached out at this point. Caching out is common due to us backtracking
1396   // from the inlined function, which might spawn several paths.
1397   if (!IsNew)
1398     return true;
1399 
1400   NewNode->addPredecessor(BeforeProcessingCall, G);
1401 
1402   // Add the new node to the work list.
1403   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1404                                   CalleeSF->getIndex());
1405   NumTimesRetriedWithoutInlining++;
1406   return true;
1407 }
1408 
1409 /// Block entrance.  (Update counters).
1410 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1411                                          NodeBuilderWithSinks &nodeBuilder,
1412                                          ExplodedNode *Pred) {
1413   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1414 
1415   // If this block is terminated by a loop and it has already been visited the
1416   // maximum number of times, widen the loop.
1417   unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1418   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1419       AMgr.options.shouldWidenLoops()) {
1420     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1421     if (!(Term &&
1422           (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1423       return;
1424     // Widen.
1425     const LocationContext *LCtx = Pred->getLocationContext();
1426     ProgramStateRef WidenedState =
1427         getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1428     nodeBuilder.generateNode(WidenedState, Pred);
1429     return;
1430   }
1431 
1432   // FIXME: Refactor this into a checker.
1433   if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1434     static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1435     const ExplodedNode *Sink =
1436                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1437 
1438     // Check if we stopped at the top level function or not.
1439     // Root node should have the location context of the top most function.
1440     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1441     const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1442     const LocationContext *RootLC =
1443                         (*G.roots_begin())->getLocation().getLocationContext();
1444     if (RootLC->getCurrentStackFrame() != CalleeSF) {
1445       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1446 
1447       // Re-run the call evaluation without inlining it, by storing the
1448       // no-inlining policy in the state and enqueuing the new work item on
1449       // the list. Replay should almost never fail. Use the stats to catch it
1450       // if it does.
1451       if ((!AMgr.options.NoRetryExhausted &&
1452            replayWithoutInlining(Pred, CalleeLC)))
1453         return;
1454       NumMaxBlockCountReachedInInlined++;
1455     } else
1456       NumMaxBlockCountReached++;
1457 
1458     // Make sink nodes as exhausted(for stats) only if retry failed.
1459     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1460   }
1461 }
1462 
1463 //===----------------------------------------------------------------------===//
1464 // Branch processing.
1465 //===----------------------------------------------------------------------===//
1466 
1467 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1468 /// to try to recover some path-sensitivity for casts of symbolic
1469 /// integers that promote their values (which are currently not tracked well).
1470 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1471 //  cast(s) did was sign-extend the original value.
1472 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1473                                 ProgramStateRef state,
1474                                 const Stmt *Condition,
1475                                 const LocationContext *LCtx,
1476                                 ASTContext &Ctx) {
1477 
1478   const Expr *Ex = dyn_cast<Expr>(Condition);
1479   if (!Ex)
1480     return UnknownVal();
1481 
1482   uint64_t bits = 0;
1483   bool bitsInit = false;
1484 
1485   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1486     QualType T = CE->getType();
1487 
1488     if (!T->isIntegralOrEnumerationType())
1489       return UnknownVal();
1490 
1491     uint64_t newBits = Ctx.getTypeSize(T);
1492     if (!bitsInit || newBits < bits) {
1493       bitsInit = true;
1494       bits = newBits;
1495     }
1496 
1497     Ex = CE->getSubExpr();
1498   }
1499 
1500   // We reached a non-cast.  Is it a symbolic value?
1501   QualType T = Ex->getType();
1502 
1503   if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1504       Ctx.getTypeSize(T) > bits)
1505     return UnknownVal();
1506 
1507   return state->getSVal(Ex, LCtx);
1508 }
1509 
1510 #ifndef NDEBUG
1511 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1512   while (Condition) {
1513     const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1514     if (!BO || !BO->isLogicalOp()) {
1515       return Condition;
1516     }
1517     Condition = BO->getRHS()->IgnoreParens();
1518   }
1519   return nullptr;
1520 }
1521 #endif
1522 
1523 // Returns the condition the branch at the end of 'B' depends on and whose value
1524 // has been evaluated within 'B'.
1525 // In most cases, the terminator condition of 'B' will be evaluated fully in
1526 // the last statement of 'B'; in those cases, the resolved condition is the
1527 // given 'Condition'.
1528 // If the condition of the branch is a logical binary operator tree, the CFG is
1529 // optimized: in that case, we know that the expression formed by all but the
1530 // rightmost leaf of the logical binary operator tree must be true, and thus
1531 // the branch condition is at this point equivalent to the truth value of that
1532 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1533 // expression in its final statement. As the full condition in that case was
1534 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1535 // expression to evaluate the truth value of the condition in the current state
1536 // space.
1537 static const Stmt *ResolveCondition(const Stmt *Condition,
1538                                     const CFGBlock *B) {
1539   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1540     Condition = Ex->IgnoreParens();
1541 
1542   const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1543   if (!BO || !BO->isLogicalOp())
1544     return Condition;
1545 
1546   assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1547          "Temporary destructor branches handled by processBindTemporary.");
1548 
1549   // For logical operations, we still have the case where some branches
1550   // use the traditional "merge" approach and others sink the branch
1551   // directly into the basic blocks representing the logical operation.
1552   // We need to distinguish between those two cases here.
1553 
1554   // The invariants are still shifting, but it is possible that the
1555   // last element in a CFGBlock is not a CFGStmt.  Look for the last
1556   // CFGStmt as the value of the condition.
1557   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1558   for (; I != E; ++I) {
1559     CFGElement Elem = *I;
1560     Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1561     if (!CS)
1562       continue;
1563     const Stmt *LastStmt = CS->getStmt();
1564     assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1565     return LastStmt;
1566   }
1567   llvm_unreachable("could not resolve condition");
1568 }
1569 
1570 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1571                                NodeBuilderContext& BldCtx,
1572                                ExplodedNode *Pred,
1573                                ExplodedNodeSet &Dst,
1574                                const CFGBlock *DstT,
1575                                const CFGBlock *DstF) {
1576   assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1577          "CXXBindTemporaryExprs are handled by processBindTemporary.");
1578   const LocationContext *LCtx = Pred->getLocationContext();
1579   PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1580   currBldrCtx = &BldCtx;
1581 
1582   // Check for NULL conditions; e.g. "for(;;)"
1583   if (!Condition) {
1584     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1585     NullCondBldr.markInfeasible(false);
1586     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1587     return;
1588   }
1589 
1590   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1591     Condition = Ex->IgnoreParens();
1592 
1593   Condition = ResolveCondition(Condition, BldCtx.getBlock());
1594   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1595                                 Condition->getLocStart(),
1596                                 "Error evaluating branch");
1597 
1598   ExplodedNodeSet CheckersOutSet;
1599   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1600                                                     Pred, *this);
1601   // We generated only sinks.
1602   if (CheckersOutSet.empty())
1603     return;
1604 
1605   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1606   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1607                              E = CheckersOutSet.end(); E != I; ++I) {
1608     ExplodedNode *PredI = *I;
1609 
1610     if (PredI->isSink())
1611       continue;
1612 
1613     ProgramStateRef PrevState = PredI->getState();
1614     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1615 
1616     if (X.isUnknownOrUndef()) {
1617       // Give it a chance to recover from unknown.
1618       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1619         if (Ex->getType()->isIntegralOrEnumerationType()) {
1620           // Try to recover some path-sensitivity.  Right now casts of symbolic
1621           // integers that promote their values are currently not tracked well.
1622           // If 'Condition' is such an expression, try and recover the
1623           // underlying value and use that instead.
1624           SVal recovered = RecoverCastedSymbol(getStateManager(),
1625                                                PrevState, Condition,
1626                                                PredI->getLocationContext(),
1627                                                getContext());
1628 
1629           if (!recovered.isUnknown()) {
1630             X = recovered;
1631           }
1632         }
1633       }
1634     }
1635 
1636     // If the condition is still unknown, give up.
1637     if (X.isUnknownOrUndef()) {
1638       builder.generateNode(PrevState, true, PredI);
1639       builder.generateNode(PrevState, false, PredI);
1640       continue;
1641     }
1642 
1643     DefinedSVal V = X.castAs<DefinedSVal>();
1644 
1645     ProgramStateRef StTrue, StFalse;
1646     std::tie(StTrue, StFalse) = PrevState->assume(V);
1647 
1648     // Process the true branch.
1649     if (builder.isFeasible(true)) {
1650       if (StTrue)
1651         builder.generateNode(StTrue, true, PredI);
1652       else
1653         builder.markInfeasible(true);
1654     }
1655 
1656     // Process the false branch.
1657     if (builder.isFeasible(false)) {
1658       if (StFalse)
1659         builder.generateNode(StFalse, false, PredI);
1660       else
1661         builder.markInfeasible(false);
1662     }
1663   }
1664   currBldrCtx = nullptr;
1665 }
1666 
1667 /// The GDM component containing the set of global variables which have been
1668 /// previously initialized with explicit initializers.
1669 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1670                                  llvm::ImmutableSet<const VarDecl *>)
1671 
1672 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1673                                           NodeBuilderContext &BuilderCtx,
1674                                           ExplodedNode *Pred,
1675                                           clang::ento::ExplodedNodeSet &Dst,
1676                                           const CFGBlock *DstT,
1677                                           const CFGBlock *DstF) {
1678   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1679   currBldrCtx = &BuilderCtx;
1680 
1681   const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1682   ProgramStateRef state = Pred->getState();
1683   bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1684   BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1685 
1686   if (!initHasRun) {
1687     state = state->add<InitializedGlobalsSet>(VD);
1688   }
1689 
1690   builder.generateNode(state, initHasRun, Pred);
1691   builder.markInfeasible(!initHasRun);
1692 
1693   currBldrCtx = nullptr;
1694 }
1695 
1696 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1697 ///  nodes by processing the 'effects' of a computed goto jump.
1698 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1699 
1700   ProgramStateRef state = builder.getState();
1701   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1702 
1703   // Three possibilities:
1704   //
1705   //   (1) We know the computed label.
1706   //   (2) The label is NULL (or some other constant), or Undefined.
1707   //   (3) We have no clue about the label.  Dispatch to all targets.
1708   //
1709 
1710   typedef IndirectGotoNodeBuilder::iterator iterator;
1711 
1712   if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1713     const LabelDecl *L = LV->getLabel();
1714 
1715     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1716       if (I.getLabel() == L) {
1717         builder.generateNode(I, state);
1718         return;
1719       }
1720     }
1721 
1722     llvm_unreachable("No block with label.");
1723   }
1724 
1725   if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1726     // Dispatch to the first target and mark it as a sink.
1727     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1728     // FIXME: add checker visit.
1729     //    UndefBranches.insert(N);
1730     return;
1731   }
1732 
1733   // This is really a catch-all.  We don't support symbolics yet.
1734   // FIXME: Implement dispatch for symbolic pointers.
1735 
1736   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1737     builder.generateNode(I, state);
1738 }
1739 
1740 #if 0
1741 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1742   const StackFrameContext* Frame = Pred.getStackFrame();
1743   const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1744       Pred.getState()->get<InitializedTemporariesSet>();
1745   return std::find_if(Set.begin(), Set.end(),
1746                       [&](const CXXBindTemporaryContext &Ctx) {
1747                         if (Ctx.second == Frame) {
1748                           Ctx.first->dump();
1749                           llvm::errs() << "\n";
1750                         }
1751            return Ctx.second == Frame;
1752          }) == Set.end();
1753 }
1754 #endif
1755 
1756 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
1757                                         ExplodedNode *Pred,
1758                                         ExplodedNodeSet &Dst,
1759                                         const BlockEdge &L) {
1760   SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1761   getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1762 }
1763 
1764 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1765 ///  nodes when the control reaches the end of a function.
1766 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1767                                       ExplodedNode *Pred) {
1768   // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1769   // We currently cannot enable this assert, as lifetime extended temporaries
1770   // are not modelled correctly.
1771   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1772   StateMgr.EndPath(Pred->getState());
1773 
1774   ExplodedNodeSet Dst;
1775   if (Pred->getLocationContext()->inTopFrame()) {
1776     // Remove dead symbols.
1777     ExplodedNodeSet AfterRemovedDead;
1778     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1779 
1780     // Notify checkers.
1781     for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1782         E = AfterRemovedDead.end(); I != E; ++I) {
1783       getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1784     }
1785   } else {
1786     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1787   }
1788 
1789   Engine.enqueueEndOfFunction(Dst);
1790 }
1791 
1792 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1793 ///  nodes by processing the 'effects' of a switch statement.
1794 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1795   typedef SwitchNodeBuilder::iterator iterator;
1796   ProgramStateRef state = builder.getState();
1797   const Expr *CondE = builder.getCondition();
1798   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1799 
1800   if (CondV_untested.isUndef()) {
1801     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1802     // FIXME: add checker
1803     //UndefBranches.insert(N);
1804 
1805     return;
1806   }
1807   DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1808 
1809   ProgramStateRef DefaultSt = state;
1810 
1811   iterator I = builder.begin(), EI = builder.end();
1812   bool defaultIsFeasible = I == EI;
1813 
1814   for ( ; I != EI; ++I) {
1815     // Successor may be pruned out during CFG construction.
1816     if (!I.getBlock())
1817       continue;
1818 
1819     const CaseStmt *Case = I.getCase();
1820 
1821     // Evaluate the LHS of the case value.
1822     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1823     assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1824 
1825     // Get the RHS of the case, if it exists.
1826     llvm::APSInt V2;
1827     if (const Expr *E = Case->getRHS())
1828       V2 = E->EvaluateKnownConstInt(getContext());
1829     else
1830       V2 = V1;
1831 
1832     ProgramStateRef StateCase;
1833     if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1834       std::tie(StateCase, DefaultSt) =
1835           DefaultSt->assumeWithinInclusiveRange(*NL, V1, V2);
1836     else // UnknownVal
1837       StateCase = DefaultSt;
1838 
1839     if (StateCase)
1840       builder.generateCaseStmtNode(I, StateCase);
1841 
1842     // Now "assume" that the case doesn't match.  Add this state
1843     // to the default state (if it is feasible).
1844     if (DefaultSt)
1845       defaultIsFeasible = true;
1846     else {
1847       defaultIsFeasible = false;
1848       break;
1849     }
1850   }
1851 
1852   if (!defaultIsFeasible)
1853     return;
1854 
1855   // If we have switch(enum value), the default branch is not
1856   // feasible if all of the enum constants not covered by 'case:' statements
1857   // are not feasible values for the switch condition.
1858   //
1859   // Note that this isn't as accurate as it could be.  Even if there isn't
1860   // a case for a particular enum value as long as that enum value isn't
1861   // feasible then it shouldn't be considered for making 'default:' reachable.
1862   const SwitchStmt *SS = builder.getSwitch();
1863   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1864   if (CondExpr->getType()->getAs<EnumType>()) {
1865     if (SS->isAllEnumCasesCovered())
1866       return;
1867   }
1868 
1869   builder.generateDefaultCaseNode(DefaultSt);
1870 }
1871 
1872 //===----------------------------------------------------------------------===//
1873 // Transfer functions: Loads and stores.
1874 //===----------------------------------------------------------------------===//
1875 
1876 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1877                                         ExplodedNode *Pred,
1878                                         ExplodedNodeSet &Dst) {
1879   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1880 
1881   ProgramStateRef state = Pred->getState();
1882   const LocationContext *LCtx = Pred->getLocationContext();
1883 
1884   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1885     // C permits "extern void v", and if you cast the address to a valid type,
1886     // you can even do things with it. We simply pretend
1887     assert(Ex->isGLValue() || VD->getType()->isVoidType());
1888     const LocationContext *LocCtxt = Pred->getLocationContext();
1889     const Decl *D = LocCtxt->getDecl();
1890     const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
1891     const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
1892     SVal V;
1893     bool IsReference;
1894     if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
1895         DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
1896         MD->getParent()->isLambda()) {
1897       // Lookup the field of the lambda.
1898       const CXXRecordDecl *CXXRec = MD->getParent();
1899       llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
1900       FieldDecl *LambdaThisCaptureField;
1901       CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
1902       const FieldDecl *FD = LambdaCaptureFields[VD];
1903       if (!FD) {
1904         // When a constant is captured, sometimes no corresponding field is
1905         // created in the lambda object.
1906         assert(VD->getType().isConstQualified());
1907         V = state->getLValue(VD, LocCtxt);
1908         IsReference = false;
1909       } else {
1910         Loc CXXThis =
1911             svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
1912         SVal CXXThisVal = state->getSVal(CXXThis);
1913         V = state->getLValue(FD, CXXThisVal);
1914         IsReference = FD->getType()->isReferenceType();
1915       }
1916     } else {
1917       V = state->getLValue(VD, LocCtxt);
1918       IsReference = VD->getType()->isReferenceType();
1919     }
1920 
1921     // For references, the 'lvalue' is the pointer address stored in the
1922     // reference region.
1923     if (IsReference) {
1924       if (const MemRegion *R = V.getAsRegion())
1925         V = state->getSVal(R);
1926       else
1927         V = UnknownVal();
1928     }
1929 
1930     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1931                       ProgramPoint::PostLValueKind);
1932     return;
1933   }
1934   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1935     assert(!Ex->isGLValue());
1936     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1937     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1938     return;
1939   }
1940   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1941     SVal V = svalBuilder.getFunctionPointer(FD);
1942     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1943                       ProgramPoint::PostLValueKind);
1944     return;
1945   }
1946   if (isa<FieldDecl>(D)) {
1947     // FIXME: Compute lvalue of field pointers-to-member.
1948     // Right now we just use a non-null void pointer, so that it gives proper
1949     // results in boolean contexts.
1950     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1951                                           currBldrCtx->blockCount());
1952     state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1953     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1954 		      ProgramPoint::PostLValueKind);
1955     return;
1956   }
1957 
1958   llvm_unreachable("Support for this Decl not implemented.");
1959 }
1960 
1961 /// VisitArraySubscriptExpr - Transfer function for array accesses
1962 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1963                                              ExplodedNode *Pred,
1964                                              ExplodedNodeSet &Dst){
1965 
1966   const Expr *Base = A->getBase()->IgnoreParens();
1967   const Expr *Idx  = A->getIdx()->IgnoreParens();
1968 
1969   ExplodedNodeSet checkerPreStmt;
1970   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1971 
1972   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1973   assert(A->isGLValue() ||
1974           (!AMgr.getLangOpts().CPlusPlus &&
1975            A->getType().isCForbiddenLValueType()));
1976 
1977   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1978                                  ei = checkerPreStmt.end(); it != ei; ++it) {
1979     const LocationContext *LCtx = (*it)->getLocationContext();
1980     ProgramStateRef state = (*it)->getState();
1981     SVal V = state->getLValue(A->getType(),
1982                               state->getSVal(Idx, LCtx),
1983                               state->getSVal(Base, LCtx));
1984     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1985                       ProgramPoint::PostLValueKind);
1986   }
1987 }
1988 
1989 /// VisitMemberExpr - Transfer function for member expressions.
1990 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1991                                  ExplodedNodeSet &Dst) {
1992 
1993   // FIXME: Prechecks eventually go in ::Visit().
1994   ExplodedNodeSet CheckedSet;
1995   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
1996 
1997   ExplodedNodeSet EvalSet;
1998   ValueDecl *Member = M->getMemberDecl();
1999 
2000   // Handle static member variables and enum constants accessed via
2001   // member syntax.
2002   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2003     ExplodedNodeSet Dst;
2004     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2005          I != E; ++I) {
2006       VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2007     }
2008   } else {
2009     StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2010     ExplodedNodeSet Tmp;
2011 
2012     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2013          I != E; ++I) {
2014       ProgramStateRef state = (*I)->getState();
2015       const LocationContext *LCtx = (*I)->getLocationContext();
2016       Expr *BaseExpr = M->getBase();
2017 
2018       // Handle C++ method calls.
2019       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2020         if (MD->isInstance())
2021           state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2022 
2023         SVal MDVal = svalBuilder.getFunctionPointer(MD);
2024         state = state->BindExpr(M, LCtx, MDVal);
2025 
2026         Bldr.generateNode(M, *I, state);
2027         continue;
2028       }
2029 
2030       // Handle regular struct fields / member variables.
2031       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2032       SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2033 
2034       FieldDecl *field = cast<FieldDecl>(Member);
2035       SVal L = state->getLValue(field, baseExprVal);
2036 
2037       if (M->isGLValue() || M->getType()->isArrayType()) {
2038         // We special-case rvalues of array type because the analyzer cannot
2039         // reason about them, since we expect all regions to be wrapped in Locs.
2040         // We instead treat these as lvalues and assume that they will decay to
2041         // pointers as soon as they are used.
2042         if (!M->isGLValue()) {
2043           assert(M->getType()->isArrayType());
2044           const ImplicitCastExpr *PE =
2045             dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
2046           if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2047             llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2048           }
2049         }
2050 
2051         if (field->getType()->isReferenceType()) {
2052           if (const MemRegion *R = L.getAsRegion())
2053             L = state->getSVal(R);
2054           else
2055             L = UnknownVal();
2056         }
2057 
2058         Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2059                           ProgramPoint::PostLValueKind);
2060       } else {
2061         Bldr.takeNodes(*I);
2062         evalLoad(Tmp, M, M, *I, state, L);
2063         Bldr.addNodes(Tmp);
2064       }
2065     }
2066   }
2067 
2068   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2069 }
2070 
2071 namespace {
2072 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2073   InvalidatedSymbols Symbols;
2074 
2075 public:
2076   CollectReachableSymbolsCallback(ProgramStateRef State) {}
2077   const InvalidatedSymbols &getSymbols() const { return Symbols; }
2078 
2079   bool VisitSymbol(SymbolRef Sym) override {
2080     Symbols.insert(Sym);
2081     return true;
2082   }
2083 };
2084 } // end anonymous namespace
2085 
2086 // A value escapes in three possible cases:
2087 // (1) We are binding to something that is not a memory region.
2088 // (2) We are binding to a MemrRegion that does not have stack storage.
2089 // (3) We are binding to a MemRegion with stack storage that the store
2090 //     does not understand.
2091 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2092                                                         SVal Loc, SVal Val) {
2093   // Are we storing to something that causes the value to "escape"?
2094   bool escapes = true;
2095 
2096   // TODO: Move to StoreManager.
2097   if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2098     escapes = !regionLoc->getRegion()->hasStackStorage();
2099 
2100     if (!escapes) {
2101       // To test (3), generate a new state with the binding added.  If it is
2102       // the same state, then it escapes (since the store cannot represent
2103       // the binding).
2104       // Do this only if we know that the store is not supposed to generate the
2105       // same state.
2106       SVal StoredVal = State->getSVal(regionLoc->getRegion());
2107       if (StoredVal != Val)
2108         escapes = (State == (State->bindLoc(*regionLoc, Val)));
2109     }
2110   }
2111 
2112   // If our store can represent the binding and we aren't storing to something
2113   // that doesn't have local storage then just return and have the simulation
2114   // state continue as is.
2115   if (!escapes)
2116     return State;
2117 
2118   // Otherwise, find all symbols referenced by 'val' that we are tracking
2119   // and stop tracking them.
2120   CollectReachableSymbolsCallback Scanner =
2121       State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2122   const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2123   State = getCheckerManager().runCheckersForPointerEscape(State,
2124                                                           EscapedSymbols,
2125                                                           /*CallEvent*/ nullptr,
2126                                                           PSK_EscapeOnBind,
2127                                                           nullptr);
2128 
2129   return State;
2130 }
2131 
2132 ProgramStateRef
2133 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2134     const InvalidatedSymbols *Invalidated,
2135     ArrayRef<const MemRegion *> ExplicitRegions,
2136     ArrayRef<const MemRegion *> Regions,
2137     const CallEvent *Call,
2138     RegionAndSymbolInvalidationTraits &ITraits) {
2139 
2140   if (!Invalidated || Invalidated->empty())
2141     return State;
2142 
2143   if (!Call)
2144     return getCheckerManager().runCheckersForPointerEscape(State,
2145                                                            *Invalidated,
2146                                                            nullptr,
2147                                                            PSK_EscapeOther,
2148                                                            &ITraits);
2149 
2150   // If the symbols were invalidated by a call, we want to find out which ones
2151   // were invalidated directly due to being arguments to the call.
2152   InvalidatedSymbols SymbolsDirectlyInvalidated;
2153   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2154       E = ExplicitRegions.end(); I != E; ++I) {
2155     if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2156       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2157   }
2158 
2159   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2160   for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2161       E = Invalidated->end(); I!=E; ++I) {
2162     SymbolRef sym = *I;
2163     if (SymbolsDirectlyInvalidated.count(sym))
2164       continue;
2165     SymbolsIndirectlyInvalidated.insert(sym);
2166   }
2167 
2168   if (!SymbolsDirectlyInvalidated.empty())
2169     State = getCheckerManager().runCheckersForPointerEscape(State,
2170         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2171 
2172   // Notify about the symbols that get indirectly invalidated by the call.
2173   if (!SymbolsIndirectlyInvalidated.empty())
2174     State = getCheckerManager().runCheckersForPointerEscape(State,
2175         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2176 
2177   return State;
2178 }
2179 
2180 /// evalBind - Handle the semantics of binding a value to a specific location.
2181 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2182 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2183                           ExplodedNode *Pred,
2184                           SVal location, SVal Val,
2185                           bool atDeclInit, const ProgramPoint *PP) {
2186 
2187   const LocationContext *LC = Pred->getLocationContext();
2188   PostStmt PS(StoreE, LC);
2189   if (!PP)
2190     PP = &PS;
2191 
2192   // Do a previsit of the bind.
2193   ExplodedNodeSet CheckedSet;
2194   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2195                                          StoreE, *this, *PP);
2196 
2197   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2198 
2199   // If the location is not a 'Loc', it will already be handled by
2200   // the checkers.  There is nothing left to do.
2201   if (!location.getAs<Loc>()) {
2202     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2203                                      /*tag*/nullptr);
2204     ProgramStateRef state = Pred->getState();
2205     state = processPointerEscapedOnBind(state, location, Val);
2206     Bldr.generateNode(L, state, Pred);
2207     return;
2208   }
2209 
2210   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2211        I!=E; ++I) {
2212     ExplodedNode *PredI = *I;
2213     ProgramStateRef state = PredI->getState();
2214 
2215     state = processPointerEscapedOnBind(state, location, Val);
2216 
2217     // When binding the value, pass on the hint that this is a initialization.
2218     // For initializations, we do not need to inform clients of region
2219     // changes.
2220     state = state->bindLoc(location.castAs<Loc>(),
2221                            Val, /* notifyChanges = */ !atDeclInit);
2222 
2223     const MemRegion *LocReg = nullptr;
2224     if (Optional<loc::MemRegionVal> LocRegVal =
2225             location.getAs<loc::MemRegionVal>()) {
2226       LocReg = LocRegVal->getRegion();
2227     }
2228 
2229     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2230     Bldr.generateNode(L, state, PredI);
2231   }
2232 }
2233 
2234 /// evalStore - Handle the semantics of a store via an assignment.
2235 ///  @param Dst The node set to store generated state nodes
2236 ///  @param AssignE The assignment expression if the store happens in an
2237 ///         assignment.
2238 ///  @param LocationE The location expression that is stored to.
2239 ///  @param state The current simulation state
2240 ///  @param location The location to store the value
2241 ///  @param Val The value to be stored
2242 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2243                              const Expr *LocationE,
2244                              ExplodedNode *Pred,
2245                              ProgramStateRef state, SVal location, SVal Val,
2246                              const ProgramPointTag *tag) {
2247   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2248   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2249   const Expr *StoreE = AssignE ? AssignE : LocationE;
2250 
2251   // Evaluate the location (checks for bad dereferences).
2252   ExplodedNodeSet Tmp;
2253   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2254 
2255   if (Tmp.empty())
2256     return;
2257 
2258   if (location.isUndef())
2259     return;
2260 
2261   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2262     evalBind(Dst, StoreE, *NI, location, Val, false);
2263 }
2264 
2265 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2266                           const Expr *NodeEx,
2267                           const Expr *BoundEx,
2268                           ExplodedNode *Pred,
2269                           ProgramStateRef state,
2270                           SVal location,
2271                           const ProgramPointTag *tag,
2272                           QualType LoadTy)
2273 {
2274   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2275 
2276   // Are we loading from a region?  This actually results in two loads; one
2277   // to fetch the address of the referenced value and one to fetch the
2278   // referenced value.
2279   if (const TypedValueRegion *TR =
2280         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2281 
2282     QualType ValTy = TR->getValueType();
2283     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2284       static SimpleProgramPointTag
2285              loadReferenceTag(TagProviderName, "Load Reference");
2286       ExplodedNodeSet Tmp;
2287       evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2288                      location, &loadReferenceTag,
2289                      getContext().getPointerType(RT->getPointeeType()));
2290 
2291       // Perform the load from the referenced value.
2292       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2293         state = (*I)->getState();
2294         location = state->getSVal(BoundEx, (*I)->getLocationContext());
2295         evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2296       }
2297       return;
2298     }
2299   }
2300 
2301   evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2302 }
2303 
2304 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2305                                 const Expr *NodeEx,
2306                                 const Expr *BoundEx,
2307                                 ExplodedNode *Pred,
2308                                 ProgramStateRef state,
2309                                 SVal location,
2310                                 const ProgramPointTag *tag,
2311                                 QualType LoadTy) {
2312   assert(NodeEx);
2313   assert(BoundEx);
2314   // Evaluate the location (checks for bad dereferences).
2315   ExplodedNodeSet Tmp;
2316   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2317   if (Tmp.empty())
2318     return;
2319 
2320   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2321   if (location.isUndef())
2322     return;
2323 
2324   // Proceed with the load.
2325   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2326     state = (*NI)->getState();
2327     const LocationContext *LCtx = (*NI)->getLocationContext();
2328 
2329     SVal V = UnknownVal();
2330     if (location.isValid()) {
2331       if (LoadTy.isNull())
2332         LoadTy = BoundEx->getType();
2333       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2334     }
2335 
2336     Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2337                       ProgramPoint::PostLoadKind);
2338   }
2339 }
2340 
2341 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2342                               const Stmt *NodeEx,
2343                               const Stmt *BoundEx,
2344                               ExplodedNode *Pred,
2345                               ProgramStateRef state,
2346                               SVal location,
2347                               const ProgramPointTag *tag,
2348                               bool isLoad) {
2349   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2350   // Early checks for performance reason.
2351   if (location.isUnknown()) {
2352     return;
2353   }
2354 
2355   ExplodedNodeSet Src;
2356   BldrTop.takeNodes(Pred);
2357   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2358   if (Pred->getState() != state) {
2359     // Associate this new state with an ExplodedNode.
2360     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2361     //   int *p;
2362     //   p = 0;
2363     //   *p = 0xDEADBEEF;
2364     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2365     // instead "int *p" is noted as
2366     // "Variable 'p' initialized to a null pointer value"
2367 
2368     static SimpleProgramPointTag tag(TagProviderName, "Location");
2369     Bldr.generateNode(NodeEx, Pred, state, &tag);
2370   }
2371   ExplodedNodeSet Tmp;
2372   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2373                                              NodeEx, BoundEx, *this);
2374   BldrTop.addNodes(Tmp);
2375 }
2376 
2377 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2378 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2379   static SimpleProgramPointTag
2380          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2381                                            "Eagerly Assume True"),
2382          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2383                                             "Eagerly Assume False");
2384   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2385                         &eagerlyAssumeBinOpBifurcationFalse);
2386 }
2387 
2388 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2389                                                    ExplodedNodeSet &Src,
2390                                                    const Expr *Ex) {
2391   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2392 
2393   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2394     ExplodedNode *Pred = *I;
2395     // Test if the previous node was as the same expression.  This can happen
2396     // when the expression fails to evaluate to anything meaningful and
2397     // (as an optimization) we don't generate a node.
2398     ProgramPoint P = Pred->getLocation();
2399     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2400       continue;
2401     }
2402 
2403     ProgramStateRef state = Pred->getState();
2404     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2405     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2406     if (SEV && SEV->isExpression()) {
2407       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2408         geteagerlyAssumeBinOpBifurcationTags();
2409 
2410       ProgramStateRef StateTrue, StateFalse;
2411       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2412 
2413       // First assume that the condition is true.
2414       if (StateTrue) {
2415         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2416         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2417         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2418       }
2419 
2420       // Next, assume that the condition is false.
2421       if (StateFalse) {
2422         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2423         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2424         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2425       }
2426     }
2427   }
2428 }
2429 
2430 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2431                                  ExplodedNodeSet &Dst) {
2432   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2433   // We have processed both the inputs and the outputs.  All of the outputs
2434   // should evaluate to Locs.  Nuke all of their values.
2435 
2436   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2437   // which interprets the inline asm and stores proper results in the
2438   // outputs.
2439 
2440   ProgramStateRef state = Pred->getState();
2441 
2442   for (const Expr *O : A->outputs()) {
2443     SVal X = state->getSVal(O, Pred->getLocationContext());
2444     assert (!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2445 
2446     if (Optional<Loc> LV = X.getAs<Loc>())
2447       state = state->bindLoc(*LV, UnknownVal());
2448   }
2449 
2450   Bldr.generateNode(A, Pred, state);
2451 }
2452 
2453 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2454                                 ExplodedNodeSet &Dst) {
2455   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2456   Bldr.generateNode(A, Pred, Pred->getState());
2457 }
2458 
2459 //===----------------------------------------------------------------------===//
2460 // Visualization.
2461 //===----------------------------------------------------------------------===//
2462 
2463 #ifndef NDEBUG
2464 static ExprEngine* GraphPrintCheckerState;
2465 static SourceManager* GraphPrintSourceManager;
2466 
2467 namespace llvm {
2468 template<>
2469 struct DOTGraphTraits<ExplodedNode*> :
2470   public DefaultDOTGraphTraits {
2471 
2472   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2473 
2474   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2475   // work.
2476   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2477 
2478 #if 0
2479       // FIXME: Replace with a general scheme to tell if the node is
2480       // an error node.
2481     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2482         GraphPrintCheckerState->isExplicitNullDeref(N) ||
2483         GraphPrintCheckerState->isUndefDeref(N) ||
2484         GraphPrintCheckerState->isUndefStore(N) ||
2485         GraphPrintCheckerState->isUndefControlFlow(N) ||
2486         GraphPrintCheckerState->isUndefResult(N) ||
2487         GraphPrintCheckerState->isBadCall(N) ||
2488         GraphPrintCheckerState->isUndefArg(N))
2489       return "color=\"red\",style=\"filled\"";
2490 
2491     if (GraphPrintCheckerState->isNoReturnCall(N))
2492       return "color=\"blue\",style=\"filled\"";
2493 #endif
2494     return "";
2495   }
2496 
2497   static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2498     if (SLoc.isFileID()) {
2499       Out << "\\lline="
2500         << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2501         << " col="
2502         << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2503         << "\\l";
2504     }
2505   }
2506 
2507   static std::string getNodeLabel(const ExplodedNode *N, void*){
2508 
2509     std::string sbuf;
2510     llvm::raw_string_ostream Out(sbuf);
2511 
2512     // Program Location.
2513     ProgramPoint Loc = N->getLocation();
2514 
2515     switch (Loc.getKind()) {
2516       case ProgramPoint::BlockEntranceKind: {
2517         Out << "Block Entrance: B"
2518             << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2519         if (const NamedDecl *ND =
2520                     dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2521           Out << " (";
2522           ND->printName(Out);
2523           Out << ")";
2524         }
2525         break;
2526       }
2527 
2528       case ProgramPoint::BlockExitKind:
2529         assert (false);
2530         break;
2531 
2532       case ProgramPoint::CallEnterKind:
2533         Out << "CallEnter";
2534         break;
2535 
2536       case ProgramPoint::CallExitBeginKind:
2537         Out << "CallExitBegin";
2538         break;
2539 
2540       case ProgramPoint::CallExitEndKind:
2541         Out << "CallExitEnd";
2542         break;
2543 
2544       case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2545         Out << "PostStmtPurgeDeadSymbols";
2546         break;
2547 
2548       case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2549         Out << "PreStmtPurgeDeadSymbols";
2550         break;
2551 
2552       case ProgramPoint::EpsilonKind:
2553         Out << "Epsilon Point";
2554         break;
2555 
2556       case ProgramPoint::PreImplicitCallKind: {
2557         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2558         Out << "PreCall: ";
2559 
2560         // FIXME: Get proper printing options.
2561         PC.getDecl()->print(Out, LangOptions());
2562         printLocation(Out, PC.getLocation());
2563         break;
2564       }
2565 
2566       case ProgramPoint::PostImplicitCallKind: {
2567         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2568         Out << "PostCall: ";
2569 
2570         // FIXME: Get proper printing options.
2571         PC.getDecl()->print(Out, LangOptions());
2572         printLocation(Out, PC.getLocation());
2573         break;
2574       }
2575 
2576       case ProgramPoint::PostInitializerKind: {
2577         Out << "PostInitializer: ";
2578         const CXXCtorInitializer *Init =
2579           Loc.castAs<PostInitializer>().getInitializer();
2580         if (const FieldDecl *FD = Init->getAnyMember())
2581           Out << *FD;
2582         else {
2583           QualType Ty = Init->getTypeSourceInfo()->getType();
2584           Ty = Ty.getLocalUnqualifiedType();
2585           LangOptions LO; // FIXME.
2586           Ty.print(Out, LO);
2587         }
2588         break;
2589       }
2590 
2591       case ProgramPoint::BlockEdgeKind: {
2592         const BlockEdge &E = Loc.castAs<BlockEdge>();
2593         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2594             << E.getDst()->getBlockID()  << ')';
2595 
2596         if (const Stmt *T = E.getSrc()->getTerminator()) {
2597           SourceLocation SLoc = T->getLocStart();
2598 
2599           Out << "\\|Terminator: ";
2600           LangOptions LO; // FIXME.
2601           E.getSrc()->printTerminator(Out, LO);
2602 
2603           if (SLoc.isFileID()) {
2604             Out << "\\lline="
2605               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2606               << " col="
2607               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2608           }
2609 
2610           if (isa<SwitchStmt>(T)) {
2611             const Stmt *Label = E.getDst()->getLabel();
2612 
2613             if (Label) {
2614               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2615                 Out << "\\lcase ";
2616                 LangOptions LO; // FIXME.
2617                 if (C->getLHS())
2618                   C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2619 
2620                 if (const Stmt *RHS = C->getRHS()) {
2621                   Out << " .. ";
2622                   RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2623                 }
2624 
2625                 Out << ":";
2626               }
2627               else {
2628                 assert (isa<DefaultStmt>(Label));
2629                 Out << "\\ldefault:";
2630               }
2631             }
2632             else
2633               Out << "\\l(implicit) default:";
2634           }
2635           else if (isa<IndirectGotoStmt>(T)) {
2636             // FIXME
2637           }
2638           else {
2639             Out << "\\lCondition: ";
2640             if (*E.getSrc()->succ_begin() == E.getDst())
2641               Out << "true";
2642             else
2643               Out << "false";
2644           }
2645 
2646           Out << "\\l";
2647         }
2648 
2649 #if 0
2650           // FIXME: Replace with a general scheme to determine
2651           // the name of the check.
2652         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2653           Out << "\\|Control-flow based on\\lUndefined value.\\l";
2654         }
2655 #endif
2656         break;
2657       }
2658 
2659       default: {
2660         const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2661         assert(S != nullptr && "Expecting non-null Stmt");
2662 
2663         Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2664         LangOptions LO; // FIXME.
2665         S->printPretty(Out, nullptr, PrintingPolicy(LO));
2666         printLocation(Out, S->getLocStart());
2667 
2668         if (Loc.getAs<PreStmt>())
2669           Out << "\\lPreStmt\\l;";
2670         else if (Loc.getAs<PostLoad>())
2671           Out << "\\lPostLoad\\l;";
2672         else if (Loc.getAs<PostStore>())
2673           Out << "\\lPostStore\\l";
2674         else if (Loc.getAs<PostLValue>())
2675           Out << "\\lPostLValue\\l";
2676 
2677 #if 0
2678           // FIXME: Replace with a general scheme to determine
2679           // the name of the check.
2680         if (GraphPrintCheckerState->isImplicitNullDeref(N))
2681           Out << "\\|Implicit-Null Dereference.\\l";
2682         else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2683           Out << "\\|Explicit-Null Dereference.\\l";
2684         else if (GraphPrintCheckerState->isUndefDeref(N))
2685           Out << "\\|Dereference of undefialied value.\\l";
2686         else if (GraphPrintCheckerState->isUndefStore(N))
2687           Out << "\\|Store to Undefined Loc.";
2688         else if (GraphPrintCheckerState->isUndefResult(N))
2689           Out << "\\|Result of operation is undefined.";
2690         else if (GraphPrintCheckerState->isNoReturnCall(N))
2691           Out << "\\|Call to function marked \"noreturn\".";
2692         else if (GraphPrintCheckerState->isBadCall(N))
2693           Out << "\\|Call to NULL/Undefined.";
2694         else if (GraphPrintCheckerState->isUndefArg(N))
2695           Out << "\\|Argument in call is undefined";
2696 #endif
2697 
2698         break;
2699       }
2700     }
2701 
2702     ProgramStateRef state = N->getState();
2703     Out << "\\|StateID: " << (const void*) state.get()
2704         << " NodeID: " << (const void*) N << "\\|";
2705     state->printDOT(Out);
2706 
2707     Out << "\\l";
2708 
2709     if (const ProgramPointTag *tag = Loc.getTag()) {
2710       Out << "\\|Tag: " << tag->getTagDescription();
2711       Out << "\\l";
2712     }
2713     return Out.str();
2714   }
2715 };
2716 } // end llvm namespace
2717 #endif
2718 
2719 void ExprEngine::ViewGraph(bool trim) {
2720 #ifndef NDEBUG
2721   if (trim) {
2722     std::vector<const ExplodedNode*> Src;
2723 
2724     // Flush any outstanding reports to make sure we cover all the nodes.
2725     // This does not cause them to get displayed.
2726     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2727       const_cast<BugType*>(*I)->FlushReports(BR);
2728 
2729     // Iterate through the reports and get their nodes.
2730     for (BugReporter::EQClasses_iterator
2731            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2732       ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2733       if (N) Src.push_back(N);
2734     }
2735 
2736     ViewGraph(Src);
2737   }
2738   else {
2739     GraphPrintCheckerState = this;
2740     GraphPrintSourceManager = &getContext().getSourceManager();
2741 
2742     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2743 
2744     GraphPrintCheckerState = nullptr;
2745     GraphPrintSourceManager = nullptr;
2746   }
2747 #endif
2748 }
2749 
2750 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2751 #ifndef NDEBUG
2752   GraphPrintCheckerState = this;
2753   GraphPrintSourceManager = &getContext().getSourceManager();
2754 
2755   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2756 
2757   if (!TrimmedG.get())
2758     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2759   else
2760     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2761 
2762   GraphPrintCheckerState = nullptr;
2763   GraphPrintSourceManager = nullptr;
2764 #endif
2765 }
2766