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