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