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     case Stmt::OMPDistributeParallelForSimdDirectiveClass:
848       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
849 
850     case Stmt::ObjCSubscriptRefExprClass:
851     case Stmt::ObjCPropertyRefExprClass:
852       llvm_unreachable("These are handled by PseudoObjectExpr");
853 
854     case Stmt::GNUNullExprClass: {
855       // GNU __null is a pointer-width integer, not an actual pointer.
856       ProgramStateRef state = Pred->getState();
857       state = state->BindExpr(S, Pred->getLocationContext(),
858                               svalBuilder.makeIntValWithPtrWidth(0, false));
859       Bldr.generateNode(S, Pred, state);
860       break;
861     }
862 
863     case Stmt::ObjCAtSynchronizedStmtClass:
864       Bldr.takeNodes(Pred);
865       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
866       Bldr.addNodes(Dst);
867       break;
868 
869     case Stmt::ExprWithCleanupsClass:
870       // Handled due to fully linearised CFG.
871       break;
872 
873     case Stmt::CXXBindTemporaryExprClass: {
874       Bldr.takeNodes(Pred);
875       ExplodedNodeSet PreVisit;
876       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
877       ExplodedNodeSet Next;
878       VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
879       getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
880       Bldr.addNodes(Dst);
881       break;
882     }
883 
884     // Cases not handled yet; but will handle some day.
885     case Stmt::DesignatedInitExprClass:
886     case Stmt::DesignatedInitUpdateExprClass:
887     case Stmt::ExtVectorElementExprClass:
888     case Stmt::ImaginaryLiteralClass:
889     case Stmt::ObjCAtCatchStmtClass:
890     case Stmt::ObjCAtFinallyStmtClass:
891     case Stmt::ObjCAtTryStmtClass:
892     case Stmt::ObjCAutoreleasePoolStmtClass:
893     case Stmt::ObjCEncodeExprClass:
894     case Stmt::ObjCIsaExprClass:
895     case Stmt::ObjCProtocolExprClass:
896     case Stmt::ObjCSelectorExprClass:
897     case Stmt::ParenListExprClass:
898     case Stmt::ShuffleVectorExprClass:
899     case Stmt::ConvertVectorExprClass:
900     case Stmt::VAArgExprClass:
901     case Stmt::CUDAKernelCallExprClass:
902     case Stmt::OpaqueValueExprClass:
903     case Stmt::AsTypeExprClass:
904     case Stmt::AtomicExprClass:
905       // Fall through.
906 
907     // Cases we intentionally don't evaluate, since they don't need
908     // to be explicitly evaluated.
909     case Stmt::PredefinedExprClass:
910     case Stmt::AddrLabelExprClass:
911     case Stmt::AttributedStmtClass:
912     case Stmt::IntegerLiteralClass:
913     case Stmt::CharacterLiteralClass:
914     case Stmt::ImplicitValueInitExprClass:
915     case Stmt::CXXScalarValueInitExprClass:
916     case Stmt::CXXBoolLiteralExprClass:
917     case Stmt::ObjCBoolLiteralExprClass:
918     case Stmt::FloatingLiteralClass:
919     case Stmt::NoInitExprClass:
920     case Stmt::SizeOfPackExprClass:
921     case Stmt::StringLiteralClass:
922     case Stmt::ObjCStringLiteralClass:
923     case Stmt::CXXPseudoDestructorExprClass:
924     case Stmt::SubstNonTypeTemplateParmExprClass:
925     case Stmt::CXXNullPtrLiteralExprClass:
926     case Stmt::OMPArraySectionExprClass:
927     case Stmt::TypeTraitExprClass: {
928       Bldr.takeNodes(Pred);
929       ExplodedNodeSet preVisit;
930       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
931       getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
932       Bldr.addNodes(Dst);
933       break;
934     }
935 
936     case Stmt::CXXDefaultArgExprClass:
937     case Stmt::CXXDefaultInitExprClass: {
938       Bldr.takeNodes(Pred);
939       ExplodedNodeSet PreVisit;
940       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
941 
942       ExplodedNodeSet Tmp;
943       StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
944 
945       const Expr *ArgE;
946       if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
947         ArgE = DefE->getExpr();
948       else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
949         ArgE = DefE->getExpr();
950       else
951         llvm_unreachable("unknown constant wrapper kind");
952 
953       bool IsTemporary = false;
954       if (const MaterializeTemporaryExpr *MTE =
955             dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
956         ArgE = MTE->GetTemporaryExpr();
957         IsTemporary = true;
958       }
959 
960       Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
961       if (!ConstantVal)
962         ConstantVal = UnknownVal();
963 
964       const LocationContext *LCtx = Pred->getLocationContext();
965       for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
966            I != E; ++I) {
967         ProgramStateRef State = (*I)->getState();
968         State = State->BindExpr(S, LCtx, *ConstantVal);
969         if (IsTemporary)
970           State = createTemporaryRegionIfNeeded(State, LCtx,
971                                                 cast<Expr>(S),
972                                                 cast<Expr>(S));
973         Bldr2.generateNode(S, *I, State);
974       }
975 
976       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
977       Bldr.addNodes(Dst);
978       break;
979     }
980 
981     // Cases we evaluate as opaque expressions, conjuring a symbol.
982     case Stmt::CXXStdInitializerListExprClass:
983     case Expr::ObjCArrayLiteralClass:
984     case Expr::ObjCDictionaryLiteralClass:
985     case Expr::ObjCBoxedExprClass: {
986       Bldr.takeNodes(Pred);
987 
988       ExplodedNodeSet preVisit;
989       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
990 
991       ExplodedNodeSet Tmp;
992       StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
993 
994       const Expr *Ex = cast<Expr>(S);
995       QualType resultType = Ex->getType();
996 
997       for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
998            it != et; ++it) {
999         ExplodedNode *N = *it;
1000         const LocationContext *LCtx = N->getLocationContext();
1001         SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1002                                                    resultType,
1003                                                    currBldrCtx->blockCount());
1004         ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
1005         Bldr2.generateNode(S, N, state);
1006       }
1007 
1008       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1009       Bldr.addNodes(Dst);
1010       break;
1011     }
1012 
1013     case Stmt::ArraySubscriptExprClass:
1014       Bldr.takeNodes(Pred);
1015       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1016       Bldr.addNodes(Dst);
1017       break;
1018 
1019     case Stmt::GCCAsmStmtClass:
1020       Bldr.takeNodes(Pred);
1021       VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1022       Bldr.addNodes(Dst);
1023       break;
1024 
1025     case Stmt::MSAsmStmtClass:
1026       Bldr.takeNodes(Pred);
1027       VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1028       Bldr.addNodes(Dst);
1029       break;
1030 
1031     case Stmt::BlockExprClass:
1032       Bldr.takeNodes(Pred);
1033       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1034       Bldr.addNodes(Dst);
1035       break;
1036 
1037     case Stmt::LambdaExprClass:
1038       if (AMgr.options.shouldInlineLambdas()) {
1039         Bldr.takeNodes(Pred);
1040         VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1041         Bldr.addNodes(Dst);
1042       } else {
1043         const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1044         Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1045       }
1046       break;
1047 
1048     case Stmt::BinaryOperatorClass: {
1049       const BinaryOperator* B = cast<BinaryOperator>(S);
1050       if (B->isLogicalOp()) {
1051         Bldr.takeNodes(Pred);
1052         VisitLogicalExpr(B, Pred, Dst);
1053         Bldr.addNodes(Dst);
1054         break;
1055       }
1056       else if (B->getOpcode() == BO_Comma) {
1057         ProgramStateRef state = Pred->getState();
1058         Bldr.generateNode(B, Pred,
1059                           state->BindExpr(B, Pred->getLocationContext(),
1060                                           state->getSVal(B->getRHS(),
1061                                                   Pred->getLocationContext())));
1062         break;
1063       }
1064 
1065       Bldr.takeNodes(Pred);
1066 
1067       if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1068           (B->isRelationalOp() || B->isEqualityOp())) {
1069         ExplodedNodeSet Tmp;
1070         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1071         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1072       }
1073       else
1074         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1075 
1076       Bldr.addNodes(Dst);
1077       break;
1078     }
1079 
1080     case Stmt::CXXOperatorCallExprClass: {
1081       const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1082 
1083       // For instance method operators, make sure the 'this' argument has a
1084       // valid region.
1085       const Decl *Callee = OCE->getCalleeDecl();
1086       if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1087         if (MD->isInstance()) {
1088           ProgramStateRef State = Pred->getState();
1089           const LocationContext *LCtx = Pred->getLocationContext();
1090           ProgramStateRef NewState =
1091             createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1092           if (NewState != State) {
1093             Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1094                                      ProgramPoint::PreStmtKind);
1095             // Did we cache out?
1096             if (!Pred)
1097               break;
1098           }
1099         }
1100       }
1101       // FALLTHROUGH
1102     }
1103     case Stmt::CallExprClass:
1104     case Stmt::CXXMemberCallExprClass:
1105     case Stmt::UserDefinedLiteralClass: {
1106       Bldr.takeNodes(Pred);
1107       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1108       Bldr.addNodes(Dst);
1109       break;
1110     }
1111 
1112     case Stmt::CXXCatchStmtClass: {
1113       Bldr.takeNodes(Pred);
1114       VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1115       Bldr.addNodes(Dst);
1116       break;
1117     }
1118 
1119     case Stmt::CXXTemporaryObjectExprClass:
1120     case Stmt::CXXConstructExprClass: {
1121       Bldr.takeNodes(Pred);
1122       VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1123       Bldr.addNodes(Dst);
1124       break;
1125     }
1126 
1127     case Stmt::CXXNewExprClass: {
1128       Bldr.takeNodes(Pred);
1129       ExplodedNodeSet PostVisit;
1130       VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1131       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1132       Bldr.addNodes(Dst);
1133       break;
1134     }
1135 
1136     case Stmt::CXXDeleteExprClass: {
1137       Bldr.takeNodes(Pred);
1138       ExplodedNodeSet PreVisit;
1139       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1140       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1141 
1142       for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1143                                      e = PreVisit.end(); i != e ; ++i)
1144         VisitCXXDeleteExpr(CDE, *i, Dst);
1145 
1146       Bldr.addNodes(Dst);
1147       break;
1148     }
1149       // FIXME: ChooseExpr is really a constant.  We need to fix
1150       //        the CFG do not model them as explicit control-flow.
1151 
1152     case Stmt::ChooseExprClass: { // __builtin_choose_expr
1153       Bldr.takeNodes(Pred);
1154       const ChooseExpr *C = cast<ChooseExpr>(S);
1155       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1156       Bldr.addNodes(Dst);
1157       break;
1158     }
1159 
1160     case Stmt::CompoundAssignOperatorClass:
1161       Bldr.takeNodes(Pred);
1162       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1163       Bldr.addNodes(Dst);
1164       break;
1165 
1166     case Stmt::CompoundLiteralExprClass:
1167       Bldr.takeNodes(Pred);
1168       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1169       Bldr.addNodes(Dst);
1170       break;
1171 
1172     case Stmt::BinaryConditionalOperatorClass:
1173     case Stmt::ConditionalOperatorClass: { // '?' operator
1174       Bldr.takeNodes(Pred);
1175       const AbstractConditionalOperator *C
1176         = cast<AbstractConditionalOperator>(S);
1177       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1178       Bldr.addNodes(Dst);
1179       break;
1180     }
1181 
1182     case Stmt::CXXThisExprClass:
1183       Bldr.takeNodes(Pred);
1184       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1185       Bldr.addNodes(Dst);
1186       break;
1187 
1188     case Stmt::DeclRefExprClass: {
1189       Bldr.takeNodes(Pred);
1190       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1191       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1192       Bldr.addNodes(Dst);
1193       break;
1194     }
1195 
1196     case Stmt::DeclStmtClass:
1197       Bldr.takeNodes(Pred);
1198       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1199       Bldr.addNodes(Dst);
1200       break;
1201 
1202     case Stmt::ImplicitCastExprClass:
1203     case Stmt::CStyleCastExprClass:
1204     case Stmt::CXXStaticCastExprClass:
1205     case Stmt::CXXDynamicCastExprClass:
1206     case Stmt::CXXReinterpretCastExprClass:
1207     case Stmt::CXXConstCastExprClass:
1208     case Stmt::CXXFunctionalCastExprClass:
1209     case Stmt::ObjCBridgedCastExprClass: {
1210       Bldr.takeNodes(Pred);
1211       const CastExpr *C = cast<CastExpr>(S);
1212       // Handle the previsit checks.
1213       ExplodedNodeSet dstPrevisit;
1214       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1215 
1216       // Handle the expression itself.
1217       ExplodedNodeSet dstExpr;
1218       for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1219                                      e = dstPrevisit.end(); i != e ; ++i) {
1220         VisitCast(C, C->getSubExpr(), *i, dstExpr);
1221       }
1222 
1223       // Handle the postvisit checks.
1224       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1225       Bldr.addNodes(Dst);
1226       break;
1227     }
1228 
1229     case Expr::MaterializeTemporaryExprClass: {
1230       Bldr.takeNodes(Pred);
1231       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1232       CreateCXXTemporaryObject(MTE, Pred, Dst);
1233       Bldr.addNodes(Dst);
1234       break;
1235     }
1236 
1237     case Stmt::InitListExprClass:
1238       Bldr.takeNodes(Pred);
1239       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1240       Bldr.addNodes(Dst);
1241       break;
1242 
1243     case Stmt::MemberExprClass:
1244       Bldr.takeNodes(Pred);
1245       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1246       Bldr.addNodes(Dst);
1247       break;
1248 
1249     case Stmt::ObjCIvarRefExprClass:
1250       Bldr.takeNodes(Pred);
1251       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1252       Bldr.addNodes(Dst);
1253       break;
1254 
1255     case Stmt::ObjCForCollectionStmtClass:
1256       Bldr.takeNodes(Pred);
1257       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1258       Bldr.addNodes(Dst);
1259       break;
1260 
1261     case Stmt::ObjCMessageExprClass:
1262       Bldr.takeNodes(Pred);
1263       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1264       Bldr.addNodes(Dst);
1265       break;
1266 
1267     case Stmt::ObjCAtThrowStmtClass:
1268     case Stmt::CXXThrowExprClass:
1269       // FIXME: This is not complete.  We basically treat @throw as
1270       // an abort.
1271       Bldr.generateSink(S, Pred, Pred->getState());
1272       break;
1273 
1274     case Stmt::ReturnStmtClass:
1275       Bldr.takeNodes(Pred);
1276       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1277       Bldr.addNodes(Dst);
1278       break;
1279 
1280     case Stmt::OffsetOfExprClass:
1281       Bldr.takeNodes(Pred);
1282       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1283       Bldr.addNodes(Dst);
1284       break;
1285 
1286     case Stmt::UnaryExprOrTypeTraitExprClass:
1287       Bldr.takeNodes(Pred);
1288       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1289                                     Pred, Dst);
1290       Bldr.addNodes(Dst);
1291       break;
1292 
1293     case Stmt::StmtExprClass: {
1294       const StmtExpr *SE = cast<StmtExpr>(S);
1295 
1296       if (SE->getSubStmt()->body_empty()) {
1297         // Empty statement expression.
1298         assert(SE->getType() == getContext().VoidTy
1299                && "Empty statement expression must have void type.");
1300         break;
1301       }
1302 
1303       if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1304         ProgramStateRef state = Pred->getState();
1305         Bldr.generateNode(SE, Pred,
1306                           state->BindExpr(SE, Pred->getLocationContext(),
1307                                           state->getSVal(LastExpr,
1308                                                   Pred->getLocationContext())));
1309       }
1310       break;
1311     }
1312 
1313     case Stmt::UnaryOperatorClass: {
1314       Bldr.takeNodes(Pred);
1315       const UnaryOperator *U = cast<UnaryOperator>(S);
1316       if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1317         ExplodedNodeSet Tmp;
1318         VisitUnaryOperator(U, Pred, Tmp);
1319         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1320       }
1321       else
1322         VisitUnaryOperator(U, Pred, Dst);
1323       Bldr.addNodes(Dst);
1324       break;
1325     }
1326 
1327     case Stmt::PseudoObjectExprClass: {
1328       Bldr.takeNodes(Pred);
1329       ProgramStateRef state = Pred->getState();
1330       const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1331       if (const Expr *Result = PE->getResultExpr()) {
1332         SVal V = state->getSVal(Result, Pred->getLocationContext());
1333         Bldr.generateNode(S, Pred,
1334                           state->BindExpr(S, Pred->getLocationContext(), V));
1335       }
1336       else
1337         Bldr.generateNode(S, Pred,
1338                           state->BindExpr(S, Pred->getLocationContext(),
1339                                                    UnknownVal()));
1340 
1341       Bldr.addNodes(Dst);
1342       break;
1343     }
1344   }
1345 }
1346 
1347 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1348                                        const LocationContext *CalleeLC) {
1349   const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1350   const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1351   assert(CalleeSF && CallerSF);
1352   ExplodedNode *BeforeProcessingCall = nullptr;
1353   const Stmt *CE = CalleeSF->getCallSite();
1354 
1355   // Find the first node before we started processing the call expression.
1356   while (N) {
1357     ProgramPoint L = N->getLocation();
1358     BeforeProcessingCall = N;
1359     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1360 
1361     // Skip the nodes corresponding to the inlined code.
1362     if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1363       continue;
1364     // We reached the caller. Find the node right before we started
1365     // processing the call.
1366     if (L.isPurgeKind())
1367       continue;
1368     if (L.getAs<PreImplicitCall>())
1369       continue;
1370     if (L.getAs<CallEnter>())
1371       continue;
1372     if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1373       if (SP->getStmt() == CE)
1374         continue;
1375     break;
1376   }
1377 
1378   if (!BeforeProcessingCall)
1379     return false;
1380 
1381   // TODO: Clean up the unneeded nodes.
1382 
1383   // Build an Epsilon node from which we will restart the analyzes.
1384   // Note that CE is permitted to be NULL!
1385   ProgramPoint NewNodeLoc =
1386                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1387   // Add the special flag to GDM to signal retrying with no inlining.
1388   // Note, changing the state ensures that we are not going to cache out.
1389   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1390   NewNodeState =
1391     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1392 
1393   // Make the new node a successor of BeforeProcessingCall.
1394   bool IsNew = false;
1395   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1396   // We cached out at this point. Caching out is common due to us backtracking
1397   // from the inlined function, which might spawn several paths.
1398   if (!IsNew)
1399     return true;
1400 
1401   NewNode->addPredecessor(BeforeProcessingCall, G);
1402 
1403   // Add the new node to the work list.
1404   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1405                                   CalleeSF->getIndex());
1406   NumTimesRetriedWithoutInlining++;
1407   return true;
1408 }
1409 
1410 /// Block entrance.  (Update counters).
1411 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1412                                          NodeBuilderWithSinks &nodeBuilder,
1413                                          ExplodedNode *Pred) {
1414   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1415 
1416   // If this block is terminated by a loop and it has already been visited the
1417   // maximum number of times, widen the loop.
1418   unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1419   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1420       AMgr.options.shouldWidenLoops()) {
1421     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1422     if (!(Term &&
1423           (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1424       return;
1425     // Widen.
1426     const LocationContext *LCtx = Pred->getLocationContext();
1427     ProgramStateRef WidenedState =
1428         getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1429     nodeBuilder.generateNode(WidenedState, Pred);
1430     return;
1431   }
1432 
1433   // FIXME: Refactor this into a checker.
1434   if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1435     static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1436     const ExplodedNode *Sink =
1437                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1438 
1439     // Check if we stopped at the top level function or not.
1440     // Root node should have the location context of the top most function.
1441     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1442     const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1443     const LocationContext *RootLC =
1444                         (*G.roots_begin())->getLocation().getLocationContext();
1445     if (RootLC->getCurrentStackFrame() != CalleeSF) {
1446       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1447 
1448       // Re-run the call evaluation without inlining it, by storing the
1449       // no-inlining policy in the state and enqueuing the new work item on
1450       // the list. Replay should almost never fail. Use the stats to catch it
1451       // if it does.
1452       if ((!AMgr.options.NoRetryExhausted &&
1453            replayWithoutInlining(Pred, CalleeLC)))
1454         return;
1455       NumMaxBlockCountReachedInInlined++;
1456     } else
1457       NumMaxBlockCountReached++;
1458 
1459     // Make sink nodes as exhausted(for stats) only if retry failed.
1460     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1461   }
1462 }
1463 
1464 //===----------------------------------------------------------------------===//
1465 // Branch processing.
1466 //===----------------------------------------------------------------------===//
1467 
1468 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1469 /// to try to recover some path-sensitivity for casts of symbolic
1470 /// integers that promote their values (which are currently not tracked well).
1471 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1472 //  cast(s) did was sign-extend the original value.
1473 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1474                                 ProgramStateRef state,
1475                                 const Stmt *Condition,
1476                                 const LocationContext *LCtx,
1477                                 ASTContext &Ctx) {
1478 
1479   const Expr *Ex = dyn_cast<Expr>(Condition);
1480   if (!Ex)
1481     return UnknownVal();
1482 
1483   uint64_t bits = 0;
1484   bool bitsInit = false;
1485 
1486   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1487     QualType T = CE->getType();
1488 
1489     if (!T->isIntegralOrEnumerationType())
1490       return UnknownVal();
1491 
1492     uint64_t newBits = Ctx.getTypeSize(T);
1493     if (!bitsInit || newBits < bits) {
1494       bitsInit = true;
1495       bits = newBits;
1496     }
1497 
1498     Ex = CE->getSubExpr();
1499   }
1500 
1501   // We reached a non-cast.  Is it a symbolic value?
1502   QualType T = Ex->getType();
1503 
1504   if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1505       Ctx.getTypeSize(T) > bits)
1506     return UnknownVal();
1507 
1508   return state->getSVal(Ex, LCtx);
1509 }
1510 
1511 #ifndef NDEBUG
1512 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1513   while (Condition) {
1514     const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1515     if (!BO || !BO->isLogicalOp()) {
1516       return Condition;
1517     }
1518     Condition = BO->getRHS()->IgnoreParens();
1519   }
1520   return nullptr;
1521 }
1522 #endif
1523 
1524 // Returns the condition the branch at the end of 'B' depends on and whose value
1525 // has been evaluated within 'B'.
1526 // In most cases, the terminator condition of 'B' will be evaluated fully in
1527 // the last statement of 'B'; in those cases, the resolved condition is the
1528 // given 'Condition'.
1529 // If the condition of the branch is a logical binary operator tree, the CFG is
1530 // optimized: in that case, we know that the expression formed by all but the
1531 // rightmost leaf of the logical binary operator tree must be true, and thus
1532 // the branch condition is at this point equivalent to the truth value of that
1533 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1534 // expression in its final statement. As the full condition in that case was
1535 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1536 // expression to evaluate the truth value of the condition in the current state
1537 // space.
1538 static const Stmt *ResolveCondition(const Stmt *Condition,
1539                                     const CFGBlock *B) {
1540   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1541     Condition = Ex->IgnoreParens();
1542 
1543   const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1544   if (!BO || !BO->isLogicalOp())
1545     return Condition;
1546 
1547   assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1548          "Temporary destructor branches handled by processBindTemporary.");
1549 
1550   // For logical operations, we still have the case where some branches
1551   // use the traditional "merge" approach and others sink the branch
1552   // directly into the basic blocks representing the logical operation.
1553   // We need to distinguish between those two cases here.
1554 
1555   // The invariants are still shifting, but it is possible that the
1556   // last element in a CFGBlock is not a CFGStmt.  Look for the last
1557   // CFGStmt as the value of the condition.
1558   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1559   for (; I != E; ++I) {
1560     CFGElement Elem = *I;
1561     Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1562     if (!CS)
1563       continue;
1564     const Stmt *LastStmt = CS->getStmt();
1565     assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1566     return LastStmt;
1567   }
1568   llvm_unreachable("could not resolve condition");
1569 }
1570 
1571 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1572                                NodeBuilderContext& BldCtx,
1573                                ExplodedNode *Pred,
1574                                ExplodedNodeSet &Dst,
1575                                const CFGBlock *DstT,
1576                                const CFGBlock *DstF) {
1577   assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1578          "CXXBindTemporaryExprs are handled by processBindTemporary.");
1579   const LocationContext *LCtx = Pred->getLocationContext();
1580   PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1581   currBldrCtx = &BldCtx;
1582 
1583   // Check for NULL conditions; e.g. "for(;;)"
1584   if (!Condition) {
1585     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1586     NullCondBldr.markInfeasible(false);
1587     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1588     return;
1589   }
1590 
1591   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1592     Condition = Ex->IgnoreParens();
1593 
1594   Condition = ResolveCondition(Condition, BldCtx.getBlock());
1595   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1596                                 Condition->getLocStart(),
1597                                 "Error evaluating branch");
1598 
1599   ExplodedNodeSet CheckersOutSet;
1600   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1601                                                     Pred, *this);
1602   // We generated only sinks.
1603   if (CheckersOutSet.empty())
1604     return;
1605 
1606   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1607   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1608                              E = CheckersOutSet.end(); E != I; ++I) {
1609     ExplodedNode *PredI = *I;
1610 
1611     if (PredI->isSink())
1612       continue;
1613 
1614     ProgramStateRef PrevState = PredI->getState();
1615     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1616 
1617     if (X.isUnknownOrUndef()) {
1618       // Give it a chance to recover from unknown.
1619       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1620         if (Ex->getType()->isIntegralOrEnumerationType()) {
1621           // Try to recover some path-sensitivity.  Right now casts of symbolic
1622           // integers that promote their values are currently not tracked well.
1623           // If 'Condition' is such an expression, try and recover the
1624           // underlying value and use that instead.
1625           SVal recovered = RecoverCastedSymbol(getStateManager(),
1626                                                PrevState, Condition,
1627                                                PredI->getLocationContext(),
1628                                                getContext());
1629 
1630           if (!recovered.isUnknown()) {
1631             X = recovered;
1632           }
1633         }
1634       }
1635     }
1636 
1637     // If the condition is still unknown, give up.
1638     if (X.isUnknownOrUndef()) {
1639       builder.generateNode(PrevState, true, PredI);
1640       builder.generateNode(PrevState, false, PredI);
1641       continue;
1642     }
1643 
1644     DefinedSVal V = X.castAs<DefinedSVal>();
1645 
1646     ProgramStateRef StTrue, StFalse;
1647     std::tie(StTrue, StFalse) = PrevState->assume(V);
1648 
1649     // Process the true branch.
1650     if (builder.isFeasible(true)) {
1651       if (StTrue)
1652         builder.generateNode(StTrue, true, PredI);
1653       else
1654         builder.markInfeasible(true);
1655     }
1656 
1657     // Process the false branch.
1658     if (builder.isFeasible(false)) {
1659       if (StFalse)
1660         builder.generateNode(StFalse, false, PredI);
1661       else
1662         builder.markInfeasible(false);
1663     }
1664   }
1665   currBldrCtx = nullptr;
1666 }
1667 
1668 /// The GDM component containing the set of global variables which have been
1669 /// previously initialized with explicit initializers.
1670 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1671                                  llvm::ImmutableSet<const VarDecl *>)
1672 
1673 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1674                                           NodeBuilderContext &BuilderCtx,
1675                                           ExplodedNode *Pred,
1676                                           clang::ento::ExplodedNodeSet &Dst,
1677                                           const CFGBlock *DstT,
1678                                           const CFGBlock *DstF) {
1679   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1680   currBldrCtx = &BuilderCtx;
1681 
1682   const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1683   ProgramStateRef state = Pred->getState();
1684   bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1685   BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1686 
1687   if (!initHasRun) {
1688     state = state->add<InitializedGlobalsSet>(VD);
1689   }
1690 
1691   builder.generateNode(state, initHasRun, Pred);
1692   builder.markInfeasible(!initHasRun);
1693 
1694   currBldrCtx = nullptr;
1695 }
1696 
1697 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1698 ///  nodes by processing the 'effects' of a computed goto jump.
1699 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1700 
1701   ProgramStateRef state = builder.getState();
1702   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1703 
1704   // Three possibilities:
1705   //
1706   //   (1) We know the computed label.
1707   //   (2) The label is NULL (or some other constant), or Undefined.
1708   //   (3) We have no clue about the label.  Dispatch to all targets.
1709   //
1710 
1711   typedef IndirectGotoNodeBuilder::iterator iterator;
1712 
1713   if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1714     const LabelDecl *L = LV->getLabel();
1715 
1716     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1717       if (I.getLabel() == L) {
1718         builder.generateNode(I, state);
1719         return;
1720       }
1721     }
1722 
1723     llvm_unreachable("No block with label.");
1724   }
1725 
1726   if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1727     // Dispatch to the first target and mark it as a sink.
1728     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1729     // FIXME: add checker visit.
1730     //    UndefBranches.insert(N);
1731     return;
1732   }
1733 
1734   // This is really a catch-all.  We don't support symbolics yet.
1735   // FIXME: Implement dispatch for symbolic pointers.
1736 
1737   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1738     builder.generateNode(I, state);
1739 }
1740 
1741 #if 0
1742 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1743   const StackFrameContext* Frame = Pred.getStackFrame();
1744   const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1745       Pred.getState()->get<InitializedTemporariesSet>();
1746   return std::find_if(Set.begin(), Set.end(),
1747                       [&](const CXXBindTemporaryContext &Ctx) {
1748                         if (Ctx.second == Frame) {
1749                           Ctx.first->dump();
1750                           llvm::errs() << "\n";
1751                         }
1752            return Ctx.second == Frame;
1753          }) == Set.end();
1754 }
1755 #endif
1756 
1757 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
1758                                         ExplodedNode *Pred,
1759                                         ExplodedNodeSet &Dst,
1760                                         const BlockEdge &L) {
1761   SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1762   getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1763 }
1764 
1765 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1766 ///  nodes when the control reaches the end of a function.
1767 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1768                                       ExplodedNode *Pred) {
1769   // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1770   // We currently cannot enable this assert, as lifetime extended temporaries
1771   // are not modelled correctly.
1772   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1773   StateMgr.EndPath(Pred->getState());
1774 
1775   ExplodedNodeSet Dst;
1776   if (Pred->getLocationContext()->inTopFrame()) {
1777     // Remove dead symbols.
1778     ExplodedNodeSet AfterRemovedDead;
1779     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1780 
1781     // Notify checkers.
1782     for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1783         E = AfterRemovedDead.end(); I != E; ++I) {
1784       getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1785     }
1786   } else {
1787     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1788   }
1789 
1790   Engine.enqueueEndOfFunction(Dst);
1791 }
1792 
1793 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1794 ///  nodes by processing the 'effects' of a switch statement.
1795 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1796   typedef SwitchNodeBuilder::iterator iterator;
1797   ProgramStateRef state = builder.getState();
1798   const Expr *CondE = builder.getCondition();
1799   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1800 
1801   if (CondV_untested.isUndef()) {
1802     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1803     // FIXME: add checker
1804     //UndefBranches.insert(N);
1805 
1806     return;
1807   }
1808   DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1809 
1810   ProgramStateRef DefaultSt = state;
1811 
1812   iterator I = builder.begin(), EI = builder.end();
1813   bool defaultIsFeasible = I == EI;
1814 
1815   for ( ; I != EI; ++I) {
1816     // Successor may be pruned out during CFG construction.
1817     if (!I.getBlock())
1818       continue;
1819 
1820     const CaseStmt *Case = I.getCase();
1821 
1822     // Evaluate the LHS of the case value.
1823     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1824     assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1825 
1826     // Get the RHS of the case, if it exists.
1827     llvm::APSInt V2;
1828     if (const Expr *E = Case->getRHS())
1829       V2 = E->EvaluateKnownConstInt(getContext());
1830     else
1831       V2 = V1;
1832 
1833     ProgramStateRef StateCase;
1834     if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1835       std::tie(StateCase, DefaultSt) =
1836           DefaultSt->assumeWithinInclusiveRange(*NL, V1, V2);
1837     else // UnknownVal
1838       StateCase = DefaultSt;
1839 
1840     if (StateCase)
1841       builder.generateCaseStmtNode(I, StateCase);
1842 
1843     // Now "assume" that the case doesn't match.  Add this state
1844     // to the default state (if it is feasible).
1845     if (DefaultSt)
1846       defaultIsFeasible = true;
1847     else {
1848       defaultIsFeasible = false;
1849       break;
1850     }
1851   }
1852 
1853   if (!defaultIsFeasible)
1854     return;
1855 
1856   // If we have switch(enum value), the default branch is not
1857   // feasible if all of the enum constants not covered by 'case:' statements
1858   // are not feasible values for the switch condition.
1859   //
1860   // Note that this isn't as accurate as it could be.  Even if there isn't
1861   // a case for a particular enum value as long as that enum value isn't
1862   // feasible then it shouldn't be considered for making 'default:' reachable.
1863   const SwitchStmt *SS = builder.getSwitch();
1864   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1865   if (CondExpr->getType()->getAs<EnumType>()) {
1866     if (SS->isAllEnumCasesCovered())
1867       return;
1868   }
1869 
1870   builder.generateDefaultCaseNode(DefaultSt);
1871 }
1872 
1873 //===----------------------------------------------------------------------===//
1874 // Transfer functions: Loads and stores.
1875 //===----------------------------------------------------------------------===//
1876 
1877 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1878                                         ExplodedNode *Pred,
1879                                         ExplodedNodeSet &Dst) {
1880   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1881 
1882   ProgramStateRef state = Pred->getState();
1883   const LocationContext *LCtx = Pred->getLocationContext();
1884 
1885   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1886     // C permits "extern void v", and if you cast the address to a valid type,
1887     // you can even do things with it. We simply pretend
1888     assert(Ex->isGLValue() || VD->getType()->isVoidType());
1889     const LocationContext *LocCtxt = Pred->getLocationContext();
1890     const Decl *D = LocCtxt->getDecl();
1891     const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
1892     const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
1893     SVal V;
1894     bool IsReference;
1895     if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
1896         DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
1897         MD->getParent()->isLambda()) {
1898       // Lookup the field of the lambda.
1899       const CXXRecordDecl *CXXRec = MD->getParent();
1900       llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
1901       FieldDecl *LambdaThisCaptureField;
1902       CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
1903       const FieldDecl *FD = LambdaCaptureFields[VD];
1904       if (!FD) {
1905         // When a constant is captured, sometimes no corresponding field is
1906         // created in the lambda object.
1907         assert(VD->getType().isConstQualified());
1908         V = state->getLValue(VD, LocCtxt);
1909         IsReference = false;
1910       } else {
1911         Loc CXXThis =
1912             svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
1913         SVal CXXThisVal = state->getSVal(CXXThis);
1914         V = state->getLValue(FD, CXXThisVal);
1915         IsReference = FD->getType()->isReferenceType();
1916       }
1917     } else {
1918       V = state->getLValue(VD, LocCtxt);
1919       IsReference = VD->getType()->isReferenceType();
1920     }
1921 
1922     // For references, the 'lvalue' is the pointer address stored in the
1923     // reference region.
1924     if (IsReference) {
1925       if (const MemRegion *R = V.getAsRegion())
1926         V = state->getSVal(R);
1927       else
1928         V = UnknownVal();
1929     }
1930 
1931     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1932                       ProgramPoint::PostLValueKind);
1933     return;
1934   }
1935   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1936     assert(!Ex->isGLValue());
1937     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1938     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1939     return;
1940   }
1941   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1942     SVal V = svalBuilder.getFunctionPointer(FD);
1943     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1944                       ProgramPoint::PostLValueKind);
1945     return;
1946   }
1947   if (isa<FieldDecl>(D)) {
1948     // FIXME: Compute lvalue of field pointers-to-member.
1949     // Right now we just use a non-null void pointer, so that it gives proper
1950     // results in boolean contexts.
1951     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1952                                           currBldrCtx->blockCount());
1953     state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1954     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1955 		      ProgramPoint::PostLValueKind);
1956     return;
1957   }
1958 
1959   llvm_unreachable("Support for this Decl not implemented.");
1960 }
1961 
1962 /// VisitArraySubscriptExpr - Transfer function for array accesses
1963 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1964                                              ExplodedNode *Pred,
1965                                              ExplodedNodeSet &Dst){
1966 
1967   const Expr *Base = A->getBase()->IgnoreParens();
1968   const Expr *Idx  = A->getIdx()->IgnoreParens();
1969 
1970   ExplodedNodeSet checkerPreStmt;
1971   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1972 
1973   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1974   assert(A->isGLValue() ||
1975           (!AMgr.getLangOpts().CPlusPlus &&
1976            A->getType().isCForbiddenLValueType()));
1977 
1978   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1979                                  ei = checkerPreStmt.end(); it != ei; ++it) {
1980     const LocationContext *LCtx = (*it)->getLocationContext();
1981     ProgramStateRef state = (*it)->getState();
1982     SVal V = state->getLValue(A->getType(),
1983                               state->getSVal(Idx, LCtx),
1984                               state->getSVal(Base, LCtx));
1985     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1986                       ProgramPoint::PostLValueKind);
1987   }
1988 }
1989 
1990 /// VisitMemberExpr - Transfer function for member expressions.
1991 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1992                                  ExplodedNodeSet &Dst) {
1993 
1994   // FIXME: Prechecks eventually go in ::Visit().
1995   ExplodedNodeSet CheckedSet;
1996   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
1997 
1998   ExplodedNodeSet EvalSet;
1999   ValueDecl *Member = M->getMemberDecl();
2000 
2001   // Handle static member variables and enum constants accessed via
2002   // member syntax.
2003   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2004     ExplodedNodeSet Dst;
2005     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2006          I != E; ++I) {
2007       VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2008     }
2009   } else {
2010     StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2011     ExplodedNodeSet Tmp;
2012 
2013     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2014          I != E; ++I) {
2015       ProgramStateRef state = (*I)->getState();
2016       const LocationContext *LCtx = (*I)->getLocationContext();
2017       Expr *BaseExpr = M->getBase();
2018 
2019       // Handle C++ method calls.
2020       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2021         if (MD->isInstance())
2022           state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2023 
2024         SVal MDVal = svalBuilder.getFunctionPointer(MD);
2025         state = state->BindExpr(M, LCtx, MDVal);
2026 
2027         Bldr.generateNode(M, *I, state);
2028         continue;
2029       }
2030 
2031       // Handle regular struct fields / member variables.
2032       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2033       SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2034 
2035       FieldDecl *field = cast<FieldDecl>(Member);
2036       SVal L = state->getLValue(field, baseExprVal);
2037 
2038       if (M->isGLValue() || M->getType()->isArrayType()) {
2039         // We special-case rvalues of array type because the analyzer cannot
2040         // reason about them, since we expect all regions to be wrapped in Locs.
2041         // We instead treat these as lvalues and assume that they will decay to
2042         // pointers as soon as they are used.
2043         if (!M->isGLValue()) {
2044           assert(M->getType()->isArrayType());
2045           const ImplicitCastExpr *PE =
2046             dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
2047           if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2048             llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2049           }
2050         }
2051 
2052         if (field->getType()->isReferenceType()) {
2053           if (const MemRegion *R = L.getAsRegion())
2054             L = state->getSVal(R);
2055           else
2056             L = UnknownVal();
2057         }
2058 
2059         Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2060                           ProgramPoint::PostLValueKind);
2061       } else {
2062         Bldr.takeNodes(*I);
2063         evalLoad(Tmp, M, M, *I, state, L);
2064         Bldr.addNodes(Tmp);
2065       }
2066     }
2067   }
2068 
2069   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2070 }
2071 
2072 namespace {
2073 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2074   InvalidatedSymbols Symbols;
2075 
2076 public:
2077   CollectReachableSymbolsCallback(ProgramStateRef State) {}
2078   const InvalidatedSymbols &getSymbols() const { return Symbols; }
2079 
2080   bool VisitSymbol(SymbolRef Sym) override {
2081     Symbols.insert(Sym);
2082     return true;
2083   }
2084 };
2085 } // end anonymous namespace
2086 
2087 // A value escapes in three possible cases:
2088 // (1) We are binding to something that is not a memory region.
2089 // (2) We are binding to a MemrRegion that does not have stack storage.
2090 // (3) We are binding to a MemRegion with stack storage that the store
2091 //     does not understand.
2092 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2093                                                         SVal Loc, SVal Val) {
2094   // Are we storing to something that causes the value to "escape"?
2095   bool escapes = true;
2096 
2097   // TODO: Move to StoreManager.
2098   if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2099     escapes = !regionLoc->getRegion()->hasStackStorage();
2100 
2101     if (!escapes) {
2102       // To test (3), generate a new state with the binding added.  If it is
2103       // the same state, then it escapes (since the store cannot represent
2104       // the binding).
2105       // Do this only if we know that the store is not supposed to generate the
2106       // same state.
2107       SVal StoredVal = State->getSVal(regionLoc->getRegion());
2108       if (StoredVal != Val)
2109         escapes = (State == (State->bindLoc(*regionLoc, Val)));
2110     }
2111   }
2112 
2113   // If our store can represent the binding and we aren't storing to something
2114   // that doesn't have local storage then just return and have the simulation
2115   // state continue as is.
2116   if (!escapes)
2117     return State;
2118 
2119   // Otherwise, find all symbols referenced by 'val' that we are tracking
2120   // and stop tracking them.
2121   CollectReachableSymbolsCallback Scanner =
2122       State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2123   const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2124   State = getCheckerManager().runCheckersForPointerEscape(State,
2125                                                           EscapedSymbols,
2126                                                           /*CallEvent*/ nullptr,
2127                                                           PSK_EscapeOnBind,
2128                                                           nullptr);
2129 
2130   return State;
2131 }
2132 
2133 ProgramStateRef
2134 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2135     const InvalidatedSymbols *Invalidated,
2136     ArrayRef<const MemRegion *> ExplicitRegions,
2137     ArrayRef<const MemRegion *> Regions,
2138     const CallEvent *Call,
2139     RegionAndSymbolInvalidationTraits &ITraits) {
2140 
2141   if (!Invalidated || Invalidated->empty())
2142     return State;
2143 
2144   if (!Call)
2145     return getCheckerManager().runCheckersForPointerEscape(State,
2146                                                            *Invalidated,
2147                                                            nullptr,
2148                                                            PSK_EscapeOther,
2149                                                            &ITraits);
2150 
2151   // If the symbols were invalidated by a call, we want to find out which ones
2152   // were invalidated directly due to being arguments to the call.
2153   InvalidatedSymbols SymbolsDirectlyInvalidated;
2154   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2155       E = ExplicitRegions.end(); I != E; ++I) {
2156     if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2157       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2158   }
2159 
2160   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2161   for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2162       E = Invalidated->end(); I!=E; ++I) {
2163     SymbolRef sym = *I;
2164     if (SymbolsDirectlyInvalidated.count(sym))
2165       continue;
2166     SymbolsIndirectlyInvalidated.insert(sym);
2167   }
2168 
2169   if (!SymbolsDirectlyInvalidated.empty())
2170     State = getCheckerManager().runCheckersForPointerEscape(State,
2171         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2172 
2173   // Notify about the symbols that get indirectly invalidated by the call.
2174   if (!SymbolsIndirectlyInvalidated.empty())
2175     State = getCheckerManager().runCheckersForPointerEscape(State,
2176         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2177 
2178   return State;
2179 }
2180 
2181 /// evalBind - Handle the semantics of binding a value to a specific location.
2182 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2183 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2184                           ExplodedNode *Pred,
2185                           SVal location, SVal Val,
2186                           bool atDeclInit, const ProgramPoint *PP) {
2187 
2188   const LocationContext *LC = Pred->getLocationContext();
2189   PostStmt PS(StoreE, LC);
2190   if (!PP)
2191     PP = &PS;
2192 
2193   // Do a previsit of the bind.
2194   ExplodedNodeSet CheckedSet;
2195   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2196                                          StoreE, *this, *PP);
2197 
2198   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2199 
2200   // If the location is not a 'Loc', it will already be handled by
2201   // the checkers.  There is nothing left to do.
2202   if (!location.getAs<Loc>()) {
2203     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2204                                      /*tag*/nullptr);
2205     ProgramStateRef state = Pred->getState();
2206     state = processPointerEscapedOnBind(state, location, Val);
2207     Bldr.generateNode(L, state, Pred);
2208     return;
2209   }
2210 
2211   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2212        I!=E; ++I) {
2213     ExplodedNode *PredI = *I;
2214     ProgramStateRef state = PredI->getState();
2215 
2216     state = processPointerEscapedOnBind(state, location, Val);
2217 
2218     // When binding the value, pass on the hint that this is a initialization.
2219     // For initializations, we do not need to inform clients of region
2220     // changes.
2221     state = state->bindLoc(location.castAs<Loc>(),
2222                            Val, /* notifyChanges = */ !atDeclInit);
2223 
2224     const MemRegion *LocReg = nullptr;
2225     if (Optional<loc::MemRegionVal> LocRegVal =
2226             location.getAs<loc::MemRegionVal>()) {
2227       LocReg = LocRegVal->getRegion();
2228     }
2229 
2230     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2231     Bldr.generateNode(L, state, PredI);
2232   }
2233 }
2234 
2235 /// evalStore - Handle the semantics of a store via an assignment.
2236 ///  @param Dst The node set to store generated state nodes
2237 ///  @param AssignE The assignment expression if the store happens in an
2238 ///         assignment.
2239 ///  @param LocationE The location expression that is stored to.
2240 ///  @param state The current simulation state
2241 ///  @param location The location to store the value
2242 ///  @param Val The value to be stored
2243 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2244                              const Expr *LocationE,
2245                              ExplodedNode *Pred,
2246                              ProgramStateRef state, SVal location, SVal Val,
2247                              const ProgramPointTag *tag) {
2248   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2249   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2250   const Expr *StoreE = AssignE ? AssignE : LocationE;
2251 
2252   // Evaluate the location (checks for bad dereferences).
2253   ExplodedNodeSet Tmp;
2254   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2255 
2256   if (Tmp.empty())
2257     return;
2258 
2259   if (location.isUndef())
2260     return;
2261 
2262   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2263     evalBind(Dst, StoreE, *NI, location, Val, false);
2264 }
2265 
2266 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2267                           const Expr *NodeEx,
2268                           const Expr *BoundEx,
2269                           ExplodedNode *Pred,
2270                           ProgramStateRef state,
2271                           SVal location,
2272                           const ProgramPointTag *tag,
2273                           QualType LoadTy)
2274 {
2275   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2276 
2277   // Are we loading from a region?  This actually results in two loads; one
2278   // to fetch the address of the referenced value and one to fetch the
2279   // referenced value.
2280   if (const TypedValueRegion *TR =
2281         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2282 
2283     QualType ValTy = TR->getValueType();
2284     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2285       static SimpleProgramPointTag
2286              loadReferenceTag(TagProviderName, "Load Reference");
2287       ExplodedNodeSet Tmp;
2288       evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2289                      location, &loadReferenceTag,
2290                      getContext().getPointerType(RT->getPointeeType()));
2291 
2292       // Perform the load from the referenced value.
2293       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2294         state = (*I)->getState();
2295         location = state->getSVal(BoundEx, (*I)->getLocationContext());
2296         evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2297       }
2298       return;
2299     }
2300   }
2301 
2302   evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2303 }
2304 
2305 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2306                                 const Expr *NodeEx,
2307                                 const Expr *BoundEx,
2308                                 ExplodedNode *Pred,
2309                                 ProgramStateRef state,
2310                                 SVal location,
2311                                 const ProgramPointTag *tag,
2312                                 QualType LoadTy) {
2313   assert(NodeEx);
2314   assert(BoundEx);
2315   // Evaluate the location (checks for bad dereferences).
2316   ExplodedNodeSet Tmp;
2317   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2318   if (Tmp.empty())
2319     return;
2320 
2321   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2322   if (location.isUndef())
2323     return;
2324 
2325   // Proceed with the load.
2326   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2327     state = (*NI)->getState();
2328     const LocationContext *LCtx = (*NI)->getLocationContext();
2329 
2330     SVal V = UnknownVal();
2331     if (location.isValid()) {
2332       if (LoadTy.isNull())
2333         LoadTy = BoundEx->getType();
2334       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2335     }
2336 
2337     Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2338                       ProgramPoint::PostLoadKind);
2339   }
2340 }
2341 
2342 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2343                               const Stmt *NodeEx,
2344                               const Stmt *BoundEx,
2345                               ExplodedNode *Pred,
2346                               ProgramStateRef state,
2347                               SVal location,
2348                               const ProgramPointTag *tag,
2349                               bool isLoad) {
2350   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2351   // Early checks for performance reason.
2352   if (location.isUnknown()) {
2353     return;
2354   }
2355 
2356   ExplodedNodeSet Src;
2357   BldrTop.takeNodes(Pred);
2358   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2359   if (Pred->getState() != state) {
2360     // Associate this new state with an ExplodedNode.
2361     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2362     //   int *p;
2363     //   p = 0;
2364     //   *p = 0xDEADBEEF;
2365     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2366     // instead "int *p" is noted as
2367     // "Variable 'p' initialized to a null pointer value"
2368 
2369     static SimpleProgramPointTag tag(TagProviderName, "Location");
2370     Bldr.generateNode(NodeEx, Pred, state, &tag);
2371   }
2372   ExplodedNodeSet Tmp;
2373   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2374                                              NodeEx, BoundEx, *this);
2375   BldrTop.addNodes(Tmp);
2376 }
2377 
2378 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2379 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2380   static SimpleProgramPointTag
2381          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2382                                            "Eagerly Assume True"),
2383          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2384                                             "Eagerly Assume False");
2385   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2386                         &eagerlyAssumeBinOpBifurcationFalse);
2387 }
2388 
2389 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2390                                                    ExplodedNodeSet &Src,
2391                                                    const Expr *Ex) {
2392   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2393 
2394   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2395     ExplodedNode *Pred = *I;
2396     // Test if the previous node was as the same expression.  This can happen
2397     // when the expression fails to evaluate to anything meaningful and
2398     // (as an optimization) we don't generate a node.
2399     ProgramPoint P = Pred->getLocation();
2400     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2401       continue;
2402     }
2403 
2404     ProgramStateRef state = Pred->getState();
2405     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2406     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2407     if (SEV && SEV->isExpression()) {
2408       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2409         geteagerlyAssumeBinOpBifurcationTags();
2410 
2411       ProgramStateRef StateTrue, StateFalse;
2412       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2413 
2414       // First assume that the condition is true.
2415       if (StateTrue) {
2416         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2417         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2418         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2419       }
2420 
2421       // Next, assume that the condition is false.
2422       if (StateFalse) {
2423         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2424         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2425         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2426       }
2427     }
2428   }
2429 }
2430 
2431 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2432                                  ExplodedNodeSet &Dst) {
2433   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2434   // We have processed both the inputs and the outputs.  All of the outputs
2435   // should evaluate to Locs.  Nuke all of their values.
2436 
2437   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2438   // which interprets the inline asm and stores proper results in the
2439   // outputs.
2440 
2441   ProgramStateRef state = Pred->getState();
2442 
2443   for (const Expr *O : A->outputs()) {
2444     SVal X = state->getSVal(O, Pred->getLocationContext());
2445     assert (!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2446 
2447     if (Optional<Loc> LV = X.getAs<Loc>())
2448       state = state->bindLoc(*LV, UnknownVal());
2449   }
2450 
2451   Bldr.generateNode(A, Pred, state);
2452 }
2453 
2454 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2455                                 ExplodedNodeSet &Dst) {
2456   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2457   Bldr.generateNode(A, Pred, Pred->getState());
2458 }
2459 
2460 //===----------------------------------------------------------------------===//
2461 // Visualization.
2462 //===----------------------------------------------------------------------===//
2463 
2464 #ifndef NDEBUG
2465 static ExprEngine* GraphPrintCheckerState;
2466 static SourceManager* GraphPrintSourceManager;
2467 
2468 namespace llvm {
2469 template<>
2470 struct DOTGraphTraits<ExplodedNode*> :
2471   public DefaultDOTGraphTraits {
2472 
2473   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2474 
2475   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2476   // work.
2477   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2478 
2479 #if 0
2480       // FIXME: Replace with a general scheme to tell if the node is
2481       // an error node.
2482     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2483         GraphPrintCheckerState->isExplicitNullDeref(N) ||
2484         GraphPrintCheckerState->isUndefDeref(N) ||
2485         GraphPrintCheckerState->isUndefStore(N) ||
2486         GraphPrintCheckerState->isUndefControlFlow(N) ||
2487         GraphPrintCheckerState->isUndefResult(N) ||
2488         GraphPrintCheckerState->isBadCall(N) ||
2489         GraphPrintCheckerState->isUndefArg(N))
2490       return "color=\"red\",style=\"filled\"";
2491 
2492     if (GraphPrintCheckerState->isNoReturnCall(N))
2493       return "color=\"blue\",style=\"filled\"";
2494 #endif
2495     return "";
2496   }
2497 
2498   static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2499     if (SLoc.isFileID()) {
2500       Out << "\\lline="
2501         << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2502         << " col="
2503         << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2504         << "\\l";
2505     }
2506   }
2507 
2508   static std::string getNodeLabel(const ExplodedNode *N, void*){
2509 
2510     std::string sbuf;
2511     llvm::raw_string_ostream Out(sbuf);
2512 
2513     // Program Location.
2514     ProgramPoint Loc = N->getLocation();
2515 
2516     switch (Loc.getKind()) {
2517       case ProgramPoint::BlockEntranceKind: {
2518         Out << "Block Entrance: B"
2519             << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2520         if (const NamedDecl *ND =
2521                     dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2522           Out << " (";
2523           ND->printName(Out);
2524           Out << ")";
2525         }
2526         break;
2527       }
2528 
2529       case ProgramPoint::BlockExitKind:
2530         assert (false);
2531         break;
2532 
2533       case ProgramPoint::CallEnterKind:
2534         Out << "CallEnter";
2535         break;
2536 
2537       case ProgramPoint::CallExitBeginKind:
2538         Out << "CallExitBegin";
2539         break;
2540 
2541       case ProgramPoint::CallExitEndKind:
2542         Out << "CallExitEnd";
2543         break;
2544 
2545       case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2546         Out << "PostStmtPurgeDeadSymbols";
2547         break;
2548 
2549       case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2550         Out << "PreStmtPurgeDeadSymbols";
2551         break;
2552 
2553       case ProgramPoint::EpsilonKind:
2554         Out << "Epsilon Point";
2555         break;
2556 
2557       case ProgramPoint::PreImplicitCallKind: {
2558         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2559         Out << "PreCall: ";
2560 
2561         // FIXME: Get proper printing options.
2562         PC.getDecl()->print(Out, LangOptions());
2563         printLocation(Out, PC.getLocation());
2564         break;
2565       }
2566 
2567       case ProgramPoint::PostImplicitCallKind: {
2568         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2569         Out << "PostCall: ";
2570 
2571         // FIXME: Get proper printing options.
2572         PC.getDecl()->print(Out, LangOptions());
2573         printLocation(Out, PC.getLocation());
2574         break;
2575       }
2576 
2577       case ProgramPoint::PostInitializerKind: {
2578         Out << "PostInitializer: ";
2579         const CXXCtorInitializer *Init =
2580           Loc.castAs<PostInitializer>().getInitializer();
2581         if (const FieldDecl *FD = Init->getAnyMember())
2582           Out << *FD;
2583         else {
2584           QualType Ty = Init->getTypeSourceInfo()->getType();
2585           Ty = Ty.getLocalUnqualifiedType();
2586           LangOptions LO; // FIXME.
2587           Ty.print(Out, LO);
2588         }
2589         break;
2590       }
2591 
2592       case ProgramPoint::BlockEdgeKind: {
2593         const BlockEdge &E = Loc.castAs<BlockEdge>();
2594         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2595             << E.getDst()->getBlockID()  << ')';
2596 
2597         if (const Stmt *T = E.getSrc()->getTerminator()) {
2598           SourceLocation SLoc = T->getLocStart();
2599 
2600           Out << "\\|Terminator: ";
2601           LangOptions LO; // FIXME.
2602           E.getSrc()->printTerminator(Out, LO);
2603 
2604           if (SLoc.isFileID()) {
2605             Out << "\\lline="
2606               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2607               << " col="
2608               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2609           }
2610 
2611           if (isa<SwitchStmt>(T)) {
2612             const Stmt *Label = E.getDst()->getLabel();
2613 
2614             if (Label) {
2615               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2616                 Out << "\\lcase ";
2617                 LangOptions LO; // FIXME.
2618                 if (C->getLHS())
2619                   C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2620 
2621                 if (const Stmt *RHS = C->getRHS()) {
2622                   Out << " .. ";
2623                   RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2624                 }
2625 
2626                 Out << ":";
2627               }
2628               else {
2629                 assert (isa<DefaultStmt>(Label));
2630                 Out << "\\ldefault:";
2631               }
2632             }
2633             else
2634               Out << "\\l(implicit) default:";
2635           }
2636           else if (isa<IndirectGotoStmt>(T)) {
2637             // FIXME
2638           }
2639           else {
2640             Out << "\\lCondition: ";
2641             if (*E.getSrc()->succ_begin() == E.getDst())
2642               Out << "true";
2643             else
2644               Out << "false";
2645           }
2646 
2647           Out << "\\l";
2648         }
2649 
2650 #if 0
2651           // FIXME: Replace with a general scheme to determine
2652           // the name of the check.
2653         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2654           Out << "\\|Control-flow based on\\lUndefined value.\\l";
2655         }
2656 #endif
2657         break;
2658       }
2659 
2660       default: {
2661         const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2662         assert(S != nullptr && "Expecting non-null Stmt");
2663 
2664         Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2665         LangOptions LO; // FIXME.
2666         S->printPretty(Out, nullptr, PrintingPolicy(LO));
2667         printLocation(Out, S->getLocStart());
2668 
2669         if (Loc.getAs<PreStmt>())
2670           Out << "\\lPreStmt\\l;";
2671         else if (Loc.getAs<PostLoad>())
2672           Out << "\\lPostLoad\\l;";
2673         else if (Loc.getAs<PostStore>())
2674           Out << "\\lPostStore\\l";
2675         else if (Loc.getAs<PostLValue>())
2676           Out << "\\lPostLValue\\l";
2677 
2678 #if 0
2679           // FIXME: Replace with a general scheme to determine
2680           // the name of the check.
2681         if (GraphPrintCheckerState->isImplicitNullDeref(N))
2682           Out << "\\|Implicit-Null Dereference.\\l";
2683         else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2684           Out << "\\|Explicit-Null Dereference.\\l";
2685         else if (GraphPrintCheckerState->isUndefDeref(N))
2686           Out << "\\|Dereference of undefialied value.\\l";
2687         else if (GraphPrintCheckerState->isUndefStore(N))
2688           Out << "\\|Store to Undefined Loc.";
2689         else if (GraphPrintCheckerState->isUndefResult(N))
2690           Out << "\\|Result of operation is undefined.";
2691         else if (GraphPrintCheckerState->isNoReturnCall(N))
2692           Out << "\\|Call to function marked \"noreturn\".";
2693         else if (GraphPrintCheckerState->isBadCall(N))
2694           Out << "\\|Call to NULL/Undefined.";
2695         else if (GraphPrintCheckerState->isUndefArg(N))
2696           Out << "\\|Argument in call is undefined";
2697 #endif
2698 
2699         break;
2700       }
2701     }
2702 
2703     ProgramStateRef state = N->getState();
2704     Out << "\\|StateID: " << (const void*) state.get()
2705         << " NodeID: " << (const void*) N << "\\|";
2706     state->printDOT(Out);
2707 
2708     Out << "\\l";
2709 
2710     if (const ProgramPointTag *tag = Loc.getTag()) {
2711       Out << "\\|Tag: " << tag->getTagDescription();
2712       Out << "\\l";
2713     }
2714     return Out.str();
2715   }
2716 };
2717 } // end llvm namespace
2718 #endif
2719 
2720 void ExprEngine::ViewGraph(bool trim) {
2721 #ifndef NDEBUG
2722   if (trim) {
2723     std::vector<const ExplodedNode*> Src;
2724 
2725     // Flush any outstanding reports to make sure we cover all the nodes.
2726     // This does not cause them to get displayed.
2727     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2728       const_cast<BugType*>(*I)->FlushReports(BR);
2729 
2730     // Iterate through the reports and get their nodes.
2731     for (BugReporter::EQClasses_iterator
2732            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2733       ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2734       if (N) Src.push_back(N);
2735     }
2736 
2737     ViewGraph(Src);
2738   }
2739   else {
2740     GraphPrintCheckerState = this;
2741     GraphPrintSourceManager = &getContext().getSourceManager();
2742 
2743     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2744 
2745     GraphPrintCheckerState = nullptr;
2746     GraphPrintSourceManager = nullptr;
2747   }
2748 #endif
2749 }
2750 
2751 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2752 #ifndef NDEBUG
2753   GraphPrintCheckerState = this;
2754   GraphPrintSourceManager = &getContext().getSourceManager();
2755 
2756   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2757 
2758   if (!TrimmedG.get())
2759     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2760   else
2761     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2762 
2763   GraphPrintCheckerState = nullptr;
2764   GraphPrintSourceManager = nullptr;
2765 #endif
2766 }
2767