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