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