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