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 
48 //===----------------------------------------------------------------------===//
49 // Utility functions.
50 //===----------------------------------------------------------------------===//
51 
52 static inline Selector GetNullarySelector(const char* name, ASTContext &Ctx) {
53   IdentifierInfo* II = &Ctx.Idents.get(name);
54   return Ctx.Selectors.getSelector(0, &II);
55 }
56 
57 //===----------------------------------------------------------------------===//
58 // Engine construction and deletion.
59 //===----------------------------------------------------------------------===//
60 
61 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
62                        SetOfDecls *VisitedCallees)
63   : AMgr(mgr),
64     AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
65     Engine(*this, VisitedCallees),
66     G(Engine.getGraph()),
67     StateMgr(getContext(), mgr.getStoreManagerCreator(),
68              mgr.getConstraintManagerCreator(), G.getAllocator(),
69              *this),
70     SymMgr(StateMgr.getSymbolManager()),
71     svalBuilder(StateMgr.getSValBuilder()),
72     EntryNode(NULL),
73     currentStmt(NULL), currentStmtIdx(0), currentBuilderContext(0),
74     NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
75     RaiseSel(GetNullarySelector("raise", getContext())),
76     ObjCGCEnabled(gcEnabled), BR(mgr, *this) {
77 
78   if (mgr.shouldEagerlyTrimExplodedGraph()) {
79     // Enable eager node reclaimation when constructing the ExplodedGraph.
80     G.enableNodeReclamation();
81   }
82 }
83 
84 ExprEngine::~ExprEngine() {
85   BR.FlushReports();
86   delete [] NSExceptionInstanceRaiseSelectors;
87 }
88 
89 //===----------------------------------------------------------------------===//
90 // Utility methods.
91 //===----------------------------------------------------------------------===//
92 
93 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
94   ProgramStateRef state = StateMgr.getInitialState(InitLoc);
95   const Decl *D = InitLoc->getDecl();
96 
97   // Preconditions.
98   // FIXME: It would be nice if we had a more general mechanism to add
99   // such preconditions.  Some day.
100   do {
101 
102     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
103       // Precondition: the first argument of 'main' is an integer guaranteed
104       //  to be > 0.
105       const IdentifierInfo *II = FD->getIdentifier();
106       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
107         break;
108 
109       const ParmVarDecl *PD = FD->getParamDecl(0);
110       QualType T = PD->getType();
111       if (!T->isIntegerType())
112         break;
113 
114       const MemRegion *R = state->getRegion(PD, InitLoc);
115       if (!R)
116         break;
117 
118       SVal V = state->getSVal(loc::MemRegionVal(R));
119       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
120                                            svalBuilder.makeZeroVal(T),
121                                            getContext().IntTy);
122 
123       DefinedOrUnknownSVal *Constraint =
124         dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
125 
126       if (!Constraint)
127         break;
128 
129       if (ProgramStateRef newState = state->assume(*Constraint, true))
130         state = newState;
131     }
132     break;
133   }
134   while (0);
135 
136   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
137     // Precondition: 'self' is always non-null upon entry to an Objective-C
138     // method.
139     const ImplicitParamDecl *SelfD = MD->getSelfDecl();
140     const MemRegion *R = state->getRegion(SelfD, InitLoc);
141     SVal V = state->getSVal(loc::MemRegionVal(R));
142 
143     if (const Loc *LV = dyn_cast<Loc>(&V)) {
144       // Assume that the pointer value in 'self' is non-null.
145       state = state->assume(*LV, true);
146       assert(state && "'self' cannot be null");
147     }
148   }
149 
150   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
151     if (!MD->isStatic()) {
152       // Precondition: 'this' is always non-null upon entry to the
153       // top-level function.  This is our starting assumption for
154       // analyzing an "open" program.
155       const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
156       if (SFC->getParent() == 0) {
157         loc::MemRegionVal L(getCXXThisRegion(MD, SFC));
158         SVal V = state->getSVal(L);
159         if (const Loc *LV = dyn_cast<Loc>(&V)) {
160           state = state->assume(*LV, true);
161           assert(state && "'this' cannot be null");
162         }
163       }
164     }
165   }
166 
167   return state;
168 }
169 
170 //===----------------------------------------------------------------------===//
171 // Top-level transfer function logic (Dispatcher).
172 //===----------------------------------------------------------------------===//
173 
174 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
175 ///  logic for handling assumptions on symbolic values.
176 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
177                                               SVal cond, bool assumption) {
178   return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
179 }
180 
181 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
182   return getCheckerManager().wantsRegionChangeUpdate(state);
183 }
184 
185 ProgramStateRef
186 ExprEngine::processRegionChanges(ProgramStateRef state,
187                             const StoreManager::InvalidatedSymbols *invalidated,
188                                  ArrayRef<const MemRegion *> Explicits,
189                                  ArrayRef<const MemRegion *> Regions,
190                                  const CallOrObjCMessage *Call) {
191   return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
192                                                       Explicits, Regions, Call);
193 }
194 
195 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
196                             const char *NL, const char *Sep) {
197   getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
198 }
199 
200 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
201   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
202 }
203 
204 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
205                                    unsigned StmtIdx, NodeBuilderContext *Ctx) {
206   currentStmtIdx = StmtIdx;
207   currentBuilderContext = Ctx;
208 
209   switch (E.getKind()) {
210     case CFGElement::Invalid:
211       llvm_unreachable("Unexpected CFGElement kind.");
212     case CFGElement::Statement:
213       ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred);
214       return;
215     case CFGElement::Initializer:
216       ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred);
217       return;
218     case CFGElement::AutomaticObjectDtor:
219     case CFGElement::BaseDtor:
220     case CFGElement::MemberDtor:
221     case CFGElement::TemporaryDtor:
222       ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred);
223       return;
224   }
225 }
226 
227 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
228                                      const CFGStmt S,
229                                      const ExplodedNode *Pred,
230                                      const LocationContext *LC) {
231 
232   // Are we never purging state values?
233   if (AMgr.getPurgeMode() == PurgeNone)
234     return false;
235 
236   // Is this the beginning of a basic block?
237   if (isa<BlockEntrance>(Pred->getLocation()))
238     return true;
239 
240   // Is this on a non-expression?
241   if (!isa<Expr>(S.getStmt()))
242     return true;
243 
244   // Run before processing a call.
245   if (isa<CallExpr>(S.getStmt()))
246     return true;
247 
248   // Is this an expression that is consumed by another expression?  If so,
249   // postpone cleaning out the state.
250   ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
251   return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
252 }
253 
254 void ExprEngine::ProcessStmt(const CFGStmt S,
255                              ExplodedNode *Pred) {
256   // Reclaim any unnecessary nodes in the ExplodedGraph.
257   G.reclaimRecentlyAllocatedNodes();
258 
259   currentStmt = S.getStmt();
260   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
261                                 currentStmt->getLocStart(),
262                                 "Error evaluating statement");
263 
264   EntryNode = Pred;
265 
266   ProgramStateRef EntryState = EntryNode->getState();
267   CleanedState = EntryState;
268 
269   // Create the cleaned state.
270   const LocationContext *LC = EntryNode->getLocationContext();
271   SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager());
272 
273   if (shouldRemoveDeadBindings(AMgr, S, Pred, LC)) {
274     NumRemoveDeadBindings++;
275     getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
276 
277     const StackFrameContext *SFC = LC->getCurrentStackFrame();
278 
279     // Create a state in which dead bindings are removed from the environment
280     // and the store. TODO: The function should just return new env and store,
281     // not a new state.
282     CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
283   } else {
284     NumRemoveDeadBindingsSkipped++;
285   }
286 
287   // Process any special transfer function for dead symbols.
288   ExplodedNodeSet Tmp;
289   // A tag to track convenience transitions, which can be removed at cleanup.
290   static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
291 
292   if (!SymReaper.hasDeadSymbols()) {
293     // Generate a CleanedNode that has the environment and store cleaned
294     // up. Since no symbols are dead, we can optimize and not clean out
295     // the constraint manager.
296     StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
297     Bldr.generateNode(currentStmt, EntryNode, CleanedState, false, &cleanupTag);
298 
299   } else {
300     // Call checkers with the non-cleaned state so that they could query the
301     // values of the soon to be dead symbols.
302     ExplodedNodeSet CheckedSet;
303     getCheckerManager().runCheckersForDeadSymbols(CheckedSet, EntryNode,
304                                                  SymReaper, currentStmt, *this);
305 
306     // For each node in CheckedSet, generate CleanedNodes that have the
307     // environment, the store, and the constraints cleaned up but have the
308     // user-supplied states as the predecessors.
309     StmtNodeBuilder Bldr(CheckedSet, Tmp, *currentBuilderContext);
310     for (ExplodedNodeSet::const_iterator
311           I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
312       ProgramStateRef CheckerState = (*I)->getState();
313 
314       // The constraint manager has not been cleaned up yet, so clean up now.
315       CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
316                                                                SymReaper);
317 
318       assert(StateMgr.haveEqualEnvironments(CheckerState, EntryState) &&
319         "Checkers are not allowed to modify the Environment as a part of "
320         "checkDeadSymbols processing.");
321       assert(StateMgr.haveEqualStores(CheckerState, EntryState) &&
322         "Checkers are not allowed to modify the Store as a part of "
323         "checkDeadSymbols processing.");
324 
325       // Create a state based on CleanedState with CheckerState GDM and
326       // generate a transition to that state.
327       ProgramStateRef CleanedCheckerSt =
328         StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
329       Bldr.generateNode(currentStmt, *I, CleanedCheckerSt, false, &cleanupTag,
330                         ProgramPoint::PostPurgeDeadSymbolsKind);
331     }
332   }
333 
334   ExplodedNodeSet Dst;
335   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
336     ExplodedNodeSet DstI;
337     // Visit the statement.
338     Visit(currentStmt, *I, DstI);
339     Dst.insert(DstI);
340   }
341 
342   // Enqueue the new nodes onto the work list.
343   Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
344 
345   // NULL out these variables to cleanup.
346   CleanedState = NULL;
347   EntryNode = NULL;
348   currentStmt = 0;
349 }
350 
351 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
352                                     ExplodedNode *Pred) {
353   ExplodedNodeSet Dst;
354 
355   // We don't set EntryNode and currentStmt. And we don't clean up state.
356   const CXXCtorInitializer *BMI = Init.getInitializer();
357   const StackFrameContext *stackFrame =
358                            cast<StackFrameContext>(Pred->getLocationContext());
359   const CXXConstructorDecl *decl =
360                            cast<CXXConstructorDecl>(stackFrame->getDecl());
361   const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame);
362 
363   SVal thisVal = Pred->getState()->getSVal(thisReg);
364 
365   if (BMI->isAnyMemberInitializer()) {
366     ExplodedNodeSet AfterEval;
367 
368     // Evaluate the initializer.
369     Visit(BMI->getInit(), Pred, AfterEval);
370 
371     StmtNodeBuilder Bldr(AfterEval, Dst, *currentBuilderContext);
372     for (ExplodedNodeSet::iterator I = AfterEval.begin(),
373                                    E = AfterEval.end(); I != E; ++I){
374       ExplodedNode *P = *I;
375       ProgramStateRef state = P->getState();
376 
377       const FieldDecl *FD = BMI->getAnyMember();
378 
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, P, state);
388     }
389   } else {
390     assert(BMI->isBaseInitializer());
391 
392     // Get the base class declaration.
393     const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
394 
395     // Create the base object region.
396     SVal baseVal =
397         getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
398     const MemRegion *baseReg = baseVal.getAsRegion();
399     assert(baseReg);
400 
401     VisitCXXConstructExpr(ctorExpr, baseReg, Pred, Dst);
402   }
403 
404   // Enqueue the new nodes onto the work list.
405   Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
406 }
407 
408 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
409                                      ExplodedNode *Pred) {
410   ExplodedNodeSet Dst;
411   switch (D.getKind()) {
412   case CFGElement::AutomaticObjectDtor:
413     ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst);
414     break;
415   case CFGElement::BaseDtor:
416     ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst);
417     break;
418   case CFGElement::MemberDtor:
419     ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst);
420     break;
421   case CFGElement::TemporaryDtor:
422     ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst);
423     break;
424   default:
425     llvm_unreachable("Unexpected dtor kind.");
426   }
427 
428   // Enqueue the new nodes onto the work list.
429   Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
430 }
431 
432 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
433                                          ExplodedNode *Pred,
434                                          ExplodedNodeSet &Dst) {
435   ProgramStateRef state = Pred->getState();
436   const VarDecl *varDecl = Dtor.getVarDecl();
437 
438   QualType varType = varDecl->getType();
439 
440   if (const ReferenceType *refType = varType->getAs<ReferenceType>())
441     varType = refType->getPointeeType();
442 
443   const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
444   assert(recordDecl && "get CXXRecordDecl fail");
445   const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
446 
447   Loc dest = state->getLValue(varDecl, Pred->getLocationContext());
448 
449   VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
450                      Dtor.getTriggerStmt(), Pred, Dst);
451 }
452 
453 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
454                                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {}
455 
456 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
457                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {}
458 
459 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
460                                       ExplodedNode *Pred,
461                                       ExplodedNodeSet &Dst) {}
462 
463 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
464                        ExplodedNodeSet &DstTop) {
465   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
466                                 S->getLocStart(),
467                                 "Error evaluating statement");
468   ExplodedNodeSet Dst;
469   StmtNodeBuilder Bldr(Pred, DstTop, *currentBuilderContext);
470 
471   // Expressions to ignore.
472   if (const Expr *Ex = dyn_cast<Expr>(S))
473     S = Ex->IgnoreParens();
474 
475   // FIXME: add metadata to the CFG so that we can disable
476   //  this check when we KNOW that there is no block-level subexpression.
477   //  The motivation is that this check requires a hashtable lookup.
478 
479   if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S))
480     return;
481 
482   switch (S->getStmtClass()) {
483     // C++ and ARC stuff we don't support yet.
484     case Expr::ObjCIndirectCopyRestoreExprClass:
485     case Stmt::CXXDependentScopeMemberExprClass:
486     case Stmt::CXXPseudoDestructorExprClass:
487     case Stmt::CXXTryStmtClass:
488     case Stmt::CXXTypeidExprClass:
489     case Stmt::CXXUuidofExprClass:
490     case Stmt::CXXUnresolvedConstructExprClass:
491     case Stmt::CXXScalarValueInitExprClass:
492     case Stmt::DependentScopeDeclRefExprClass:
493     case Stmt::UnaryTypeTraitExprClass:
494     case Stmt::BinaryTypeTraitExprClass:
495     case Stmt::TypeTraitExprClass:
496     case Stmt::ArrayTypeTraitExprClass:
497     case Stmt::ExpressionTraitExprClass:
498     case Stmt::UnresolvedLookupExprClass:
499     case Stmt::UnresolvedMemberExprClass:
500     case Stmt::CXXNoexceptExprClass:
501     case Stmt::PackExpansionExprClass:
502     case Stmt::SubstNonTypeTemplateParmPackExprClass:
503     case Stmt::SEHTryStmtClass:
504     case Stmt::SEHExceptStmtClass:
505     case Stmt::LambdaExprClass:
506     case Stmt::SEHFinallyStmtClass: {
507       const ExplodedNode *node = Bldr.generateNode(S, Pred, Pred->getState(),
508                                                    /* sink */ true);
509       Engine.addAbortedBlock(node, currentBuilderContext->getBlock());
510       break;
511     }
512 
513     // We don't handle default arguments either yet, but we can fake it
514     // for now by just skipping them.
515     case Stmt::SubstNonTypeTemplateParmExprClass:
516     case Stmt::CXXDefaultArgExprClass:
517       break;
518 
519     case Stmt::ParenExprClass:
520       llvm_unreachable("ParenExprs already handled.");
521     case Stmt::GenericSelectionExprClass:
522       llvm_unreachable("GenericSelectionExprs already handled.");
523     // Cases that should never be evaluated simply because they shouldn't
524     // appear in the CFG.
525     case Stmt::BreakStmtClass:
526     case Stmt::CaseStmtClass:
527     case Stmt::CompoundStmtClass:
528     case Stmt::ContinueStmtClass:
529     case Stmt::CXXForRangeStmtClass:
530     case Stmt::DefaultStmtClass:
531     case Stmt::DoStmtClass:
532     case Stmt::ForStmtClass:
533     case Stmt::GotoStmtClass:
534     case Stmt::IfStmtClass:
535     case Stmt::IndirectGotoStmtClass:
536     case Stmt::LabelStmtClass:
537     case Stmt::NoStmtClass:
538     case Stmt::NullStmtClass:
539     case Stmt::SwitchStmtClass:
540     case Stmt::WhileStmtClass:
541     case Expr::MSDependentExistsStmtClass:
542       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
543 
544     case Stmt::GNUNullExprClass: {
545       // GNU __null is a pointer-width integer, not an actual pointer.
546       ProgramStateRef state = Pred->getState();
547       state = state->BindExpr(S, Pred->getLocationContext(),
548                               svalBuilder.makeIntValWithPtrWidth(0, false));
549       Bldr.generateNode(S, Pred, state);
550       break;
551     }
552 
553     case Stmt::ObjCAtSynchronizedStmtClass:
554       Bldr.takeNodes(Pred);
555       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
556       Bldr.addNodes(Dst);
557       break;
558 
559     // FIXME.
560     case Stmt::ObjCSubscriptRefExprClass:
561       break;
562 
563     case Stmt::ObjCPropertyRefExprClass:
564       // Implicitly handled by Environment::getSVal().
565       break;
566 
567     case Stmt::ImplicitValueInitExprClass: {
568       ProgramStateRef state = Pred->getState();
569       QualType ty = cast<ImplicitValueInitExpr>(S)->getType();
570       SVal val = svalBuilder.makeZeroVal(ty);
571       Bldr.generateNode(S, Pred, state->BindExpr(S, Pred->getLocationContext(),
572                                                  val));
573       break;
574     }
575 
576     case Stmt::ExprWithCleanupsClass:
577       Bldr.takeNodes(Pred);
578       Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst);
579       Bldr.addNodes(Dst);
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         CreateCXXTemporaryObject(Materialize, Pred, Dst);
840       else
841         Visit(Materialize->GetTemporaryExpr(), 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 /// Block entrance.  (Update counters).
979 void ExprEngine::processCFGBlockEntrance(NodeBuilderWithSinks &nodeBuilder) {
980 
981   // FIXME: Refactor this into a checker.
982   ExplodedNode *pred = nodeBuilder.getContext().getPred();
983 
984   if (nodeBuilder.getContext().getCurrentBlockCount() >= AMgr.getMaxVisit()) {
985     static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
986     nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
987   }
988 }
989 
990 //===----------------------------------------------------------------------===//
991 // Branch processing.
992 //===----------------------------------------------------------------------===//
993 
994 ProgramStateRef ExprEngine::MarkBranch(ProgramStateRef state,
995                                            const Stmt *Terminator,
996                                            const LocationContext *LCtx,
997                                            bool branchTaken) {
998 
999   switch (Terminator->getStmtClass()) {
1000     default:
1001       return state;
1002 
1003     case Stmt::BinaryOperatorClass: { // '&&' and '||'
1004 
1005       const BinaryOperator* B = cast<BinaryOperator>(Terminator);
1006       BinaryOperator::Opcode Op = B->getOpcode();
1007 
1008       assert (Op == BO_LAnd || Op == BO_LOr);
1009 
1010       // For &&, if we take the true branch, then the value of the whole
1011       // expression is that of the RHS expression.
1012       //
1013       // For ||, if we take the false branch, then the value of the whole
1014       // expression is that of the RHS expression.
1015 
1016       const Expr *Ex = (Op == BO_LAnd && branchTaken) ||
1017                        (Op == BO_LOr && !branchTaken)
1018                        ? B->getRHS() : B->getLHS();
1019 
1020       return state->BindExpr(B, LCtx, UndefinedVal(Ex));
1021     }
1022 
1023     case Stmt::BinaryConditionalOperatorClass:
1024     case Stmt::ConditionalOperatorClass: { // ?:
1025       const AbstractConditionalOperator* C
1026         = cast<AbstractConditionalOperator>(Terminator);
1027 
1028       // For ?, if branchTaken == true then the value is either the LHS or
1029       // the condition itself. (GNU extension).
1030 
1031       const Expr *Ex;
1032 
1033       if (branchTaken)
1034         Ex = C->getTrueExpr();
1035       else
1036         Ex = C->getFalseExpr();
1037 
1038       return state->BindExpr(C, LCtx, UndefinedVal(Ex));
1039     }
1040 
1041     case Stmt::ChooseExprClass: { // ?:
1042 
1043       const ChooseExpr *C = cast<ChooseExpr>(Terminator);
1044 
1045       const Expr *Ex = branchTaken ? C->getLHS() : C->getRHS();
1046       return state->BindExpr(C, LCtx, UndefinedVal(Ex));
1047     }
1048   }
1049 }
1050 
1051 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1052 /// to try to recover some path-sensitivity for casts of symbolic
1053 /// integers that promote their values (which are currently not tracked well).
1054 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1055 //  cast(s) did was sign-extend the original value.
1056 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1057                                 ProgramStateRef state,
1058                                 const Stmt *Condition,
1059                                 const LocationContext *LCtx,
1060                                 ASTContext &Ctx) {
1061 
1062   const Expr *Ex = dyn_cast<Expr>(Condition);
1063   if (!Ex)
1064     return UnknownVal();
1065 
1066   uint64_t bits = 0;
1067   bool bitsInit = false;
1068 
1069   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1070     QualType T = CE->getType();
1071 
1072     if (!T->isIntegerType())
1073       return UnknownVal();
1074 
1075     uint64_t newBits = Ctx.getTypeSize(T);
1076     if (!bitsInit || newBits < bits) {
1077       bitsInit = true;
1078       bits = newBits;
1079     }
1080 
1081     Ex = CE->getSubExpr();
1082   }
1083 
1084   // We reached a non-cast.  Is it a symbolic value?
1085   QualType T = Ex->getType();
1086 
1087   if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
1088     return UnknownVal();
1089 
1090   return state->getSVal(Ex, LCtx);
1091 }
1092 
1093 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1094                                NodeBuilderContext& BldCtx,
1095                                ExplodedNode *Pred,
1096                                ExplodedNodeSet &Dst,
1097                                const CFGBlock *DstT,
1098                                const CFGBlock *DstF) {
1099   currentBuilderContext = &BldCtx;
1100 
1101   // Check for NULL conditions; e.g. "for(;;)"
1102   if (!Condition) {
1103     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1104     NullCondBldr.markInfeasible(false);
1105     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1106     return;
1107   }
1108 
1109   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1110                                 Condition->getLocStart(),
1111                                 "Error evaluating branch");
1112 
1113   ExplodedNodeSet CheckersOutSet;
1114   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1115                                                     Pred, *this);
1116   // We generated only sinks.
1117   if (CheckersOutSet.empty())
1118     return;
1119 
1120   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1121   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1122                              E = CheckersOutSet.end(); E != I; ++I) {
1123     ExplodedNode *PredI = *I;
1124 
1125     if (PredI->isSink())
1126       continue;
1127 
1128     ProgramStateRef PrevState = Pred->getState();
1129     SVal X = PrevState->getSVal(Condition, Pred->getLocationContext());
1130 
1131     if (X.isUnknownOrUndef()) {
1132       // Give it a chance to recover from unknown.
1133       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1134         if (Ex->getType()->isIntegerType()) {
1135           // Try to recover some path-sensitivity.  Right now casts of symbolic
1136           // integers that promote their values are currently not tracked well.
1137           // If 'Condition' is such an expression, try and recover the
1138           // underlying value and use that instead.
1139           SVal recovered = RecoverCastedSymbol(getStateManager(),
1140                                                PrevState, Condition,
1141                                                Pred->getLocationContext(),
1142                                                getContext());
1143 
1144           if (!recovered.isUnknown()) {
1145             X = recovered;
1146           }
1147         }
1148       }
1149     }
1150 
1151     const LocationContext *LCtx = PredI->getLocationContext();
1152 
1153     // If the condition is still unknown, give up.
1154     if (X.isUnknownOrUndef()) {
1155       builder.generateNode(MarkBranch(PrevState, Term, LCtx, true),
1156                            true, PredI);
1157       builder.generateNode(MarkBranch(PrevState, Term, LCtx, false),
1158                            false, PredI);
1159       continue;
1160     }
1161 
1162     DefinedSVal V = cast<DefinedSVal>(X);
1163 
1164     // Process the true branch.
1165     if (builder.isFeasible(true)) {
1166       if (ProgramStateRef state = PrevState->assume(V, true))
1167         builder.generateNode(MarkBranch(state, Term, LCtx, true),
1168                              true, PredI);
1169       else
1170         builder.markInfeasible(true);
1171     }
1172 
1173     // Process the false branch.
1174     if (builder.isFeasible(false)) {
1175       if (ProgramStateRef state = PrevState->assume(V, false))
1176         builder.generateNode(MarkBranch(state, Term, LCtx, false),
1177                              false, PredI);
1178       else
1179         builder.markInfeasible(false);
1180     }
1181   }
1182   currentBuilderContext = 0;
1183 }
1184 
1185 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1186 ///  nodes by processing the 'effects' of a computed goto jump.
1187 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1188 
1189   ProgramStateRef state = builder.getState();
1190   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1191 
1192   // Three possibilities:
1193   //
1194   //   (1) We know the computed label.
1195   //   (2) The label is NULL (or some other constant), or Undefined.
1196   //   (3) We have no clue about the label.  Dispatch to all targets.
1197   //
1198 
1199   typedef IndirectGotoNodeBuilder::iterator iterator;
1200 
1201   if (isa<loc::GotoLabel>(V)) {
1202     const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
1203 
1204     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1205       if (I.getLabel() == L) {
1206         builder.generateNode(I, state);
1207         return;
1208       }
1209     }
1210 
1211     llvm_unreachable("No block with label.");
1212   }
1213 
1214   if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
1215     // Dispatch to the first target and mark it as a sink.
1216     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1217     // FIXME: add checker visit.
1218     //    UndefBranches.insert(N);
1219     return;
1220   }
1221 
1222   // This is really a catch-all.  We don't support symbolics yet.
1223   // FIXME: Implement dispatch for symbolic pointers.
1224 
1225   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1226     builder.generateNode(I, state);
1227 }
1228 
1229 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1230 ///  nodes when the control reaches the end of a function.
1231 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC) {
1232   StateMgr.EndPath(BC.Pred->getState());
1233   ExplodedNodeSet Dst;
1234   getCheckerManager().runCheckersForEndPath(BC, Dst, *this);
1235   Engine.enqueueEndOfFunction(Dst);
1236 }
1237 
1238 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1239 ///  nodes by processing the 'effects' of a switch statement.
1240 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1241   typedef SwitchNodeBuilder::iterator iterator;
1242   ProgramStateRef state = builder.getState();
1243   const Expr *CondE = builder.getCondition();
1244   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1245 
1246   if (CondV_untested.isUndef()) {
1247     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1248     // FIXME: add checker
1249     //UndefBranches.insert(N);
1250 
1251     return;
1252   }
1253   DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
1254 
1255   ProgramStateRef DefaultSt = state;
1256 
1257   iterator I = builder.begin(), EI = builder.end();
1258   bool defaultIsFeasible = I == EI;
1259 
1260   for ( ; I != EI; ++I) {
1261     // Successor may be pruned out during CFG construction.
1262     if (!I.getBlock())
1263       continue;
1264 
1265     const CaseStmt *Case = I.getCase();
1266 
1267     // Evaluate the LHS of the case value.
1268     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1269     assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1270 
1271     // Get the RHS of the case, if it exists.
1272     llvm::APSInt V2;
1273     if (const Expr *E = Case->getRHS())
1274       V2 = E->EvaluateKnownConstInt(getContext());
1275     else
1276       V2 = V1;
1277 
1278     // FIXME: Eventually we should replace the logic below with a range
1279     //  comparison, rather than concretize the values within the range.
1280     //  This should be easy once we have "ranges" for NonLVals.
1281 
1282     do {
1283       nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1284       DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1285                                                CondV, CaseVal);
1286 
1287       // Now "assume" that the case matches.
1288       if (ProgramStateRef stateNew = state->assume(Res, true)) {
1289         builder.generateCaseStmtNode(I, stateNew);
1290 
1291         // If CondV evaluates to a constant, then we know that this
1292         // is the *only* case that we can take, so stop evaluating the
1293         // others.
1294         if (isa<nonloc::ConcreteInt>(CondV))
1295           return;
1296       }
1297 
1298       // Now "assume" that the case doesn't match.  Add this state
1299       // to the default state (if it is feasible).
1300       if (DefaultSt) {
1301         if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1302           defaultIsFeasible = true;
1303           DefaultSt = stateNew;
1304         }
1305         else {
1306           defaultIsFeasible = false;
1307           DefaultSt = NULL;
1308         }
1309       }
1310 
1311       // Concretize the next value in the range.
1312       if (V1 == V2)
1313         break;
1314 
1315       ++V1;
1316       assert (V1 <= V2);
1317 
1318     } while (true);
1319   }
1320 
1321   if (!defaultIsFeasible)
1322     return;
1323 
1324   // If we have switch(enum value), the default branch is not
1325   // feasible if all of the enum constants not covered by 'case:' statements
1326   // are not feasible values for the switch condition.
1327   //
1328   // Note that this isn't as accurate as it could be.  Even if there isn't
1329   // a case for a particular enum value as long as that enum value isn't
1330   // feasible then it shouldn't be considered for making 'default:' reachable.
1331   const SwitchStmt *SS = builder.getSwitch();
1332   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1333   if (CondExpr->getType()->getAs<EnumType>()) {
1334     if (SS->isAllEnumCasesCovered())
1335       return;
1336   }
1337 
1338   builder.generateDefaultCaseNode(DefaultSt);
1339 }
1340 
1341 //===----------------------------------------------------------------------===//
1342 // Transfer functions: Loads and stores.
1343 //===----------------------------------------------------------------------===//
1344 
1345 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1346                                         ExplodedNode *Pred,
1347                                         ExplodedNodeSet &Dst) {
1348   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
1349 
1350   ProgramStateRef state = Pred->getState();
1351   const LocationContext *LCtx = Pred->getLocationContext();
1352 
1353   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1354     assert(Ex->isLValue());
1355     SVal V = state->getLValue(VD, Pred->getLocationContext());
1356 
1357     // For references, the 'lvalue' is the pointer address stored in the
1358     // reference region.
1359     if (VD->getType()->isReferenceType()) {
1360       if (const MemRegion *R = V.getAsRegion())
1361         V = state->getSVal(R);
1362       else
1363         V = UnknownVal();
1364     }
1365 
1366     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
1367                       ProgramPoint::PostLValueKind);
1368     return;
1369   }
1370   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1371     assert(!Ex->isLValue());
1372     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1373     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1374     return;
1375   }
1376   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1377     SVal V = svalBuilder.getFunctionPointer(FD);
1378     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
1379                       ProgramPoint::PostLValueKind);
1380     return;
1381   }
1382   assert (false &&
1383           "ValueDecl support for this ValueDecl not implemented.");
1384 }
1385 
1386 /// VisitArraySubscriptExpr - Transfer function for array accesses
1387 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1388                                              ExplodedNode *Pred,
1389                                              ExplodedNodeSet &Dst){
1390 
1391   const Expr *Base = A->getBase()->IgnoreParens();
1392   const Expr *Idx  = A->getIdx()->IgnoreParens();
1393 
1394 
1395   ExplodedNodeSet checkerPreStmt;
1396   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1397 
1398   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currentBuilderContext);
1399 
1400   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1401                                  ei = checkerPreStmt.end(); it != ei; ++it) {
1402     const LocationContext *LCtx = (*it)->getLocationContext();
1403     ProgramStateRef state = (*it)->getState();
1404     SVal V = state->getLValue(A->getType(),
1405                               state->getSVal(Idx, LCtx),
1406                               state->getSVal(Base, LCtx));
1407     assert(A->isLValue());
1408     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V),
1409                       false, 0, ProgramPoint::PostLValueKind);
1410   }
1411 }
1412 
1413 /// VisitMemberExpr - Transfer function for member expressions.
1414 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1415                                  ExplodedNodeSet &TopDst) {
1416 
1417   StmtNodeBuilder Bldr(Pred, TopDst, *currentBuilderContext);
1418   ExplodedNodeSet Dst;
1419   Decl *member = M->getMemberDecl();
1420   if (VarDecl *VD = dyn_cast<VarDecl>(member)) {
1421     assert(M->isLValue());
1422     Bldr.takeNodes(Pred);
1423     VisitCommonDeclRefExpr(M, VD, Pred, Dst);
1424     Bldr.addNodes(Dst);
1425     return;
1426   }
1427 
1428   FieldDecl *field = dyn_cast<FieldDecl>(member);
1429   if (!field) // FIXME: skipping member expressions for non-fields
1430     return;
1431 
1432   Expr *baseExpr = M->getBase()->IgnoreParens();
1433   ProgramStateRef state = Pred->getState();
1434   const LocationContext *LCtx = Pred->getLocationContext();
1435   SVal baseExprVal = state->getSVal(baseExpr, Pred->getLocationContext());
1436   if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
1437       isa<nonloc::CompoundVal>(baseExprVal) ||
1438       // FIXME: This can originate by conjuring a symbol for an unknown
1439       // temporary struct object, see test/Analysis/fields.c:
1440       // (p = getit()).x
1441       isa<nonloc::SymbolVal>(baseExprVal)) {
1442     Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, UnknownVal()));
1443     return;
1444   }
1445 
1446   // FIXME: Should we insert some assumption logic in here to determine
1447   // if "Base" is a valid piece of memory?  Before we put this assumption
1448   // later when using FieldOffset lvals (which we no longer have).
1449 
1450   // For all other cases, compute an lvalue.
1451   SVal L = state->getLValue(field, baseExprVal);
1452   if (M->isLValue())
1453     Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), false, 0,
1454                       ProgramPoint::PostLValueKind);
1455   else {
1456     Bldr.takeNodes(Pred);
1457     evalLoad(Dst, M, Pred, state, L);
1458     Bldr.addNodes(Dst);
1459   }
1460 }
1461 
1462 /// evalBind - Handle the semantics of binding a value to a specific location.
1463 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
1464 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
1465                           ExplodedNode *Pred,
1466                           SVal location, SVal Val, bool atDeclInit,
1467                           ProgramPoint::Kind PointKind) {
1468 
1469   // Do a previsit of the bind.
1470   ExplodedNodeSet CheckedSet;
1471   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
1472                                          StoreE, *this, PointKind);
1473 
1474   // TODO:AZ Remove TmpDst after NB refactoring is done.
1475   ExplodedNodeSet TmpDst;
1476   StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currentBuilderContext);
1477 
1478   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1479        I!=E; ++I) {
1480     ProgramStateRef state = (*I)->getState();
1481 
1482     if (atDeclInit) {
1483       const VarRegion *VR =
1484         cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
1485 
1486       state = state->bindDecl(VR, Val);
1487     } else {
1488       state = state->bindLoc(location, Val);
1489     }
1490 
1491     Bldr.generateNode(StoreE, *I, state, false, 0, PointKind);
1492   }
1493 
1494   Dst.insert(TmpDst);
1495 }
1496 
1497 /// evalStore - Handle the semantics of a store via an assignment.
1498 ///  @param Dst The node set to store generated state nodes
1499 ///  @param AssignE The assignment expression if the store happens in an
1500 ///         assignment.
1501 ///  @param LocatioinE The location expression that is stored to.
1502 ///  @param state The current simulation state
1503 ///  @param location The location to store the value
1504 ///  @param Val The value to be stored
1505 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
1506                              const Expr *LocationE,
1507                              ExplodedNode *Pred,
1508                              ProgramStateRef state, SVal location, SVal Val,
1509                              const ProgramPointTag *tag) {
1510   // Proceed with the store.  We use AssignE as the anchor for the PostStore
1511   // ProgramPoint if it is non-NULL, and LocationE otherwise.
1512   const Expr *StoreE = AssignE ? AssignE : LocationE;
1513 
1514   if (isa<loc::ObjCPropRef>(location)) {
1515     assert(false);
1516   }
1517 
1518   // Evaluate the location (checks for bad dereferences).
1519   ExplodedNodeSet Tmp;
1520   evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
1521 
1522   if (Tmp.empty())
1523     return;
1524 
1525   if (location.isUndef())
1526     return;
1527 
1528   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1529     evalBind(Dst, StoreE, *NI, location, Val, false,
1530              ProgramPoint::PostStoreKind);
1531 }
1532 
1533 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, const Expr *Ex,
1534                             ExplodedNode *Pred,
1535                             ProgramStateRef state, SVal location,
1536                             const ProgramPointTag *tag, QualType LoadTy) {
1537   assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
1538 
1539   if (isa<loc::ObjCPropRef>(location)) {
1540     assert(false);
1541   }
1542 
1543   // Are we loading from a region?  This actually results in two loads; one
1544   // to fetch the address of the referenced value and one to fetch the
1545   // referenced value.
1546   if (const TypedValueRegion *TR =
1547         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
1548 
1549     QualType ValTy = TR->getValueType();
1550     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
1551       static SimpleProgramPointTag
1552              loadReferenceTag("ExprEngine : Load Reference");
1553       ExplodedNodeSet Tmp;
1554       evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
1555                      getContext().getPointerType(RT->getPointeeType()));
1556 
1557       // Perform the load from the referenced value.
1558       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
1559         state = (*I)->getState();
1560         location = state->getSVal(Ex, (*I)->getLocationContext());
1561         evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
1562       }
1563       return;
1564     }
1565   }
1566 
1567   evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
1568 }
1569 
1570 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex,
1571                                   ExplodedNode *Pred,
1572                                   ProgramStateRef state, SVal location,
1573                                   const ProgramPointTag *tag, QualType LoadTy) {
1574 
1575   // Evaluate the location (checks for bad dereferences).
1576   ExplodedNodeSet Tmp;
1577   evalLocation(Tmp, Ex, Pred, state, location, tag, true);
1578   if (Tmp.empty())
1579     return;
1580 
1581   StmtNodeBuilder Bldr(Tmp, Dst, *currentBuilderContext);
1582   if (location.isUndef())
1583     return;
1584 
1585   // Proceed with the load.
1586   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1587     state = (*NI)->getState();
1588     const LocationContext *LCtx = (*NI)->getLocationContext();
1589 
1590     if (location.isUnknown()) {
1591       // This is important.  We must nuke the old binding.
1592       Bldr.generateNode(Ex, *NI, state->BindExpr(Ex, LCtx, UnknownVal()),
1593                         false, tag, ProgramPoint::PostLoadKind);
1594     }
1595     else {
1596       if (LoadTy.isNull())
1597         LoadTy = Ex->getType();
1598       SVal V = state->getSVal(cast<Loc>(location), LoadTy);
1599       Bldr.generateNode(Ex, *NI, state->bindExprAndLocation(Ex, LCtx,
1600                                                             location, V),
1601                         false, tag, ProgramPoint::PostLoadKind);
1602     }
1603   }
1604 }
1605 
1606 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
1607                                 ExplodedNode *Pred,
1608                                 ProgramStateRef state, SVal location,
1609                                 const ProgramPointTag *tag, bool isLoad) {
1610   StmtNodeBuilder BldrTop(Pred, Dst, *currentBuilderContext);
1611   // Early checks for performance reason.
1612   if (location.isUnknown()) {
1613     return;
1614   }
1615 
1616   ExplodedNodeSet Src;
1617   BldrTop.takeNodes(Pred);
1618   StmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext);
1619   if (Pred->getState() != state) {
1620     // Associate this new state with an ExplodedNode.
1621     // FIXME: If I pass null tag, the graph is incorrect, e.g for
1622     //   int *p;
1623     //   p = 0;
1624     //   *p = 0xDEADBEEF;
1625     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
1626     // instead "int *p" is noted as
1627     // "Variable 'p' initialized to a null pointer value"
1628 
1629     // FIXME: why is 'tag' not used instead of etag?
1630     static SimpleProgramPointTag etag("ExprEngine: Location");
1631 
1632     Bldr.generateNode(S, Pred, state, false, &etag);
1633   }
1634   ExplodedNodeSet Tmp;
1635   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, S,
1636                                              *this);
1637   BldrTop.addNodes(Tmp);
1638 }
1639 
1640 std::pair<const ProgramPointTag *, const ProgramPointTag*>
1641 ExprEngine::getEagerlyAssumeTags() {
1642   static SimpleProgramPointTag
1643          EagerlyAssumeTrue("ExprEngine : Eagerly Assume True"),
1644          EagerlyAssumeFalse("ExprEngine : Eagerly Assume False");
1645   return std::make_pair(&EagerlyAssumeTrue, &EagerlyAssumeFalse);
1646 }
1647 
1648 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
1649                                    const Expr *Ex) {
1650   StmtNodeBuilder Bldr(Src, Dst, *currentBuilderContext);
1651 
1652   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
1653     ExplodedNode *Pred = *I;
1654     // Test if the previous node was as the same expression.  This can happen
1655     // when the expression fails to evaluate to anything meaningful and
1656     // (as an optimization) we don't generate a node.
1657     ProgramPoint P = Pred->getLocation();
1658     if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
1659       continue;
1660     }
1661 
1662     ProgramStateRef state = Pred->getState();
1663     SVal V = state->getSVal(Ex, Pred->getLocationContext());
1664     nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V);
1665     if (SEV && SEV->isExpression()) {
1666       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
1667         getEagerlyAssumeTags();
1668 
1669       // First assume that the condition is true.
1670       if (ProgramStateRef StateTrue = state->assume(*SEV, true)) {
1671         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
1672         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
1673         Bldr.generateNode(Ex, Pred, StateTrue, false, tags.first);
1674       }
1675 
1676       // Next, assume that the condition is false.
1677       if (ProgramStateRef StateFalse = state->assume(*SEV, false)) {
1678         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
1679         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
1680         Bldr.generateNode(Ex, Pred, StateFalse, false, tags.second);
1681       }
1682     }
1683   }
1684 }
1685 
1686 void ExprEngine::VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred,
1687                               ExplodedNodeSet &Dst) {
1688   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
1689   // We have processed both the inputs and the outputs.  All of the outputs
1690   // should evaluate to Locs.  Nuke all of their values.
1691 
1692   // FIXME: Some day in the future it would be nice to allow a "plug-in"
1693   // which interprets the inline asm and stores proper results in the
1694   // outputs.
1695 
1696   ProgramStateRef state = Pred->getState();
1697 
1698   for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
1699        OE = A->end_outputs(); OI != OE; ++OI) {
1700     SVal X = state->getSVal(*OI, Pred->getLocationContext());
1701     assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
1702 
1703     if (isa<Loc>(X))
1704       state = state->bindLoc(cast<Loc>(X), UnknownVal());
1705   }
1706 
1707   Bldr.generateNode(A, Pred, state);
1708 }
1709 
1710 //===----------------------------------------------------------------------===//
1711 // Visualization.
1712 //===----------------------------------------------------------------------===//
1713 
1714 #ifndef NDEBUG
1715 static ExprEngine* GraphPrintCheckerState;
1716 static SourceManager* GraphPrintSourceManager;
1717 
1718 namespace llvm {
1719 template<>
1720 struct DOTGraphTraits<ExplodedNode*> :
1721   public DefaultDOTGraphTraits {
1722 
1723   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
1724 
1725   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
1726   // work.
1727   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
1728 
1729 #if 0
1730       // FIXME: Replace with a general scheme to tell if the node is
1731       // an error node.
1732     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
1733         GraphPrintCheckerState->isExplicitNullDeref(N) ||
1734         GraphPrintCheckerState->isUndefDeref(N) ||
1735         GraphPrintCheckerState->isUndefStore(N) ||
1736         GraphPrintCheckerState->isUndefControlFlow(N) ||
1737         GraphPrintCheckerState->isUndefResult(N) ||
1738         GraphPrintCheckerState->isBadCall(N) ||
1739         GraphPrintCheckerState->isUndefArg(N))
1740       return "color=\"red\",style=\"filled\"";
1741 
1742     if (GraphPrintCheckerState->isNoReturnCall(N))
1743       return "color=\"blue\",style=\"filled\"";
1744 #endif
1745     return "";
1746   }
1747 
1748   static std::string getNodeLabel(const ExplodedNode *N, void*){
1749 
1750     std::string sbuf;
1751     llvm::raw_string_ostream Out(sbuf);
1752 
1753     // Program Location.
1754     ProgramPoint Loc = N->getLocation();
1755 
1756     switch (Loc.getKind()) {
1757       case ProgramPoint::BlockEntranceKind:
1758         Out << "Block Entrance: B"
1759             << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
1760         break;
1761 
1762       case ProgramPoint::BlockExitKind:
1763         assert (false);
1764         break;
1765 
1766       case ProgramPoint::CallEnterKind:
1767         Out << "CallEnter";
1768         break;
1769 
1770       case ProgramPoint::CallExitKind:
1771         Out << "CallExit";
1772         break;
1773 
1774       default: {
1775         if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
1776           const Stmt *S = L->getStmt();
1777           SourceLocation SLoc = S->getLocStart();
1778 
1779           Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
1780           LangOptions LO; // FIXME.
1781           S->printPretty(Out, 0, PrintingPolicy(LO));
1782 
1783           if (SLoc.isFileID()) {
1784             Out << "\\lline="
1785               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
1786               << " col="
1787               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
1788               << "\\l";
1789           }
1790 
1791           if (isa<PreStmt>(Loc))
1792             Out << "\\lPreStmt\\l;";
1793           else if (isa<PostLoad>(Loc))
1794             Out << "\\lPostLoad\\l;";
1795           else if (isa<PostStore>(Loc))
1796             Out << "\\lPostStore\\l";
1797           else if (isa<PostLValue>(Loc))
1798             Out << "\\lPostLValue\\l";
1799 
1800 #if 0
1801             // FIXME: Replace with a general scheme to determine
1802             // the name of the check.
1803           if (GraphPrintCheckerState->isImplicitNullDeref(N))
1804             Out << "\\|Implicit-Null Dereference.\\l";
1805           else if (GraphPrintCheckerState->isExplicitNullDeref(N))
1806             Out << "\\|Explicit-Null Dereference.\\l";
1807           else if (GraphPrintCheckerState->isUndefDeref(N))
1808             Out << "\\|Dereference of undefialied value.\\l";
1809           else if (GraphPrintCheckerState->isUndefStore(N))
1810             Out << "\\|Store to Undefined Loc.";
1811           else if (GraphPrintCheckerState->isUndefResult(N))
1812             Out << "\\|Result of operation is undefined.";
1813           else if (GraphPrintCheckerState->isNoReturnCall(N))
1814             Out << "\\|Call to function marked \"noreturn\".";
1815           else if (GraphPrintCheckerState->isBadCall(N))
1816             Out << "\\|Call to NULL/Undefined.";
1817           else if (GraphPrintCheckerState->isUndefArg(N))
1818             Out << "\\|Argument in call is undefined";
1819 #endif
1820 
1821           break;
1822         }
1823 
1824         const BlockEdge &E = cast<BlockEdge>(Loc);
1825         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
1826             << E.getDst()->getBlockID()  << ')';
1827 
1828         if (const Stmt *T = E.getSrc()->getTerminator()) {
1829 
1830           SourceLocation SLoc = T->getLocStart();
1831 
1832           Out << "\\|Terminator: ";
1833           LangOptions LO; // FIXME.
1834           E.getSrc()->printTerminator(Out, LO);
1835 
1836           if (SLoc.isFileID()) {
1837             Out << "\\lline="
1838               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
1839               << " col="
1840               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
1841           }
1842 
1843           if (isa<SwitchStmt>(T)) {
1844             const Stmt *Label = E.getDst()->getLabel();
1845 
1846             if (Label) {
1847               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
1848                 Out << "\\lcase ";
1849                 LangOptions LO; // FIXME.
1850                 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
1851 
1852                 if (const Stmt *RHS = C->getRHS()) {
1853                   Out << " .. ";
1854                   RHS->printPretty(Out, 0, PrintingPolicy(LO));
1855                 }
1856 
1857                 Out << ":";
1858               }
1859               else {
1860                 assert (isa<DefaultStmt>(Label));
1861                 Out << "\\ldefault:";
1862               }
1863             }
1864             else
1865               Out << "\\l(implicit) default:";
1866           }
1867           else if (isa<IndirectGotoStmt>(T)) {
1868             // FIXME
1869           }
1870           else {
1871             Out << "\\lCondition: ";
1872             if (*E.getSrc()->succ_begin() == E.getDst())
1873               Out << "true";
1874             else
1875               Out << "false";
1876           }
1877 
1878           Out << "\\l";
1879         }
1880 
1881 #if 0
1882           // FIXME: Replace with a general scheme to determine
1883           // the name of the check.
1884         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
1885           Out << "\\|Control-flow based on\\lUndefined value.\\l";
1886         }
1887 #endif
1888       }
1889     }
1890 
1891     ProgramStateRef state = N->getState();
1892     Out << "\\|StateID: " << (void*) state.getPtr()
1893         << " NodeID: " << (void*) N << "\\|";
1894     state->printDOT(Out);
1895 
1896     Out << "\\l";
1897 
1898     if (const ProgramPointTag *tag = Loc.getTag()) {
1899       Out << "\\|Tag: " << tag->getTagDescription();
1900       Out << "\\l";
1901     }
1902     return Out.str();
1903   }
1904 };
1905 } // end llvm namespace
1906 #endif
1907 
1908 #ifndef NDEBUG
1909 template <typename ITERATOR>
1910 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
1911 
1912 template <> ExplodedNode*
1913 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
1914   (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
1915   return I->first;
1916 }
1917 #endif
1918 
1919 void ExprEngine::ViewGraph(bool trim) {
1920 #ifndef NDEBUG
1921   if (trim) {
1922     std::vector<ExplodedNode*> Src;
1923 
1924     // Flush any outstanding reports to make sure we cover all the nodes.
1925     // This does not cause them to get displayed.
1926     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
1927       const_cast<BugType*>(*I)->FlushReports(BR);
1928 
1929     // Iterate through the reports and get their nodes.
1930     for (BugReporter::EQClasses_iterator
1931            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
1932       BugReportEquivClass& EQ = *EI;
1933       const BugReport &R = **EQ.begin();
1934       ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode());
1935       if (N) Src.push_back(N);
1936     }
1937 
1938     ViewGraph(&Src[0], &Src[0]+Src.size());
1939   }
1940   else {
1941     GraphPrintCheckerState = this;
1942     GraphPrintSourceManager = &getContext().getSourceManager();
1943 
1944     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
1945 
1946     GraphPrintCheckerState = NULL;
1947     GraphPrintSourceManager = NULL;
1948   }
1949 #endif
1950 }
1951 
1952 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
1953 #ifndef NDEBUG
1954   GraphPrintCheckerState = this;
1955   GraphPrintSourceManager = &getContext().getSourceManager();
1956 
1957   std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
1958 
1959   if (!TrimmedG.get())
1960     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
1961   else
1962     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
1963 
1964   GraphPrintCheckerState = NULL;
1965   GraphPrintSourceManager = NULL;
1966 #endif
1967 }
1968