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