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