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