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