ExprEngine.cpp revision ed2e2de580f840385f25a188ed48d2a14948af76
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
38using namespace clang;
39using namespace ento;
40using llvm::APSInt;
41
42STATISTIC(NumRemoveDeadBindings,
43            "The # of times RemoveDeadBindings is called");
44STATISTIC(NumMaxBlockCountReached,
45            "The # of aborted paths due to reaching the maximum block count in "
46            "a top level function");
47STATISTIC(NumMaxBlockCountReachedInInlined,
48            "The # of aborted paths due to reaching the maximum block count in "
49            "an inlined function");
50STATISTIC(NumTimesRetriedWithoutInlining,
51            "The # of times we re-evaluated a call without inlining");
52
53//===----------------------------------------------------------------------===//
54// Engine construction and deletion.
55//===----------------------------------------------------------------------===//
56
57ExprEngine::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
83ExprEngine::~ExprEngine() {
84  BR.FlushReports();
85}
86
87//===----------------------------------------------------------------------===//
88// Utility methods.
89//===----------------------------------------------------------------------===//
90
91ProgramStateRef 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
169ProgramStateRef
170ExprEngine::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.
236ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
237                                              SVal cond, bool assumption) {
238  return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
239}
240
241bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
242  return getCheckerManager().wantsRegionChangeUpdate(state);
243}
244
245ProgramStateRef
246ExprEngine::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
255void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
256                            const char *NL, const char *Sep) {
257  getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
258}
259
260void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
261  getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
262}
263
264void 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
286static 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
313void 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
395void 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
426void 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
510void 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
534void 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
553void 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
573void 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
590void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
591                                      ExplodedNode *Pred,
592                                      ExplodedNodeSet &Dst) {}
593
594void 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::CXXStdInitializerListExprClass:
611    case Stmt::CXXTryStmtClass:
612    case Stmt::CXXTypeidExprClass:
613    case Stmt::CXXUuidofExprClass:
614    case Stmt::MSPropertyRefExprClass:
615    case Stmt::CXXUnresolvedConstructExprClass:
616    case Stmt::DependentScopeDeclRefExprClass:
617    case Stmt::UnaryTypeTraitExprClass:
618    case Stmt::BinaryTypeTraitExprClass:
619    case Stmt::TypeTraitExprClass:
620    case Stmt::ArrayTypeTraitExprClass:
621    case Stmt::ExpressionTraitExprClass:
622    case Stmt::UnresolvedLookupExprClass:
623    case Stmt::UnresolvedMemberExprClass:
624    case Stmt::CXXNoexceptExprClass:
625    case Stmt::PackExpansionExprClass:
626    case Stmt::SubstNonTypeTemplateParmPackExprClass:
627    case Stmt::FunctionParmPackExprClass:
628    case Stmt::SEHTryStmtClass:
629    case Stmt::SEHExceptStmtClass:
630    case Stmt::LambdaExprClass:
631    case Stmt::SEHFinallyStmtClass: {
632      const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
633      Engine.addAbortedBlock(node, currBldrCtx->getBlock());
634      break;
635    }
636
637    case Stmt::ParenExprClass:
638      llvm_unreachable("ParenExprs already handled.");
639    case Stmt::GenericSelectionExprClass:
640      llvm_unreachable("GenericSelectionExprs already handled.");
641    // Cases that should never be evaluated simply because they shouldn't
642    // appear in the CFG.
643    case Stmt::BreakStmtClass:
644    case Stmt::CaseStmtClass:
645    case Stmt::CompoundStmtClass:
646    case Stmt::ContinueStmtClass:
647    case Stmt::CXXForRangeStmtClass:
648    case Stmt::DefaultStmtClass:
649    case Stmt::DoStmtClass:
650    case Stmt::ForStmtClass:
651    case Stmt::GotoStmtClass:
652    case Stmt::IfStmtClass:
653    case Stmt::IndirectGotoStmtClass:
654    case Stmt::LabelStmtClass:
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::AttributedStmtClass:
712    case Stmt::IntegerLiteralClass:
713    case Stmt::CharacterLiteralClass:
714    case Stmt::ImplicitValueInitExprClass:
715    case Stmt::CXXScalarValueInitExprClass:
716    case Stmt::CXXBoolLiteralExprClass:
717    case Stmt::ObjCBoolLiteralExprClass:
718    case Stmt::FloatingLiteralClass:
719    case Stmt::SizeOfPackExprClass:
720    case Stmt::StringLiteralClass:
721    case Stmt::ObjCStringLiteralClass:
722    case Stmt::CXXBindTemporaryExprClass:
723    case Stmt::SubstNonTypeTemplateParmExprClass:
724    case Stmt::CXXNullPtrLiteralExprClass: {
725      Bldr.takeNodes(Pred);
726      ExplodedNodeSet preVisit;
727      getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
728      getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
729      Bldr.addNodes(Dst);
730      break;
731    }
732
733    case Stmt::CXXDefaultArgExprClass: {
734      Bldr.takeNodes(Pred);
735      ExplodedNodeSet PreVisit;
736      getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
737
738      ExplodedNodeSet Tmp;
739      StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
740
741      const LocationContext *LCtx = Pred->getLocationContext();
742      const CXXDefaultArgExpr *DefaultE = cast<CXXDefaultArgExpr>(S);
743      const Expr *ArgE = DefaultE->getExpr();
744
745      bool IsTemporary = false;
746      if (const MaterializeTemporaryExpr *MTE =
747            dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
748        ArgE = MTE->GetTemporaryExpr();
749        IsTemporary = true;
750      }
751
752      Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
753      if (!ConstantVal)
754        ConstantVal = UnknownVal();
755
756      for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
757           I != E; ++I) {
758        ProgramStateRef State = (*I)->getState();
759        State = State->BindExpr(DefaultE, LCtx, *ConstantVal);
760        if (IsTemporary)
761          State = createTemporaryRegionIfNeeded(State, LCtx, DefaultE,
762                                                DefaultE);
763        Bldr2.generateNode(S, *I, State);
764      }
765
766      getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
767      Bldr.addNodes(Dst);
768      break;
769    }
770
771    case Expr::ObjCArrayLiteralClass:
772    case Expr::ObjCDictionaryLiteralClass:
773      // FIXME: explicitly model with a region and the actual contents
774      // of the container.  For now, conjure a symbol.
775    case Expr::ObjCBoxedExprClass: {
776      Bldr.takeNodes(Pred);
777
778      ExplodedNodeSet preVisit;
779      getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
780
781      ExplodedNodeSet Tmp;
782      StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
783
784      const Expr *Ex = cast<Expr>(S);
785      QualType resultType = Ex->getType();
786
787      for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
788           it != et; ++it) {
789        ExplodedNode *N = *it;
790        const LocationContext *LCtx = N->getLocationContext();
791        SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType,
792                                                   currBldrCtx->blockCount());
793        ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
794        Bldr2.generateNode(S, N, state);
795      }
796
797      getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
798      Bldr.addNodes(Dst);
799      break;
800    }
801
802    case Stmt::ArraySubscriptExprClass:
803      Bldr.takeNodes(Pred);
804      VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
805      Bldr.addNodes(Dst);
806      break;
807
808    case Stmt::GCCAsmStmtClass:
809      Bldr.takeNodes(Pred);
810      VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
811      Bldr.addNodes(Dst);
812      break;
813
814    case Stmt::MSAsmStmtClass:
815      Bldr.takeNodes(Pred);
816      VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
817      Bldr.addNodes(Dst);
818      break;
819
820    case Stmt::BlockExprClass:
821      Bldr.takeNodes(Pred);
822      VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
823      Bldr.addNodes(Dst);
824      break;
825
826    case Stmt::BinaryOperatorClass: {
827      const BinaryOperator* B = cast<BinaryOperator>(S);
828      if (B->isLogicalOp()) {
829        Bldr.takeNodes(Pred);
830        VisitLogicalExpr(B, Pred, Dst);
831        Bldr.addNodes(Dst);
832        break;
833      }
834      else if (B->getOpcode() == BO_Comma) {
835        ProgramStateRef state = Pred->getState();
836        Bldr.generateNode(B, Pred,
837                          state->BindExpr(B, Pred->getLocationContext(),
838                                          state->getSVal(B->getRHS(),
839                                                  Pred->getLocationContext())));
840        break;
841      }
842
843      Bldr.takeNodes(Pred);
844
845      if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
846          (B->isRelationalOp() || B->isEqualityOp())) {
847        ExplodedNodeSet Tmp;
848        VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
849        evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
850      }
851      else
852        VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
853
854      Bldr.addNodes(Dst);
855      break;
856    }
857
858    case Stmt::CXXOperatorCallExprClass: {
859      const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
860
861      // For instance method operators, make sure the 'this' argument has a
862      // valid region.
863      const Decl *Callee = OCE->getCalleeDecl();
864      if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
865        if (MD->isInstance()) {
866          ProgramStateRef State = Pred->getState();
867          const LocationContext *LCtx = Pred->getLocationContext();
868          ProgramStateRef NewState =
869            createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
870          if (NewState != State) {
871            Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0,
872                                     ProgramPoint::PreStmtKind);
873            // Did we cache out?
874            if (!Pred)
875              break;
876          }
877        }
878      }
879      // FALLTHROUGH
880    }
881    case Stmt::CallExprClass:
882    case Stmt::CXXMemberCallExprClass:
883    case Stmt::UserDefinedLiteralClass: {
884      Bldr.takeNodes(Pred);
885      VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
886      Bldr.addNodes(Dst);
887      break;
888    }
889
890    case Stmt::CXXCatchStmtClass: {
891      Bldr.takeNodes(Pred);
892      VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
893      Bldr.addNodes(Dst);
894      break;
895    }
896
897    case Stmt::CXXTemporaryObjectExprClass:
898    case Stmt::CXXConstructExprClass: {
899      Bldr.takeNodes(Pred);
900      VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
901      Bldr.addNodes(Dst);
902      break;
903    }
904
905    case Stmt::CXXNewExprClass: {
906      Bldr.takeNodes(Pred);
907      ExplodedNodeSet PostVisit;
908      VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
909      getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
910      Bldr.addNodes(Dst);
911      break;
912    }
913
914    case Stmt::CXXDeleteExprClass: {
915      Bldr.takeNodes(Pred);
916      ExplodedNodeSet PreVisit;
917      const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
918      getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
919
920      for (ExplodedNodeSet::iterator i = PreVisit.begin(),
921                                     e = PreVisit.end(); i != e ; ++i)
922        VisitCXXDeleteExpr(CDE, *i, Dst);
923
924      Bldr.addNodes(Dst);
925      break;
926    }
927      // FIXME: ChooseExpr is really a constant.  We need to fix
928      //        the CFG do not model them as explicit control-flow.
929
930    case Stmt::ChooseExprClass: { // __builtin_choose_expr
931      Bldr.takeNodes(Pred);
932      const ChooseExpr *C = cast<ChooseExpr>(S);
933      VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
934      Bldr.addNodes(Dst);
935      break;
936    }
937
938    case Stmt::CompoundAssignOperatorClass:
939      Bldr.takeNodes(Pred);
940      VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
941      Bldr.addNodes(Dst);
942      break;
943
944    case Stmt::CompoundLiteralExprClass:
945      Bldr.takeNodes(Pred);
946      VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
947      Bldr.addNodes(Dst);
948      break;
949
950    case Stmt::BinaryConditionalOperatorClass:
951    case Stmt::ConditionalOperatorClass: { // '?' operator
952      Bldr.takeNodes(Pred);
953      const AbstractConditionalOperator *C
954        = cast<AbstractConditionalOperator>(S);
955      VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
956      Bldr.addNodes(Dst);
957      break;
958    }
959
960    case Stmt::CXXThisExprClass:
961      Bldr.takeNodes(Pred);
962      VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
963      Bldr.addNodes(Dst);
964      break;
965
966    case Stmt::DeclRefExprClass: {
967      Bldr.takeNodes(Pred);
968      const DeclRefExpr *DE = cast<DeclRefExpr>(S);
969      VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
970      Bldr.addNodes(Dst);
971      break;
972    }
973
974    case Stmt::DeclStmtClass:
975      Bldr.takeNodes(Pred);
976      VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
977      Bldr.addNodes(Dst);
978      break;
979
980    case Stmt::ImplicitCastExprClass:
981    case Stmt::CStyleCastExprClass:
982    case Stmt::CXXStaticCastExprClass:
983    case Stmt::CXXDynamicCastExprClass:
984    case Stmt::CXXReinterpretCastExprClass:
985    case Stmt::CXXConstCastExprClass:
986    case Stmt::CXXFunctionalCastExprClass:
987    case Stmt::ObjCBridgedCastExprClass: {
988      Bldr.takeNodes(Pred);
989      const CastExpr *C = cast<CastExpr>(S);
990      // Handle the previsit checks.
991      ExplodedNodeSet dstPrevisit;
992      getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
993
994      // Handle the expression itself.
995      ExplodedNodeSet dstExpr;
996      for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
997                                     e = dstPrevisit.end(); i != e ; ++i) {
998        VisitCast(C, C->getSubExpr(), *i, dstExpr);
999      }
1000
1001      // Handle the postvisit checks.
1002      getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1003      Bldr.addNodes(Dst);
1004      break;
1005    }
1006
1007    case Expr::MaterializeTemporaryExprClass: {
1008      Bldr.takeNodes(Pred);
1009      const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1010      CreateCXXTemporaryObject(MTE, Pred, Dst);
1011      Bldr.addNodes(Dst);
1012      break;
1013    }
1014
1015    case Stmt::InitListExprClass:
1016      Bldr.takeNodes(Pred);
1017      VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1018      Bldr.addNodes(Dst);
1019      break;
1020
1021    case Stmt::MemberExprClass:
1022      Bldr.takeNodes(Pred);
1023      VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1024      Bldr.addNodes(Dst);
1025      break;
1026
1027    case Stmt::ObjCIvarRefExprClass:
1028      Bldr.takeNodes(Pred);
1029      VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1030      Bldr.addNodes(Dst);
1031      break;
1032
1033    case Stmt::ObjCForCollectionStmtClass:
1034      Bldr.takeNodes(Pred);
1035      VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1036      Bldr.addNodes(Dst);
1037      break;
1038
1039    case Stmt::ObjCMessageExprClass:
1040      Bldr.takeNodes(Pred);
1041      VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1042      Bldr.addNodes(Dst);
1043      break;
1044
1045    case Stmt::ObjCAtThrowStmtClass:
1046    case Stmt::CXXThrowExprClass:
1047      // FIXME: This is not complete.  We basically treat @throw as
1048      // an abort.
1049      Bldr.generateSink(S, Pred, Pred->getState());
1050      break;
1051
1052    case Stmt::ReturnStmtClass:
1053      Bldr.takeNodes(Pred);
1054      VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1055      Bldr.addNodes(Dst);
1056      break;
1057
1058    case Stmt::OffsetOfExprClass:
1059      Bldr.takeNodes(Pred);
1060      VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1061      Bldr.addNodes(Dst);
1062      break;
1063
1064    case Stmt::UnaryExprOrTypeTraitExprClass:
1065      Bldr.takeNodes(Pred);
1066      VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1067                                    Pred, Dst);
1068      Bldr.addNodes(Dst);
1069      break;
1070
1071    case Stmt::StmtExprClass: {
1072      const StmtExpr *SE = cast<StmtExpr>(S);
1073
1074      if (SE->getSubStmt()->body_empty()) {
1075        // Empty statement expression.
1076        assert(SE->getType() == getContext().VoidTy
1077               && "Empty statement expression must have void type.");
1078        break;
1079      }
1080
1081      if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1082        ProgramStateRef state = Pred->getState();
1083        Bldr.generateNode(SE, Pred,
1084                          state->BindExpr(SE, Pred->getLocationContext(),
1085                                          state->getSVal(LastExpr,
1086                                                  Pred->getLocationContext())));
1087      }
1088      break;
1089    }
1090
1091    case Stmt::UnaryOperatorClass: {
1092      Bldr.takeNodes(Pred);
1093      const UnaryOperator *U = cast<UnaryOperator>(S);
1094      if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1095        ExplodedNodeSet Tmp;
1096        VisitUnaryOperator(U, Pred, Tmp);
1097        evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1098      }
1099      else
1100        VisitUnaryOperator(U, Pred, Dst);
1101      Bldr.addNodes(Dst);
1102      break;
1103    }
1104
1105    case Stmt::PseudoObjectExprClass: {
1106      Bldr.takeNodes(Pred);
1107      ProgramStateRef state = Pred->getState();
1108      const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1109      if (const Expr *Result = PE->getResultExpr()) {
1110        SVal V = state->getSVal(Result, Pred->getLocationContext());
1111        Bldr.generateNode(S, Pred,
1112                          state->BindExpr(S, Pred->getLocationContext(), V));
1113      }
1114      else
1115        Bldr.generateNode(S, Pred,
1116                          state->BindExpr(S, Pred->getLocationContext(),
1117                                                   UnknownVal()));
1118
1119      Bldr.addNodes(Dst);
1120      break;
1121    }
1122  }
1123}
1124
1125bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1126                                       const LocationContext *CalleeLC) {
1127  const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1128  const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1129  assert(CalleeSF && CallerSF);
1130  ExplodedNode *BeforeProcessingCall = 0;
1131  const Stmt *CE = CalleeSF->getCallSite();
1132
1133  // Find the first node before we started processing the call expression.
1134  while (N) {
1135    ProgramPoint L = N->getLocation();
1136    BeforeProcessingCall = N;
1137    N = N->pred_empty() ? NULL : *(N->pred_begin());
1138
1139    // Skip the nodes corresponding to the inlined code.
1140    if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1141      continue;
1142    // We reached the caller. Find the node right before we started
1143    // processing the call.
1144    if (L.isPurgeKind())
1145      continue;
1146    if (L.getAs<PreImplicitCall>())
1147      continue;
1148    if (L.getAs<CallEnter>())
1149      continue;
1150    if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1151      if (SP->getStmt() == CE)
1152        continue;
1153    break;
1154  }
1155
1156  if (!BeforeProcessingCall)
1157    return false;
1158
1159  // TODO: Clean up the unneeded nodes.
1160
1161  // Build an Epsilon node from which we will restart the analyzes.
1162  // Note that CE is permitted to be NULL!
1163  ProgramPoint NewNodeLoc =
1164               EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1165  // Add the special flag to GDM to signal retrying with no inlining.
1166  // Note, changing the state ensures that we are not going to cache out.
1167  ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1168  NewNodeState =
1169    NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1170
1171  // Make the new node a successor of BeforeProcessingCall.
1172  bool IsNew = false;
1173  ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1174  // We cached out at this point. Caching out is common due to us backtracking
1175  // from the inlined function, which might spawn several paths.
1176  if (!IsNew)
1177    return true;
1178
1179  NewNode->addPredecessor(BeforeProcessingCall, G);
1180
1181  // Add the new node to the work list.
1182  Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1183                                  CalleeSF->getIndex());
1184  NumTimesRetriedWithoutInlining++;
1185  return true;
1186}
1187
1188/// Block entrance.  (Update counters).
1189void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1190                                         NodeBuilderWithSinks &nodeBuilder,
1191                                         ExplodedNode *Pred) {
1192
1193  // FIXME: Refactor this into a checker.
1194  if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
1195    static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
1196    const ExplodedNode *Sink =
1197                   nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1198
1199    // Check if we stopped at the top level function or not.
1200    // Root node should have the location context of the top most function.
1201    const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1202    const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1203    const LocationContext *RootLC =
1204                        (*G.roots_begin())->getLocation().getLocationContext();
1205    if (RootLC->getCurrentStackFrame() != CalleeSF) {
1206      Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1207
1208      // Re-run the call evaluation without inlining it, by storing the
1209      // no-inlining policy in the state and enqueuing the new work item on
1210      // the list. Replay should almost never fail. Use the stats to catch it
1211      // if it does.
1212      if ((!AMgr.options.NoRetryExhausted &&
1213           replayWithoutInlining(Pred, CalleeLC)))
1214        return;
1215      NumMaxBlockCountReachedInInlined++;
1216    } else
1217      NumMaxBlockCountReached++;
1218
1219    // Make sink nodes as exhausted(for stats) only if retry failed.
1220    Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1221  }
1222}
1223
1224//===----------------------------------------------------------------------===//
1225// Branch processing.
1226//===----------------------------------------------------------------------===//
1227
1228/// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1229/// to try to recover some path-sensitivity for casts of symbolic
1230/// integers that promote their values (which are currently not tracked well).
1231/// This function returns the SVal bound to Condition->IgnoreCasts if all the
1232//  cast(s) did was sign-extend the original value.
1233static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1234                                ProgramStateRef state,
1235                                const Stmt *Condition,
1236                                const LocationContext *LCtx,
1237                                ASTContext &Ctx) {
1238
1239  const Expr *Ex = dyn_cast<Expr>(Condition);
1240  if (!Ex)
1241    return UnknownVal();
1242
1243  uint64_t bits = 0;
1244  bool bitsInit = false;
1245
1246  while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1247    QualType T = CE->getType();
1248
1249    if (!T->isIntegralOrEnumerationType())
1250      return UnknownVal();
1251
1252    uint64_t newBits = Ctx.getTypeSize(T);
1253    if (!bitsInit || newBits < bits) {
1254      bitsInit = true;
1255      bits = newBits;
1256    }
1257
1258    Ex = CE->getSubExpr();
1259  }
1260
1261  // We reached a non-cast.  Is it a symbolic value?
1262  QualType T = Ex->getType();
1263
1264  if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1265      Ctx.getTypeSize(T) > bits)
1266    return UnknownVal();
1267
1268  return state->getSVal(Ex, LCtx);
1269}
1270
1271static const Stmt *ResolveCondition(const Stmt *Condition,
1272                                    const CFGBlock *B) {
1273  if (const Expr *Ex = dyn_cast<Expr>(Condition))
1274    Condition = Ex->IgnoreParens();
1275
1276  const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1277  if (!BO || !BO->isLogicalOp())
1278    return Condition;
1279
1280  // For logical operations, we still have the case where some branches
1281  // use the traditional "merge" approach and others sink the branch
1282  // directly into the basic blocks representing the logical operation.
1283  // We need to distinguish between those two cases here.
1284
1285  // The invariants are still shifting, but it is possible that the
1286  // last element in a CFGBlock is not a CFGStmt.  Look for the last
1287  // CFGStmt as the value of the condition.
1288  CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1289  for (; I != E; ++I) {
1290    CFGElement Elem = *I;
1291    Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1292    if (!CS)
1293      continue;
1294    if (CS->getStmt() != Condition)
1295      break;
1296    return Condition;
1297  }
1298
1299  assert(I != E);
1300
1301  while (Condition) {
1302    BO = dyn_cast<BinaryOperator>(Condition);
1303    if (!BO || !BO->isLogicalOp())
1304      return Condition;
1305    Condition = BO->getRHS()->IgnoreParens();
1306  }
1307  llvm_unreachable("could not resolve condition");
1308}
1309
1310void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1311                               NodeBuilderContext& BldCtx,
1312                               ExplodedNode *Pred,
1313                               ExplodedNodeSet &Dst,
1314                               const CFGBlock *DstT,
1315                               const CFGBlock *DstF) {
1316  currBldrCtx = &BldCtx;
1317
1318  // Check for NULL conditions; e.g. "for(;;)"
1319  if (!Condition) {
1320    BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1321    NullCondBldr.markInfeasible(false);
1322    NullCondBldr.generateNode(Pred->getState(), true, Pred);
1323    return;
1324  }
1325
1326
1327  // Resolve the condition in the precense of nested '||' and '&&'.
1328  if (const Expr *Ex = dyn_cast<Expr>(Condition))
1329    Condition = Ex->IgnoreParens();
1330
1331  Condition = ResolveCondition(Condition, BldCtx.getBlock());
1332  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1333                                Condition->getLocStart(),
1334                                "Error evaluating branch");
1335
1336  ExplodedNodeSet CheckersOutSet;
1337  getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1338                                                    Pred, *this);
1339  // We generated only sinks.
1340  if (CheckersOutSet.empty())
1341    return;
1342
1343  BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1344  for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1345                             E = CheckersOutSet.end(); E != I; ++I) {
1346    ExplodedNode *PredI = *I;
1347
1348    if (PredI->isSink())
1349      continue;
1350
1351    ProgramStateRef PrevState = PredI->getState();
1352    SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1353
1354    if (X.isUnknownOrUndef()) {
1355      // Give it a chance to recover from unknown.
1356      if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1357        if (Ex->getType()->isIntegralOrEnumerationType()) {
1358          // Try to recover some path-sensitivity.  Right now casts of symbolic
1359          // integers that promote their values are currently not tracked well.
1360          // If 'Condition' is such an expression, try and recover the
1361          // underlying value and use that instead.
1362          SVal recovered = RecoverCastedSymbol(getStateManager(),
1363                                               PrevState, Condition,
1364                                               PredI->getLocationContext(),
1365                                               getContext());
1366
1367          if (!recovered.isUnknown()) {
1368            X = recovered;
1369          }
1370        }
1371      }
1372    }
1373
1374    // If the condition is still unknown, give up.
1375    if (X.isUnknownOrUndef()) {
1376      builder.generateNode(PrevState, true, PredI);
1377      builder.generateNode(PrevState, false, PredI);
1378      continue;
1379    }
1380
1381    DefinedSVal V = X.castAs<DefinedSVal>();
1382
1383    ProgramStateRef StTrue, StFalse;
1384    tie(StTrue, StFalse) = PrevState->assume(V);
1385
1386    // Process the true branch.
1387    if (builder.isFeasible(true)) {
1388      if (StTrue)
1389        builder.generateNode(StTrue, true, PredI);
1390      else
1391        builder.markInfeasible(true);
1392    }
1393
1394    // Process the false branch.
1395    if (builder.isFeasible(false)) {
1396      if (StFalse)
1397        builder.generateNode(StFalse, false, PredI);
1398      else
1399        builder.markInfeasible(false);
1400    }
1401  }
1402  currBldrCtx = 0;
1403}
1404
1405/// The GDM component containing the set of global variables which have been
1406/// previously initialized with explicit initializers.
1407REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1408                                 llvm::ImmutableSet<const VarDecl *>)
1409
1410void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1411                                          NodeBuilderContext &BuilderCtx,
1412                                          ExplodedNode *Pred,
1413                                          clang::ento::ExplodedNodeSet &Dst,
1414                                          const CFGBlock *DstT,
1415                                          const CFGBlock *DstF) {
1416  currBldrCtx = &BuilderCtx;
1417
1418  const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1419  ProgramStateRef state = Pred->getState();
1420  bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1421  BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1422
1423  if (!initHasRun) {
1424    state = state->add<InitializedGlobalsSet>(VD);
1425  }
1426
1427  builder.generateNode(state, initHasRun, Pred);
1428  builder.markInfeasible(!initHasRun);
1429
1430  currBldrCtx = 0;
1431}
1432
1433/// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1434///  nodes by processing the 'effects' of a computed goto jump.
1435void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1436
1437  ProgramStateRef state = builder.getState();
1438  SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1439
1440  // Three possibilities:
1441  //
1442  //   (1) We know the computed label.
1443  //   (2) The label is NULL (or some other constant), or Undefined.
1444  //   (3) We have no clue about the label.  Dispatch to all targets.
1445  //
1446
1447  typedef IndirectGotoNodeBuilder::iterator iterator;
1448
1449  if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1450    const LabelDecl *L = LV->getLabel();
1451
1452    for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1453      if (I.getLabel() == L) {
1454        builder.generateNode(I, state);
1455        return;
1456      }
1457    }
1458
1459    llvm_unreachable("No block with label.");
1460  }
1461
1462  if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1463    // Dispatch to the first target and mark it as a sink.
1464    //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1465    // FIXME: add checker visit.
1466    //    UndefBranches.insert(N);
1467    return;
1468  }
1469
1470  // This is really a catch-all.  We don't support symbolics yet.
1471  // FIXME: Implement dispatch for symbolic pointers.
1472
1473  for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1474    builder.generateNode(I, state);
1475}
1476
1477/// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1478///  nodes when the control reaches the end of a function.
1479void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1480                                      ExplodedNode *Pred) {
1481  StateMgr.EndPath(Pred->getState());
1482
1483  ExplodedNodeSet Dst;
1484  if (Pred->getLocationContext()->inTopFrame()) {
1485    // Remove dead symbols.
1486    ExplodedNodeSet AfterRemovedDead;
1487    removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1488
1489    // Notify checkers.
1490    for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1491        E = AfterRemovedDead.end(); I != E; ++I) {
1492      getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1493    }
1494  } else {
1495    getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1496  }
1497
1498  Engine.enqueueEndOfFunction(Dst);
1499}
1500
1501/// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1502///  nodes by processing the 'effects' of a switch statement.
1503void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1504  typedef SwitchNodeBuilder::iterator iterator;
1505  ProgramStateRef state = builder.getState();
1506  const Expr *CondE = builder.getCondition();
1507  SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1508
1509  if (CondV_untested.isUndef()) {
1510    //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1511    // FIXME: add checker
1512    //UndefBranches.insert(N);
1513
1514    return;
1515  }
1516  DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1517
1518  ProgramStateRef DefaultSt = state;
1519
1520  iterator I = builder.begin(), EI = builder.end();
1521  bool defaultIsFeasible = I == EI;
1522
1523  for ( ; I != EI; ++I) {
1524    // Successor may be pruned out during CFG construction.
1525    if (!I.getBlock())
1526      continue;
1527
1528    const CaseStmt *Case = I.getCase();
1529
1530    // Evaluate the LHS of the case value.
1531    llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1532    assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1533
1534    // Get the RHS of the case, if it exists.
1535    llvm::APSInt V2;
1536    if (const Expr *E = Case->getRHS())
1537      V2 = E->EvaluateKnownConstInt(getContext());
1538    else
1539      V2 = V1;
1540
1541    // FIXME: Eventually we should replace the logic below with a range
1542    //  comparison, rather than concretize the values within the range.
1543    //  This should be easy once we have "ranges" for NonLVals.
1544
1545    do {
1546      nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1547      DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1548                                               CondV, CaseVal);
1549
1550      // Now "assume" that the case matches.
1551      if (ProgramStateRef stateNew = state->assume(Res, true)) {
1552        builder.generateCaseStmtNode(I, stateNew);
1553
1554        // If CondV evaluates to a constant, then we know that this
1555        // is the *only* case that we can take, so stop evaluating the
1556        // others.
1557        if (CondV.getAs<nonloc::ConcreteInt>())
1558          return;
1559      }
1560
1561      // Now "assume" that the case doesn't match.  Add this state
1562      // to the default state (if it is feasible).
1563      if (DefaultSt) {
1564        if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1565          defaultIsFeasible = true;
1566          DefaultSt = stateNew;
1567        }
1568        else {
1569          defaultIsFeasible = false;
1570          DefaultSt = NULL;
1571        }
1572      }
1573
1574      // Concretize the next value in the range.
1575      if (V1 == V2)
1576        break;
1577
1578      ++V1;
1579      assert (V1 <= V2);
1580
1581    } while (true);
1582  }
1583
1584  if (!defaultIsFeasible)
1585    return;
1586
1587  // If we have switch(enum value), the default branch is not
1588  // feasible if all of the enum constants not covered by 'case:' statements
1589  // are not feasible values for the switch condition.
1590  //
1591  // Note that this isn't as accurate as it could be.  Even if there isn't
1592  // a case for a particular enum value as long as that enum value isn't
1593  // feasible then it shouldn't be considered for making 'default:' reachable.
1594  const SwitchStmt *SS = builder.getSwitch();
1595  const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1596  if (CondExpr->getType()->getAs<EnumType>()) {
1597    if (SS->isAllEnumCasesCovered())
1598      return;
1599  }
1600
1601  builder.generateDefaultCaseNode(DefaultSt);
1602}
1603
1604//===----------------------------------------------------------------------===//
1605// Transfer functions: Loads and stores.
1606//===----------------------------------------------------------------------===//
1607
1608void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1609                                        ExplodedNode *Pred,
1610                                        ExplodedNodeSet &Dst) {
1611  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1612
1613  ProgramStateRef state = Pred->getState();
1614  const LocationContext *LCtx = Pred->getLocationContext();
1615
1616  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1617    // C permits "extern void v", and if you cast the address to a valid type,
1618    // you can even do things with it. We simply pretend
1619    assert(Ex->isGLValue() || VD->getType()->isVoidType());
1620    SVal V = state->getLValue(VD, Pred->getLocationContext());
1621
1622    // For references, the 'lvalue' is the pointer address stored in the
1623    // reference region.
1624    if (VD->getType()->isReferenceType()) {
1625      if (const MemRegion *R = V.getAsRegion())
1626        V = state->getSVal(R);
1627      else
1628        V = UnknownVal();
1629    }
1630
1631    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1632                      ProgramPoint::PostLValueKind);
1633    return;
1634  }
1635  if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1636    assert(!Ex->isGLValue());
1637    SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1638    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1639    return;
1640  }
1641  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1642    SVal V = svalBuilder.getFunctionPointer(FD);
1643    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1644                      ProgramPoint::PostLValueKind);
1645    return;
1646  }
1647  if (isa<FieldDecl>(D)) {
1648    // FIXME: Compute lvalue of field pointers-to-member.
1649    // Right now we just use a non-null void pointer, so that it gives proper
1650    // results in boolean contexts.
1651    SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1652                                          currBldrCtx->blockCount());
1653    state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1654    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1655		      ProgramPoint::PostLValueKind);
1656    return;
1657  }
1658
1659  llvm_unreachable("Support for this Decl not implemented.");
1660}
1661
1662/// VisitArraySubscriptExpr - Transfer function for array accesses
1663void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1664                                             ExplodedNode *Pred,
1665                                             ExplodedNodeSet &Dst){
1666
1667  const Expr *Base = A->getBase()->IgnoreParens();
1668  const Expr *Idx  = A->getIdx()->IgnoreParens();
1669
1670
1671  ExplodedNodeSet checkerPreStmt;
1672  getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1673
1674  StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1675
1676  for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1677                                 ei = checkerPreStmt.end(); it != ei; ++it) {
1678    const LocationContext *LCtx = (*it)->getLocationContext();
1679    ProgramStateRef state = (*it)->getState();
1680    SVal V = state->getLValue(A->getType(),
1681                              state->getSVal(Idx, LCtx),
1682                              state->getSVal(Base, LCtx));
1683    assert(A->isGLValue());
1684    Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0,
1685                      ProgramPoint::PostLValueKind);
1686  }
1687}
1688
1689/// VisitMemberExpr - Transfer function for member expressions.
1690void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1691                                 ExplodedNodeSet &TopDst) {
1692
1693  StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx);
1694  ExplodedNodeSet Dst;
1695  ValueDecl *Member = M->getMemberDecl();
1696
1697  // Handle static member variables and enum constants accessed via
1698  // member syntax.
1699  if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1700    Bldr.takeNodes(Pred);
1701    VisitCommonDeclRefExpr(M, Member, Pred, Dst);
1702    Bldr.addNodes(Dst);
1703    return;
1704  }
1705
1706  ProgramStateRef state = Pred->getState();
1707  const LocationContext *LCtx = Pred->getLocationContext();
1708  Expr *BaseExpr = M->getBase();
1709
1710  // Handle C++ method calls.
1711  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
1712    if (MD->isInstance())
1713      state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1714
1715    SVal MDVal = svalBuilder.getFunctionPointer(MD);
1716    state = state->BindExpr(M, LCtx, MDVal);
1717
1718    Bldr.generateNode(M, Pred, state);
1719    return;
1720  }
1721
1722  // Handle regular struct fields / member variables.
1723  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1724  SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
1725
1726  FieldDecl *field = cast<FieldDecl>(Member);
1727  SVal L = state->getLValue(field, baseExprVal);
1728
1729  if (M->isGLValue() || M->getType()->isArrayType()) {
1730
1731    // We special case rvalue of array type because the analyzer cannot reason
1732    // about it, since we expect all regions to be wrapped in Locs. So we will
1733    // treat these as lvalues assuming that they will decay to pointers as soon
1734    // as they are used.
1735    if (!M->isGLValue()) {
1736      assert(M->getType()->isArrayType());
1737      const ImplicitCastExpr *PE =
1738        dyn_cast<ImplicitCastExpr>(Pred->getParentMap().getParent(M));
1739      if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
1740        assert(false &&
1741               "We assume that array is always wrapped in ArrayToPointerDecay");
1742        L = UnknownVal();
1743      }
1744    }
1745
1746    if (field->getType()->isReferenceType()) {
1747      if (const MemRegion *R = L.getAsRegion())
1748        L = state->getSVal(R);
1749      else
1750        L = UnknownVal();
1751    }
1752
1753    Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0,
1754                      ProgramPoint::PostLValueKind);
1755  } else {
1756    Bldr.takeNodes(Pred);
1757    evalLoad(Dst, M, M, Pred, state, L);
1758    Bldr.addNodes(Dst);
1759  }
1760}
1761
1762namespace {
1763class CollectReachableSymbolsCallback : public SymbolVisitor {
1764  InvalidatedSymbols Symbols;
1765public:
1766  CollectReachableSymbolsCallback(ProgramStateRef State) {}
1767  const InvalidatedSymbols &getSymbols() const { return Symbols; }
1768
1769  bool VisitSymbol(SymbolRef Sym) {
1770    Symbols.insert(Sym);
1771    return true;
1772  }
1773};
1774} // end anonymous namespace
1775
1776// A value escapes in three possible cases:
1777// (1) We are binding to something that is not a memory region.
1778// (2) We are binding to a MemrRegion that does not have stack storage.
1779// (3) We are binding to a MemRegion with stack storage that the store
1780//     does not understand.
1781ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
1782                                                        SVal Loc, SVal Val) {
1783  // Are we storing to something that causes the value to "escape"?
1784  bool escapes = true;
1785
1786  // TODO: Move to StoreManager.
1787  if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
1788    escapes = !regionLoc->getRegion()->hasStackStorage();
1789
1790    if (!escapes) {
1791      // To test (3), generate a new state with the binding added.  If it is
1792      // the same state, then it escapes (since the store cannot represent
1793      // the binding).
1794      // Do this only if we know that the store is not supposed to generate the
1795      // same state.
1796      SVal StoredVal = State->getSVal(regionLoc->getRegion());
1797      if (StoredVal != Val)
1798        escapes = (State == (State->bindLoc(*regionLoc, Val)));
1799    }
1800  }
1801
1802  // If our store can represent the binding and we aren't storing to something
1803  // that doesn't have local storage then just return and have the simulation
1804  // state continue as is.
1805  if (!escapes)
1806    return State;
1807
1808  // Otherwise, find all symbols referenced by 'val' that we are tracking
1809  // and stop tracking them.
1810  CollectReachableSymbolsCallback Scanner =
1811      State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
1812  const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
1813  State = getCheckerManager().runCheckersForPointerEscape(State,
1814                                                          EscapedSymbols,
1815                                                          /*CallEvent*/ 0,
1816                                                          PSK_EscapeOnBind);
1817
1818  return State;
1819}
1820
1821ProgramStateRef
1822ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
1823    const InvalidatedSymbols *Invalidated,
1824    ArrayRef<const MemRegion *> ExplicitRegions,
1825    ArrayRef<const MemRegion *> Regions,
1826    const CallEvent *Call,
1827    bool IsConst) {
1828
1829  if (!Invalidated || Invalidated->empty())
1830    return State;
1831
1832  if (!Call)
1833    return getCheckerManager().runCheckersForPointerEscape(State,
1834                                                           *Invalidated,
1835                                                           0,
1836                                                           PSK_EscapeOther,
1837                                                           IsConst);
1838
1839  // Note: Due to current limitations of RegionStore, we only process the top
1840  // level const pointers correctly. The lower level const pointers are
1841  // currently treated as non-const.
1842  if (IsConst)
1843    return getCheckerManager().runCheckersForPointerEscape(State,
1844                                                        *Invalidated,
1845                                                        Call,
1846                                                        PSK_DirectEscapeOnCall,
1847                                                        true);
1848
1849  // If the symbols were invalidated by a call, we want to find out which ones
1850  // were invalidated directly due to being arguments to the call.
1851  InvalidatedSymbols SymbolsDirectlyInvalidated;
1852  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1853      E = ExplicitRegions.end(); I != E; ++I) {
1854    if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1855      SymbolsDirectlyInvalidated.insert(R->getSymbol());
1856  }
1857
1858  InvalidatedSymbols SymbolsIndirectlyInvalidated;
1859  for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
1860      E = Invalidated->end(); I!=E; ++I) {
1861    SymbolRef sym = *I;
1862    if (SymbolsDirectlyInvalidated.count(sym))
1863      continue;
1864    SymbolsIndirectlyInvalidated.insert(sym);
1865  }
1866
1867  if (!SymbolsDirectlyInvalidated.empty())
1868    State = getCheckerManager().runCheckersForPointerEscape(State,
1869        SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall);
1870
1871  // Notify about the symbols that get indirectly invalidated by the call.
1872  if (!SymbolsIndirectlyInvalidated.empty())
1873    State = getCheckerManager().runCheckersForPointerEscape(State,
1874        SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall);
1875
1876  return State;
1877}
1878
1879/// evalBind - Handle the semantics of binding a value to a specific location.
1880///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
1881void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
1882                          ExplodedNode *Pred,
1883                          SVal location, SVal Val,
1884                          bool atDeclInit, const ProgramPoint *PP) {
1885
1886  const LocationContext *LC = Pred->getLocationContext();
1887  PostStmt PS(StoreE, LC);
1888  if (!PP)
1889    PP = &PS;
1890
1891  // Do a previsit of the bind.
1892  ExplodedNodeSet CheckedSet;
1893  getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
1894                                         StoreE, *this, *PP);
1895
1896
1897  StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
1898
1899  // If the location is not a 'Loc', it will already be handled by
1900  // the checkers.  There is nothing left to do.
1901  if (!location.getAs<Loc>()) {
1902    const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0);
1903    ProgramStateRef state = Pred->getState();
1904    state = processPointerEscapedOnBind(state, location, Val);
1905    Bldr.generateNode(L, state, Pred);
1906    return;
1907  }
1908
1909
1910  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1911       I!=E; ++I) {
1912    ExplodedNode *PredI = *I;
1913    ProgramStateRef state = PredI->getState();
1914
1915    state = processPointerEscapedOnBind(state, location, Val);
1916
1917    // When binding the value, pass on the hint that this is a initialization.
1918    // For initializations, we do not need to inform clients of region
1919    // changes.
1920    state = state->bindLoc(location.castAs<Loc>(),
1921                           Val, /* notifyChanges = */ !atDeclInit);
1922
1923    const MemRegion *LocReg = 0;
1924    if (Optional<loc::MemRegionVal> LocRegVal =
1925            location.getAs<loc::MemRegionVal>()) {
1926      LocReg = LocRegVal->getRegion();
1927    }
1928
1929    const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
1930    Bldr.generateNode(L, state, PredI);
1931  }
1932}
1933
1934/// evalStore - Handle the semantics of a store via an assignment.
1935///  @param Dst The node set to store generated state nodes
1936///  @param AssignE The assignment expression if the store happens in an
1937///         assignment.
1938///  @param LocationE The location expression that is stored to.
1939///  @param state The current simulation state
1940///  @param location The location to store the value
1941///  @param Val The value to be stored
1942void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
1943                             const Expr *LocationE,
1944                             ExplodedNode *Pred,
1945                             ProgramStateRef state, SVal location, SVal Val,
1946                             const ProgramPointTag *tag) {
1947  // Proceed with the store.  We use AssignE as the anchor for the PostStore
1948  // ProgramPoint if it is non-NULL, and LocationE otherwise.
1949  const Expr *StoreE = AssignE ? AssignE : LocationE;
1950
1951  // Evaluate the location (checks for bad dereferences).
1952  ExplodedNodeSet Tmp;
1953  evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
1954
1955  if (Tmp.empty())
1956    return;
1957
1958  if (location.isUndef())
1959    return;
1960
1961  for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1962    evalBind(Dst, StoreE, *NI, location, Val, false);
1963}
1964
1965void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
1966                          const Expr *NodeEx,
1967                          const Expr *BoundEx,
1968                          ExplodedNode *Pred,
1969                          ProgramStateRef state,
1970                          SVal location,
1971                          const ProgramPointTag *tag,
1972                          QualType LoadTy)
1973{
1974  assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
1975
1976  // Are we loading from a region?  This actually results in two loads; one
1977  // to fetch the address of the referenced value and one to fetch the
1978  // referenced value.
1979  if (const TypedValueRegion *TR =
1980        dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
1981
1982    QualType ValTy = TR->getValueType();
1983    if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
1984      static SimpleProgramPointTag
1985             loadReferenceTag("ExprEngine : Load Reference");
1986      ExplodedNodeSet Tmp;
1987      evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
1988                     location, &loadReferenceTag,
1989                     getContext().getPointerType(RT->getPointeeType()));
1990
1991      // Perform the load from the referenced value.
1992      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
1993        state = (*I)->getState();
1994        location = state->getSVal(BoundEx, (*I)->getLocationContext());
1995        evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
1996      }
1997      return;
1998    }
1999  }
2000
2001  evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2002}
2003
2004void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2005                                const Expr *NodeEx,
2006                                const Expr *BoundEx,
2007                                ExplodedNode *Pred,
2008                                ProgramStateRef state,
2009                                SVal location,
2010                                const ProgramPointTag *tag,
2011                                QualType LoadTy) {
2012  assert(NodeEx);
2013  assert(BoundEx);
2014  // Evaluate the location (checks for bad dereferences).
2015  ExplodedNodeSet Tmp;
2016  evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2017  if (Tmp.empty())
2018    return;
2019
2020  StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2021  if (location.isUndef())
2022    return;
2023
2024  // Proceed with the load.
2025  for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2026    state = (*NI)->getState();
2027    const LocationContext *LCtx = (*NI)->getLocationContext();
2028
2029    SVal V = UnknownVal();
2030    if (location.isValid()) {
2031      if (LoadTy.isNull())
2032        LoadTy = BoundEx->getType();
2033      V = state->getSVal(location.castAs<Loc>(), LoadTy);
2034    }
2035
2036    Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2037                      ProgramPoint::PostLoadKind);
2038  }
2039}
2040
2041void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2042                              const Stmt *NodeEx,
2043                              const Stmt *BoundEx,
2044                              ExplodedNode *Pred,
2045                              ProgramStateRef state,
2046                              SVal location,
2047                              const ProgramPointTag *tag,
2048                              bool isLoad) {
2049  StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2050  // Early checks for performance reason.
2051  if (location.isUnknown()) {
2052    return;
2053  }
2054
2055  ExplodedNodeSet Src;
2056  BldrTop.takeNodes(Pred);
2057  StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2058  if (Pred->getState() != state) {
2059    // Associate this new state with an ExplodedNode.
2060    // FIXME: If I pass null tag, the graph is incorrect, e.g for
2061    //   int *p;
2062    //   p = 0;
2063    //   *p = 0xDEADBEEF;
2064    // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2065    // instead "int *p" is noted as
2066    // "Variable 'p' initialized to a null pointer value"
2067
2068    static SimpleProgramPointTag tag("ExprEngine: Location");
2069    Bldr.generateNode(NodeEx, Pred, state, &tag);
2070  }
2071  ExplodedNodeSet Tmp;
2072  getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2073                                             NodeEx, BoundEx, *this);
2074  BldrTop.addNodes(Tmp);
2075}
2076
2077std::pair<const ProgramPointTag *, const ProgramPointTag*>
2078ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2079  static SimpleProgramPointTag
2080         eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
2081         eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
2082  return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2083                        &eagerlyAssumeBinOpBifurcationFalse);
2084}
2085
2086void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2087                                                   ExplodedNodeSet &Src,
2088                                                   const Expr *Ex) {
2089  StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2090
2091  for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2092    ExplodedNode *Pred = *I;
2093    // Test if the previous node was as the same expression.  This can happen
2094    // when the expression fails to evaluate to anything meaningful and
2095    // (as an optimization) we don't generate a node.
2096    ProgramPoint P = Pred->getLocation();
2097    if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2098      continue;
2099    }
2100
2101    ProgramStateRef state = Pred->getState();
2102    SVal V = state->getSVal(Ex, Pred->getLocationContext());
2103    Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2104    if (SEV && SEV->isExpression()) {
2105      const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2106        geteagerlyAssumeBinOpBifurcationTags();
2107
2108      ProgramStateRef StateTrue, StateFalse;
2109      tie(StateTrue, StateFalse) = state->assume(*SEV);
2110
2111      // First assume that the condition is true.
2112      if (StateTrue) {
2113        SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2114        StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2115        Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2116      }
2117
2118      // Next, assume that the condition is false.
2119      if (StateFalse) {
2120        SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2121        StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2122        Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2123      }
2124    }
2125  }
2126}
2127
2128void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2129                                 ExplodedNodeSet &Dst) {
2130  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2131  // We have processed both the inputs and the outputs.  All of the outputs
2132  // should evaluate to Locs.  Nuke all of their values.
2133
2134  // FIXME: Some day in the future it would be nice to allow a "plug-in"
2135  // which interprets the inline asm and stores proper results in the
2136  // outputs.
2137
2138  ProgramStateRef state = Pred->getState();
2139
2140  for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
2141       OE = A->end_outputs(); OI != OE; ++OI) {
2142    SVal X = state->getSVal(*OI, Pred->getLocationContext());
2143    assert (!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2144
2145    if (Optional<Loc> LV = X.getAs<Loc>())
2146      state = state->bindLoc(*LV, UnknownVal());
2147  }
2148
2149  Bldr.generateNode(A, Pred, state);
2150}
2151
2152void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2153                                ExplodedNodeSet &Dst) {
2154  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2155  Bldr.generateNode(A, Pred, Pred->getState());
2156}
2157
2158//===----------------------------------------------------------------------===//
2159// Visualization.
2160//===----------------------------------------------------------------------===//
2161
2162#ifndef NDEBUG
2163static ExprEngine* GraphPrintCheckerState;
2164static SourceManager* GraphPrintSourceManager;
2165
2166namespace llvm {
2167template<>
2168struct DOTGraphTraits<ExplodedNode*> :
2169  public DefaultDOTGraphTraits {
2170
2171  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2172
2173  // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2174  // work.
2175  static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2176
2177#if 0
2178      // FIXME: Replace with a general scheme to tell if the node is
2179      // an error node.
2180    if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2181        GraphPrintCheckerState->isExplicitNullDeref(N) ||
2182        GraphPrintCheckerState->isUndefDeref(N) ||
2183        GraphPrintCheckerState->isUndefStore(N) ||
2184        GraphPrintCheckerState->isUndefControlFlow(N) ||
2185        GraphPrintCheckerState->isUndefResult(N) ||
2186        GraphPrintCheckerState->isBadCall(N) ||
2187        GraphPrintCheckerState->isUndefArg(N))
2188      return "color=\"red\",style=\"filled\"";
2189
2190    if (GraphPrintCheckerState->isNoReturnCall(N))
2191      return "color=\"blue\",style=\"filled\"";
2192#endif
2193    return "";
2194  }
2195
2196  static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2197    if (SLoc.isFileID()) {
2198      Out << "\\lline="
2199        << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2200        << " col="
2201        << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2202        << "\\l";
2203    }
2204  }
2205
2206  static std::string getNodeLabel(const ExplodedNode *N, void*){
2207
2208    std::string sbuf;
2209    llvm::raw_string_ostream Out(sbuf);
2210
2211    // Program Location.
2212    ProgramPoint Loc = N->getLocation();
2213
2214    switch (Loc.getKind()) {
2215      case ProgramPoint::BlockEntranceKind: {
2216        Out << "Block Entrance: B"
2217            << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2218        if (const NamedDecl *ND =
2219                    dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2220          Out << " (";
2221          ND->printName(Out);
2222          Out << ")";
2223        }
2224        break;
2225      }
2226
2227      case ProgramPoint::BlockExitKind:
2228        assert (false);
2229        break;
2230
2231      case ProgramPoint::CallEnterKind:
2232        Out << "CallEnter";
2233        break;
2234
2235      case ProgramPoint::CallExitBeginKind:
2236        Out << "CallExitBegin";
2237        break;
2238
2239      case ProgramPoint::CallExitEndKind:
2240        Out << "CallExitEnd";
2241        break;
2242
2243      case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2244        Out << "PostStmtPurgeDeadSymbols";
2245        break;
2246
2247      case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2248        Out << "PreStmtPurgeDeadSymbols";
2249        break;
2250
2251      case ProgramPoint::EpsilonKind:
2252        Out << "Epsilon Point";
2253        break;
2254
2255      case ProgramPoint::PreImplicitCallKind: {
2256        ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2257        Out << "PreCall: ";
2258
2259        // FIXME: Get proper printing options.
2260        PC.getDecl()->print(Out, LangOptions());
2261        printLocation(Out, PC.getLocation());
2262        break;
2263      }
2264
2265      case ProgramPoint::PostImplicitCallKind: {
2266        ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2267        Out << "PostCall: ";
2268
2269        // FIXME: Get proper printing options.
2270        PC.getDecl()->print(Out, LangOptions());
2271        printLocation(Out, PC.getLocation());
2272        break;
2273      }
2274
2275      case ProgramPoint::PostInitializerKind: {
2276        Out << "PostInitializer: ";
2277        const CXXCtorInitializer *Init =
2278          Loc.castAs<PostInitializer>().getInitializer();
2279        if (const FieldDecl *FD = Init->getAnyMember())
2280          Out << *FD;
2281        else {
2282          QualType Ty = Init->getTypeSourceInfo()->getType();
2283          Ty = Ty.getLocalUnqualifiedType();
2284          LangOptions LO; // FIXME.
2285          Ty.print(Out, LO);
2286        }
2287        break;
2288      }
2289
2290      case ProgramPoint::BlockEdgeKind: {
2291        const BlockEdge &E = Loc.castAs<BlockEdge>();
2292        Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2293            << E.getDst()->getBlockID()  << ')';
2294
2295        if (const Stmt *T = E.getSrc()->getTerminator()) {
2296          SourceLocation SLoc = T->getLocStart();
2297
2298          Out << "\\|Terminator: ";
2299          LangOptions LO; // FIXME.
2300          E.getSrc()->printTerminator(Out, LO);
2301
2302          if (SLoc.isFileID()) {
2303            Out << "\\lline="
2304              << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2305              << " col="
2306              << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2307          }
2308
2309          if (isa<SwitchStmt>(T)) {
2310            const Stmt *Label = E.getDst()->getLabel();
2311
2312            if (Label) {
2313              if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2314                Out << "\\lcase ";
2315                LangOptions LO; // FIXME.
2316                C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
2317
2318                if (const Stmt *RHS = C->getRHS()) {
2319                  Out << " .. ";
2320                  RHS->printPretty(Out, 0, PrintingPolicy(LO));
2321                }
2322
2323                Out << ":";
2324              }
2325              else {
2326                assert (isa<DefaultStmt>(Label));
2327                Out << "\\ldefault:";
2328              }
2329            }
2330            else
2331              Out << "\\l(implicit) default:";
2332          }
2333          else if (isa<IndirectGotoStmt>(T)) {
2334            // FIXME
2335          }
2336          else {
2337            Out << "\\lCondition: ";
2338            if (*E.getSrc()->succ_begin() == E.getDst())
2339              Out << "true";
2340            else
2341              Out << "false";
2342          }
2343
2344          Out << "\\l";
2345        }
2346
2347#if 0
2348          // FIXME: Replace with a general scheme to determine
2349          // the name of the check.
2350        if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2351          Out << "\\|Control-flow based on\\lUndefined value.\\l";
2352        }
2353#endif
2354        break;
2355      }
2356
2357      default: {
2358        const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2359
2360        Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2361        LangOptions LO; // FIXME.
2362        S->printPretty(Out, 0, PrintingPolicy(LO));
2363        printLocation(Out, S->getLocStart());
2364
2365        if (Loc.getAs<PreStmt>())
2366          Out << "\\lPreStmt\\l;";
2367        else if (Loc.getAs<PostLoad>())
2368          Out << "\\lPostLoad\\l;";
2369        else if (Loc.getAs<PostStore>())
2370          Out << "\\lPostStore\\l";
2371        else if (Loc.getAs<PostLValue>())
2372          Out << "\\lPostLValue\\l";
2373
2374#if 0
2375          // FIXME: Replace with a general scheme to determine
2376          // the name of the check.
2377        if (GraphPrintCheckerState->isImplicitNullDeref(N))
2378          Out << "\\|Implicit-Null Dereference.\\l";
2379        else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2380          Out << "\\|Explicit-Null Dereference.\\l";
2381        else if (GraphPrintCheckerState->isUndefDeref(N))
2382          Out << "\\|Dereference of undefialied value.\\l";
2383        else if (GraphPrintCheckerState->isUndefStore(N))
2384          Out << "\\|Store to Undefined Loc.";
2385        else if (GraphPrintCheckerState->isUndefResult(N))
2386          Out << "\\|Result of operation is undefined.";
2387        else if (GraphPrintCheckerState->isNoReturnCall(N))
2388          Out << "\\|Call to function marked \"noreturn\".";
2389        else if (GraphPrintCheckerState->isBadCall(N))
2390          Out << "\\|Call to NULL/Undefined.";
2391        else if (GraphPrintCheckerState->isUndefArg(N))
2392          Out << "\\|Argument in call is undefined";
2393#endif
2394
2395        break;
2396      }
2397    }
2398
2399    ProgramStateRef state = N->getState();
2400    Out << "\\|StateID: " << (const void*) state.getPtr()
2401        << " NodeID: " << (const void*) N << "\\|";
2402    state->printDOT(Out);
2403
2404    Out << "\\l";
2405
2406    if (const ProgramPointTag *tag = Loc.getTag()) {
2407      Out << "\\|Tag: " << tag->getTagDescription();
2408      Out << "\\l";
2409    }
2410    return Out.str();
2411  }
2412};
2413} // end llvm namespace
2414#endif
2415
2416#ifndef NDEBUG
2417template <typename ITERATOR>
2418ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
2419
2420template <> ExplodedNode*
2421GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
2422  (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
2423  return I->first;
2424}
2425#endif
2426
2427void ExprEngine::ViewGraph(bool trim) {
2428#ifndef NDEBUG
2429  if (trim) {
2430    std::vector<const ExplodedNode*> Src;
2431
2432    // Flush any outstanding reports to make sure we cover all the nodes.
2433    // This does not cause them to get displayed.
2434    for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2435      const_cast<BugType*>(*I)->FlushReports(BR);
2436
2437    // Iterate through the reports and get their nodes.
2438    for (BugReporter::EQClasses_iterator
2439           EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2440      ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2441      if (N) Src.push_back(N);
2442    }
2443
2444    ViewGraph(Src);
2445  }
2446  else {
2447    GraphPrintCheckerState = this;
2448    GraphPrintSourceManager = &getContext().getSourceManager();
2449
2450    llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2451
2452    GraphPrintCheckerState = NULL;
2453    GraphPrintSourceManager = NULL;
2454  }
2455#endif
2456}
2457
2458void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2459#ifndef NDEBUG
2460  GraphPrintCheckerState = this;
2461  GraphPrintSourceManager = &getContext().getSourceManager();
2462
2463  OwningPtr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2464
2465  if (!TrimmedG.get())
2466    llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2467  else
2468    llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2469
2470  GraphPrintCheckerState = NULL;
2471  GraphPrintSourceManager = NULL;
2472#endif
2473}
2474