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