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