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