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),
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       ExplodedNodeSet PostVisit;
1328       VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1329       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1330       Bldr.addNodes(Dst);
1331       break;
1332     }
1333 
1334     case Stmt::CXXDeleteExprClass: {
1335       Bldr.takeNodes(Pred);
1336       ExplodedNodeSet PreVisit;
1337       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1338       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1339 
1340       for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1341                                      e = PreVisit.end(); i != e ; ++i)
1342         VisitCXXDeleteExpr(CDE, *i, Dst);
1343 
1344       Bldr.addNodes(Dst);
1345       break;
1346     }
1347       // FIXME: ChooseExpr is really a constant.  We need to fix
1348       //        the CFG do not model them as explicit control-flow.
1349 
1350     case Stmt::ChooseExprClass: { // __builtin_choose_expr
1351       Bldr.takeNodes(Pred);
1352       const ChooseExpr *C = cast<ChooseExpr>(S);
1353       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1354       Bldr.addNodes(Dst);
1355       break;
1356     }
1357 
1358     case Stmt::CompoundAssignOperatorClass:
1359       Bldr.takeNodes(Pred);
1360       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1361       Bldr.addNodes(Dst);
1362       break;
1363 
1364     case Stmt::CompoundLiteralExprClass:
1365       Bldr.takeNodes(Pred);
1366       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1367       Bldr.addNodes(Dst);
1368       break;
1369 
1370     case Stmt::BinaryConditionalOperatorClass:
1371     case Stmt::ConditionalOperatorClass: { // '?' operator
1372       Bldr.takeNodes(Pred);
1373       const AbstractConditionalOperator *C
1374         = cast<AbstractConditionalOperator>(S);
1375       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1376       Bldr.addNodes(Dst);
1377       break;
1378     }
1379 
1380     case Stmt::CXXThisExprClass:
1381       Bldr.takeNodes(Pred);
1382       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1383       Bldr.addNodes(Dst);
1384       break;
1385 
1386     case Stmt::DeclRefExprClass: {
1387       Bldr.takeNodes(Pred);
1388       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1389       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1390       Bldr.addNodes(Dst);
1391       break;
1392     }
1393 
1394     case Stmt::DeclStmtClass:
1395       Bldr.takeNodes(Pred);
1396       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1397       Bldr.addNodes(Dst);
1398       break;
1399 
1400     case Stmt::ImplicitCastExprClass:
1401     case Stmt::CStyleCastExprClass:
1402     case Stmt::CXXStaticCastExprClass:
1403     case Stmt::CXXDynamicCastExprClass:
1404     case Stmt::CXXReinterpretCastExprClass:
1405     case Stmt::CXXConstCastExprClass:
1406     case Stmt::CXXFunctionalCastExprClass:
1407     case Stmt::ObjCBridgedCastExprClass: {
1408       Bldr.takeNodes(Pred);
1409       const CastExpr *C = cast<CastExpr>(S);
1410       ExplodedNodeSet dstExpr;
1411       VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1412 
1413       // Handle the postvisit checks.
1414       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1415       Bldr.addNodes(Dst);
1416       break;
1417     }
1418 
1419     case Expr::MaterializeTemporaryExprClass: {
1420       Bldr.takeNodes(Pred);
1421       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1422       ExplodedNodeSet dstPrevisit;
1423       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1424       ExplodedNodeSet dstExpr;
1425       for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1426                                      e = dstPrevisit.end(); i != e ; ++i) {
1427         CreateCXXTemporaryObject(MTE, *i, dstExpr);
1428       }
1429       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1430       Bldr.addNodes(Dst);
1431       break;
1432     }
1433 
1434     case Stmt::InitListExprClass:
1435       Bldr.takeNodes(Pred);
1436       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1437       Bldr.addNodes(Dst);
1438       break;
1439 
1440     case Stmt::MemberExprClass:
1441       Bldr.takeNodes(Pred);
1442       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1443       Bldr.addNodes(Dst);
1444       break;
1445 
1446     case Stmt::AtomicExprClass:
1447       Bldr.takeNodes(Pred);
1448       VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1449       Bldr.addNodes(Dst);
1450       break;
1451 
1452     case Stmt::ObjCIvarRefExprClass:
1453       Bldr.takeNodes(Pred);
1454       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1455       Bldr.addNodes(Dst);
1456       break;
1457 
1458     case Stmt::ObjCForCollectionStmtClass:
1459       Bldr.takeNodes(Pred);
1460       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1461       Bldr.addNodes(Dst);
1462       break;
1463 
1464     case Stmt::ObjCMessageExprClass:
1465       Bldr.takeNodes(Pred);
1466       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1467       Bldr.addNodes(Dst);
1468       break;
1469 
1470     case Stmt::ObjCAtThrowStmtClass:
1471     case Stmt::CXXThrowExprClass:
1472       // FIXME: This is not complete.  We basically treat @throw as
1473       // an abort.
1474       Bldr.generateSink(S, Pred, Pred->getState());
1475       break;
1476 
1477     case Stmt::ReturnStmtClass:
1478       Bldr.takeNodes(Pred);
1479       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1480       Bldr.addNodes(Dst);
1481       break;
1482 
1483     case Stmt::OffsetOfExprClass:
1484       Bldr.takeNodes(Pred);
1485       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1486       Bldr.addNodes(Dst);
1487       break;
1488 
1489     case Stmt::UnaryExprOrTypeTraitExprClass:
1490       Bldr.takeNodes(Pred);
1491       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1492                                     Pred, Dst);
1493       Bldr.addNodes(Dst);
1494       break;
1495 
1496     case Stmt::StmtExprClass: {
1497       const StmtExpr *SE = cast<StmtExpr>(S);
1498 
1499       if (SE->getSubStmt()->body_empty()) {
1500         // Empty statement expression.
1501         assert(SE->getType() == getContext().VoidTy
1502                && "Empty statement expression must have void type.");
1503         break;
1504       }
1505 
1506       if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1507         ProgramStateRef state = Pred->getState();
1508         Bldr.generateNode(SE, Pred,
1509                           state->BindExpr(SE, Pred->getLocationContext(),
1510                                           state->getSVal(LastExpr,
1511                                                   Pred->getLocationContext())));
1512       }
1513       break;
1514     }
1515 
1516     case Stmt::UnaryOperatorClass: {
1517       Bldr.takeNodes(Pred);
1518       const UnaryOperator *U = cast<UnaryOperator>(S);
1519       if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1520         ExplodedNodeSet Tmp;
1521         VisitUnaryOperator(U, Pred, Tmp);
1522         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1523       }
1524       else
1525         VisitUnaryOperator(U, Pred, Dst);
1526       Bldr.addNodes(Dst);
1527       break;
1528     }
1529 
1530     case Stmt::PseudoObjectExprClass: {
1531       Bldr.takeNodes(Pred);
1532       ProgramStateRef state = Pred->getState();
1533       const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1534       if (const Expr *Result = PE->getResultExpr()) {
1535         SVal V = state->getSVal(Result, Pred->getLocationContext());
1536         Bldr.generateNode(S, Pred,
1537                           state->BindExpr(S, Pred->getLocationContext(), V));
1538       }
1539       else
1540         Bldr.generateNode(S, Pred,
1541                           state->BindExpr(S, Pred->getLocationContext(),
1542                                                    UnknownVal()));
1543 
1544       Bldr.addNodes(Dst);
1545       break;
1546     }
1547   }
1548 }
1549 
1550 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1551                                        const LocationContext *CalleeLC) {
1552   const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1553   const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1554   assert(CalleeSF && CallerSF);
1555   ExplodedNode *BeforeProcessingCall = nullptr;
1556   const Stmt *CE = CalleeSF->getCallSite();
1557 
1558   // Find the first node before we started processing the call expression.
1559   while (N) {
1560     ProgramPoint L = N->getLocation();
1561     BeforeProcessingCall = N;
1562     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1563 
1564     // Skip the nodes corresponding to the inlined code.
1565     if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1566       continue;
1567     // We reached the caller. Find the node right before we started
1568     // processing the call.
1569     if (L.isPurgeKind())
1570       continue;
1571     if (L.getAs<PreImplicitCall>())
1572       continue;
1573     if (L.getAs<CallEnter>())
1574       continue;
1575     if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1576       if (SP->getStmt() == CE)
1577         continue;
1578     break;
1579   }
1580 
1581   if (!BeforeProcessingCall)
1582     return false;
1583 
1584   // TODO: Clean up the unneeded nodes.
1585 
1586   // Build an Epsilon node from which we will restart the analyzes.
1587   // Note that CE is permitted to be NULL!
1588   ProgramPoint NewNodeLoc =
1589                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1590   // Add the special flag to GDM to signal retrying with no inlining.
1591   // Note, changing the state ensures that we are not going to cache out.
1592   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1593   NewNodeState =
1594     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1595 
1596   // Make the new node a successor of BeforeProcessingCall.
1597   bool IsNew = false;
1598   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1599   // We cached out at this point. Caching out is common due to us backtracking
1600   // from the inlined function, which might spawn several paths.
1601   if (!IsNew)
1602     return true;
1603 
1604   NewNode->addPredecessor(BeforeProcessingCall, G);
1605 
1606   // Add the new node to the work list.
1607   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1608                                   CalleeSF->getIndex());
1609   NumTimesRetriedWithoutInlining++;
1610   return true;
1611 }
1612 
1613 /// Block entrance.  (Update counters).
1614 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1615                                          NodeBuilderWithSinks &nodeBuilder,
1616                                          ExplodedNode *Pred) {
1617   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1618   // If we reach a loop which has a known bound (and meets
1619   // other constraints) then consider completely unrolling it.
1620   if(AMgr.options.shouldUnrollLoops()) {
1621     unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1622     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1623     if (Term) {
1624       ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1625                                                  Pred, maxBlockVisitOnPath);
1626       if (NewState != Pred->getState()) {
1627         ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1628         if (!UpdatedNode)
1629           return;
1630         Pred = UpdatedNode;
1631       }
1632     }
1633     // Is we are inside an unrolled loop then no need the check the counters.
1634     if(isUnrolledState(Pred->getState()))
1635       return;
1636   }
1637 
1638   // If this block is terminated by a loop and it has already been visited the
1639   // maximum number of times, widen the loop.
1640   unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1641   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1642       AMgr.options.shouldWidenLoops()) {
1643     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1644     if (!(Term &&
1645           (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1646       return;
1647     // Widen.
1648     const LocationContext *LCtx = Pred->getLocationContext();
1649     ProgramStateRef WidenedState =
1650         getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1651     nodeBuilder.generateNode(WidenedState, Pred);
1652     return;
1653   }
1654 
1655   // FIXME: Refactor this into a checker.
1656   if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1657     static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1658     const ExplodedNode *Sink =
1659                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1660 
1661     // Check if we stopped at the top level function or not.
1662     // Root node should have the location context of the top most function.
1663     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1664     const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1665     const LocationContext *RootLC =
1666                         (*G.roots_begin())->getLocation().getLocationContext();
1667     if (RootLC->getCurrentStackFrame() != CalleeSF) {
1668       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1669 
1670       // Re-run the call evaluation without inlining it, by storing the
1671       // no-inlining policy in the state and enqueuing the new work item on
1672       // the list. Replay should almost never fail. Use the stats to catch it
1673       // if it does.
1674       if ((!AMgr.options.NoRetryExhausted &&
1675            replayWithoutInlining(Pred, CalleeLC)))
1676         return;
1677       NumMaxBlockCountReachedInInlined++;
1678     } else
1679       NumMaxBlockCountReached++;
1680 
1681     // Make sink nodes as exhausted(for stats) only if retry failed.
1682     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1683   }
1684 }
1685 
1686 //===----------------------------------------------------------------------===//
1687 // Branch processing.
1688 //===----------------------------------------------------------------------===//
1689 
1690 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1691 /// to try to recover some path-sensitivity for casts of symbolic
1692 /// integers that promote their values (which are currently not tracked well).
1693 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1694 //  cast(s) did was sign-extend the original value.
1695 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1696                                 ProgramStateRef state,
1697                                 const Stmt *Condition,
1698                                 const LocationContext *LCtx,
1699                                 ASTContext &Ctx) {
1700 
1701   const Expr *Ex = dyn_cast<Expr>(Condition);
1702   if (!Ex)
1703     return UnknownVal();
1704 
1705   uint64_t bits = 0;
1706   bool bitsInit = false;
1707 
1708   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1709     QualType T = CE->getType();
1710 
1711     if (!T->isIntegralOrEnumerationType())
1712       return UnknownVal();
1713 
1714     uint64_t newBits = Ctx.getTypeSize(T);
1715     if (!bitsInit || newBits < bits) {
1716       bitsInit = true;
1717       bits = newBits;
1718     }
1719 
1720     Ex = CE->getSubExpr();
1721   }
1722 
1723   // We reached a non-cast.  Is it a symbolic value?
1724   QualType T = Ex->getType();
1725 
1726   if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1727       Ctx.getTypeSize(T) > bits)
1728     return UnknownVal();
1729 
1730   return state->getSVal(Ex, LCtx);
1731 }
1732 
1733 #ifndef NDEBUG
1734 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1735   while (Condition) {
1736     const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1737     if (!BO || !BO->isLogicalOp()) {
1738       return Condition;
1739     }
1740     Condition = BO->getRHS()->IgnoreParens();
1741   }
1742   return nullptr;
1743 }
1744 #endif
1745 
1746 // Returns the condition the branch at the end of 'B' depends on and whose value
1747 // has been evaluated within 'B'.
1748 // In most cases, the terminator condition of 'B' will be evaluated fully in
1749 // the last statement of 'B'; in those cases, the resolved condition is the
1750 // given 'Condition'.
1751 // If the condition of the branch is a logical binary operator tree, the CFG is
1752 // optimized: in that case, we know that the expression formed by all but the
1753 // rightmost leaf of the logical binary operator tree must be true, and thus
1754 // the branch condition is at this point equivalent to the truth value of that
1755 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1756 // expression in its final statement. As the full condition in that case was
1757 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1758 // expression to evaluate the truth value of the condition in the current state
1759 // space.
1760 static const Stmt *ResolveCondition(const Stmt *Condition,
1761                                     const CFGBlock *B) {
1762   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1763     Condition = Ex->IgnoreParens();
1764 
1765   const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1766   if (!BO || !BO->isLogicalOp())
1767     return Condition;
1768 
1769   assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1770          "Temporary destructor branches handled by processBindTemporary.");
1771 
1772   // For logical operations, we still have the case where some branches
1773   // use the traditional "merge" approach and others sink the branch
1774   // directly into the basic blocks representing the logical operation.
1775   // We need to distinguish between those two cases here.
1776 
1777   // The invariants are still shifting, but it is possible that the
1778   // last element in a CFGBlock is not a CFGStmt.  Look for the last
1779   // CFGStmt as the value of the condition.
1780   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1781   for (; I != E; ++I) {
1782     CFGElement Elem = *I;
1783     Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1784     if (!CS)
1785       continue;
1786     const Stmt *LastStmt = CS->getStmt();
1787     assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1788     return LastStmt;
1789   }
1790   llvm_unreachable("could not resolve condition");
1791 }
1792 
1793 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1794                                NodeBuilderContext& BldCtx,
1795                                ExplodedNode *Pred,
1796                                ExplodedNodeSet &Dst,
1797                                const CFGBlock *DstT,
1798                                const CFGBlock *DstF) {
1799   assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1800          "CXXBindTemporaryExprs are handled by processBindTemporary.");
1801   const LocationContext *LCtx = Pred->getLocationContext();
1802   PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1803   currBldrCtx = &BldCtx;
1804 
1805   // Check for NULL conditions; e.g. "for(;;)"
1806   if (!Condition) {
1807     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1808     NullCondBldr.markInfeasible(false);
1809     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1810     return;
1811   }
1812 
1813   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1814     Condition = Ex->IgnoreParens();
1815 
1816   Condition = ResolveCondition(Condition, BldCtx.getBlock());
1817   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1818                                 Condition->getLocStart(),
1819                                 "Error evaluating branch");
1820 
1821   ExplodedNodeSet CheckersOutSet;
1822   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1823                                                     Pred, *this);
1824   // We generated only sinks.
1825   if (CheckersOutSet.empty())
1826     return;
1827 
1828   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1829   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1830                              E = CheckersOutSet.end(); E != I; ++I) {
1831     ExplodedNode *PredI = *I;
1832 
1833     if (PredI->isSink())
1834       continue;
1835 
1836     ProgramStateRef PrevState = PredI->getState();
1837     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1838 
1839     if (X.isUnknownOrUndef()) {
1840       // Give it a chance to recover from unknown.
1841       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1842         if (Ex->getType()->isIntegralOrEnumerationType()) {
1843           // Try to recover some path-sensitivity.  Right now casts of symbolic
1844           // integers that promote their values are currently not tracked well.
1845           // If 'Condition' is such an expression, try and recover the
1846           // underlying value and use that instead.
1847           SVal recovered = RecoverCastedSymbol(getStateManager(),
1848                                                PrevState, Condition,
1849                                                PredI->getLocationContext(),
1850                                                getContext());
1851 
1852           if (!recovered.isUnknown()) {
1853             X = recovered;
1854           }
1855         }
1856       }
1857     }
1858 
1859     // If the condition is still unknown, give up.
1860     if (X.isUnknownOrUndef()) {
1861       builder.generateNode(PrevState, true, PredI);
1862       builder.generateNode(PrevState, false, PredI);
1863       continue;
1864     }
1865 
1866     DefinedSVal V = X.castAs<DefinedSVal>();
1867 
1868     ProgramStateRef StTrue, StFalse;
1869     std::tie(StTrue, StFalse) = PrevState->assume(V);
1870 
1871     // Process the true branch.
1872     if (builder.isFeasible(true)) {
1873       if (StTrue)
1874         builder.generateNode(StTrue, true, PredI);
1875       else
1876         builder.markInfeasible(true);
1877     }
1878 
1879     // Process the false branch.
1880     if (builder.isFeasible(false)) {
1881       if (StFalse)
1882         builder.generateNode(StFalse, false, PredI);
1883       else
1884         builder.markInfeasible(false);
1885     }
1886   }
1887   currBldrCtx = nullptr;
1888 }
1889 
1890 /// The GDM component containing the set of global variables which have been
1891 /// previously initialized with explicit initializers.
1892 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1893                                  llvm::ImmutableSet<const VarDecl *>)
1894 
1895 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1896                                           NodeBuilderContext &BuilderCtx,
1897                                           ExplodedNode *Pred,
1898                                           clang::ento::ExplodedNodeSet &Dst,
1899                                           const CFGBlock *DstT,
1900                                           const CFGBlock *DstF) {
1901   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1902   currBldrCtx = &BuilderCtx;
1903 
1904   const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1905   ProgramStateRef state = Pred->getState();
1906   bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1907   BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1908 
1909   if (!initHasRun) {
1910     state = state->add<InitializedGlobalsSet>(VD);
1911   }
1912 
1913   builder.generateNode(state, initHasRun, Pred);
1914   builder.markInfeasible(!initHasRun);
1915 
1916   currBldrCtx = nullptr;
1917 }
1918 
1919 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1920 ///  nodes by processing the 'effects' of a computed goto jump.
1921 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1922 
1923   ProgramStateRef state = builder.getState();
1924   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1925 
1926   // Three possibilities:
1927   //
1928   //   (1) We know the computed label.
1929   //   (2) The label is NULL (or some other constant), or Undefined.
1930   //   (3) We have no clue about the label.  Dispatch to all targets.
1931   //
1932 
1933   typedef IndirectGotoNodeBuilder::iterator iterator;
1934 
1935   if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1936     const LabelDecl *L = LV->getLabel();
1937 
1938     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1939       if (I.getLabel() == L) {
1940         builder.generateNode(I, state);
1941         return;
1942       }
1943     }
1944 
1945     llvm_unreachable("No block with label.");
1946   }
1947 
1948   if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1949     // Dispatch to the first target and mark it as a sink.
1950     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1951     // FIXME: add checker visit.
1952     //    UndefBranches.insert(N);
1953     return;
1954   }
1955 
1956   // This is really a catch-all.  We don't support symbolics yet.
1957   // FIXME: Implement dispatch for symbolic pointers.
1958 
1959   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1960     builder.generateNode(I, state);
1961 }
1962 
1963 #if 0
1964 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1965   const StackFrameContext* Frame = Pred.getStackFrame();
1966   const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1967       Pred.getState()->get<InitializedTemporariesSet>();
1968   return std::find_if(Set.begin(), Set.end(),
1969                       [&](const CXXBindTemporaryContext &Ctx) {
1970                         if (Ctx.second == Frame) {
1971                           Ctx.first->dump();
1972                           llvm::errs() << "\n";
1973                         }
1974            return Ctx.second == Frame;
1975          }) == Set.end();
1976 }
1977 #endif
1978 
1979 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
1980                                         ExplodedNode *Pred,
1981                                         ExplodedNodeSet &Dst,
1982                                         const BlockEdge &L) {
1983   SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1984   getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1985 }
1986 
1987 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1988 ///  nodes when the control reaches the end of a function.
1989 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1990                                       ExplodedNode *Pred,
1991                                       const ReturnStmt *RS) {
1992   // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1993   // We currently cannot enable this assert, as lifetime extended temporaries
1994   // are not modelled correctly.
1995   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1996   StateMgr.EndPath(Pred->getState());
1997 
1998   ExplodedNodeSet Dst;
1999   if (Pred->getLocationContext()->inTopFrame()) {
2000     // Remove dead symbols.
2001     ExplodedNodeSet AfterRemovedDead;
2002     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2003 
2004     // Notify checkers.
2005     for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
2006         E = AfterRemovedDead.end(); I != E; ++I) {
2007       getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
2008     }
2009   } else {
2010     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
2011   }
2012 
2013   Engine.enqueueEndOfFunction(Dst, RS);
2014 }
2015 
2016 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
2017 ///  nodes by processing the 'effects' of a switch statement.
2018 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
2019   typedef SwitchNodeBuilder::iterator iterator;
2020   ProgramStateRef state = builder.getState();
2021   const Expr *CondE = builder.getCondition();
2022   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2023 
2024   if (CondV_untested.isUndef()) {
2025     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2026     // FIXME: add checker
2027     //UndefBranches.insert(N);
2028 
2029     return;
2030   }
2031   DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2032 
2033   ProgramStateRef DefaultSt = state;
2034 
2035   iterator I = builder.begin(), EI = builder.end();
2036   bool defaultIsFeasible = I == EI;
2037 
2038   for ( ; I != EI; ++I) {
2039     // Successor may be pruned out during CFG construction.
2040     if (!I.getBlock())
2041       continue;
2042 
2043     const CaseStmt *Case = I.getCase();
2044 
2045     // Evaluate the LHS of the case value.
2046     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2047     assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2048 
2049     // Get the RHS of the case, if it exists.
2050     llvm::APSInt V2;
2051     if (const Expr *E = Case->getRHS())
2052       V2 = E->EvaluateKnownConstInt(getContext());
2053     else
2054       V2 = V1;
2055 
2056     ProgramStateRef StateCase;
2057     if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2058       std::tie(StateCase, DefaultSt) =
2059           DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2060     else // UnknownVal
2061       StateCase = DefaultSt;
2062 
2063     if (StateCase)
2064       builder.generateCaseStmtNode(I, StateCase);
2065 
2066     // Now "assume" that the case doesn't match.  Add this state
2067     // to the default state (if it is feasible).
2068     if (DefaultSt)
2069       defaultIsFeasible = true;
2070     else {
2071       defaultIsFeasible = false;
2072       break;
2073     }
2074   }
2075 
2076   if (!defaultIsFeasible)
2077     return;
2078 
2079   // If we have switch(enum value), the default branch is not
2080   // feasible if all of the enum constants not covered by 'case:' statements
2081   // are not feasible values for the switch condition.
2082   //
2083   // Note that this isn't as accurate as it could be.  Even if there isn't
2084   // a case for a particular enum value as long as that enum value isn't
2085   // feasible then it shouldn't be considered for making 'default:' reachable.
2086   const SwitchStmt *SS = builder.getSwitch();
2087   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2088   if (CondExpr->getType()->getAs<EnumType>()) {
2089     if (SS->isAllEnumCasesCovered())
2090       return;
2091   }
2092 
2093   builder.generateDefaultCaseNode(DefaultSt);
2094 }
2095 
2096 //===----------------------------------------------------------------------===//
2097 // Transfer functions: Loads and stores.
2098 //===----------------------------------------------------------------------===//
2099 
2100 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
2101                                         ExplodedNode *Pred,
2102                                         ExplodedNodeSet &Dst) {
2103   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2104 
2105   ProgramStateRef state = Pred->getState();
2106   const LocationContext *LCtx = Pred->getLocationContext();
2107 
2108   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2109     // C permits "extern void v", and if you cast the address to a valid type,
2110     // you can even do things with it. We simply pretend
2111     assert(Ex->isGLValue() || VD->getType()->isVoidType());
2112     const LocationContext *LocCtxt = Pred->getLocationContext();
2113     const Decl *D = LocCtxt->getDecl();
2114     const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
2115     const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2116     SVal V;
2117     bool IsReference;
2118     if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
2119         DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2120         MD->getParent()->isLambda()) {
2121       // Lookup the field of the lambda.
2122       const CXXRecordDecl *CXXRec = MD->getParent();
2123       llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2124       FieldDecl *LambdaThisCaptureField;
2125       CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2126       const FieldDecl *FD = LambdaCaptureFields[VD];
2127       if (!FD) {
2128         // When a constant is captured, sometimes no corresponding field is
2129         // created in the lambda object.
2130         assert(VD->getType().isConstQualified());
2131         V = state->getLValue(VD, LocCtxt);
2132         IsReference = false;
2133       } else {
2134         Loc CXXThis =
2135             svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
2136         SVal CXXThisVal = state->getSVal(CXXThis);
2137         V = state->getLValue(FD, CXXThisVal);
2138         IsReference = FD->getType()->isReferenceType();
2139       }
2140     } else {
2141       V = state->getLValue(VD, LocCtxt);
2142       IsReference = VD->getType()->isReferenceType();
2143     }
2144 
2145     // For references, the 'lvalue' is the pointer address stored in the
2146     // reference region.
2147     if (IsReference) {
2148       if (const MemRegion *R = V.getAsRegion())
2149         V = state->getSVal(R);
2150       else
2151         V = UnknownVal();
2152     }
2153 
2154     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2155                       ProgramPoint::PostLValueKind);
2156     return;
2157   }
2158   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
2159     assert(!Ex->isGLValue());
2160     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2161     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2162     return;
2163   }
2164   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2165     SVal V = svalBuilder.getFunctionPointer(FD);
2166     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2167                       ProgramPoint::PostLValueKind);
2168     return;
2169   }
2170   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2171     // FIXME: Compute lvalue of field pointers-to-member.
2172     // Right now we just use a non-null void pointer, so that it gives proper
2173     // results in boolean contexts.
2174     // FIXME: Maybe delegate this to the surrounding operator&.
2175     // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2176     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2177                                           currBldrCtx->blockCount());
2178     state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2179     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2180 		      ProgramPoint::PostLValueKind);
2181     return;
2182   }
2183 
2184   llvm_unreachable("Support for this Decl not implemented.");
2185 }
2186 
2187 /// VisitArraySubscriptExpr - Transfer function for array accesses
2188 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
2189                                              ExplodedNode *Pred,
2190                                              ExplodedNodeSet &Dst){
2191   const Expr *Base = A->getBase()->IgnoreParens();
2192   const Expr *Idx  = A->getIdx()->IgnoreParens();
2193 
2194   ExplodedNodeSet CheckerPreStmt;
2195   getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2196 
2197   ExplodedNodeSet EvalSet;
2198   StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2199 
2200   bool IsVectorType = A->getBase()->getType()->isVectorType();
2201 
2202   // The "like" case is for situations where C standard prohibits the type to
2203   // be an lvalue, e.g. taking the address of a subscript of an expression of
2204   // type "void *".
2205   bool IsGLValueLike = A->isGLValue() ||
2206     (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2207 
2208   for (auto *Node : CheckerPreStmt) {
2209     const LocationContext *LCtx = Node->getLocationContext();
2210     ProgramStateRef state = Node->getState();
2211 
2212     if (IsGLValueLike) {
2213       QualType T = A->getType();
2214 
2215       // One of the forbidden LValue types! We still need to have sensible
2216       // symbolic locations to represent this stuff. Note that arithmetic on
2217       // void pointers is a GCC extension.
2218       if (T->isVoidType())
2219         T = getContext().CharTy;
2220 
2221       SVal V = state->getLValue(T,
2222                                 state->getSVal(Idx, LCtx),
2223                                 state->getSVal(Base, LCtx));
2224       Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2225           ProgramPoint::PostLValueKind);
2226     } else if (IsVectorType) {
2227       // FIXME: non-glvalue vector reads are not modelled.
2228       Bldr.generateNode(A, Node, state, nullptr);
2229     } else {
2230       llvm_unreachable("Array subscript should be an lValue when not \
2231 a vector and not a forbidden lvalue type");
2232     }
2233   }
2234 
2235   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2236 }
2237 
2238 /// VisitMemberExpr - Transfer function for member expressions.
2239 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2240                                  ExplodedNodeSet &Dst) {
2241 
2242   // FIXME: Prechecks eventually go in ::Visit().
2243   ExplodedNodeSet CheckedSet;
2244   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2245 
2246   ExplodedNodeSet EvalSet;
2247   ValueDecl *Member = M->getMemberDecl();
2248 
2249   // Handle static member variables and enum constants accessed via
2250   // member syntax.
2251   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2252     ExplodedNodeSet Dst;
2253     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2254          I != E; ++I) {
2255       VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2256     }
2257   } else {
2258     StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2259     ExplodedNodeSet Tmp;
2260 
2261     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2262          I != E; ++I) {
2263       ProgramStateRef state = (*I)->getState();
2264       const LocationContext *LCtx = (*I)->getLocationContext();
2265       Expr *BaseExpr = M->getBase();
2266 
2267       // Handle C++ method calls.
2268       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2269         if (MD->isInstance())
2270           state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2271 
2272         SVal MDVal = svalBuilder.getFunctionPointer(MD);
2273         state = state->BindExpr(M, LCtx, MDVal);
2274 
2275         Bldr.generateNode(M, *I, state);
2276         continue;
2277       }
2278 
2279       // Handle regular struct fields / member variables.
2280       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2281       SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2282 
2283       FieldDecl *field = cast<FieldDecl>(Member);
2284       SVal L = state->getLValue(field, baseExprVal);
2285 
2286       if (M->isGLValue() || M->getType()->isArrayType()) {
2287         // We special-case rvalues of array type because the analyzer cannot
2288         // reason about them, since we expect all regions to be wrapped in Locs.
2289         // We instead treat these as lvalues and assume that they will decay to
2290         // pointers as soon as they are used.
2291         if (!M->isGLValue()) {
2292           assert(M->getType()->isArrayType());
2293           const ImplicitCastExpr *PE =
2294             dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M));
2295           if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2296             llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2297           }
2298         }
2299 
2300         if (field->getType()->isReferenceType()) {
2301           if (const MemRegion *R = L.getAsRegion())
2302             L = state->getSVal(R);
2303           else
2304             L = UnknownVal();
2305         }
2306 
2307         Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2308                           ProgramPoint::PostLValueKind);
2309       } else {
2310         Bldr.takeNodes(*I);
2311         evalLoad(Tmp, M, M, *I, state, L);
2312         Bldr.addNodes(Tmp);
2313       }
2314     }
2315   }
2316 
2317   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2318 }
2319 
2320 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2321                                  ExplodedNodeSet &Dst) {
2322   ExplodedNodeSet AfterPreSet;
2323   getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2324 
2325   // For now, treat all the arguments to C11 atomics as escaping.
2326   // FIXME: Ideally we should model the behavior of the atomics precisely here.
2327 
2328   ExplodedNodeSet AfterInvalidateSet;
2329   StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2330 
2331   for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end();
2332        I != E; ++I) {
2333     ProgramStateRef State = (*I)->getState();
2334     const LocationContext *LCtx = (*I)->getLocationContext();
2335 
2336     SmallVector<SVal, 8> ValuesToInvalidate;
2337     for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2338       const Expr *SubExpr = AE->getSubExprs()[SI];
2339       SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2340       ValuesToInvalidate.push_back(SubExprVal);
2341     }
2342 
2343     State = State->invalidateRegions(ValuesToInvalidate, AE,
2344                                     currBldrCtx->blockCount(),
2345                                     LCtx,
2346                                     /*CausedByPointerEscape*/true,
2347                                     /*Symbols=*/nullptr);
2348 
2349     SVal ResultVal = UnknownVal();
2350     State = State->BindExpr(AE, LCtx, ResultVal);
2351     Bldr.generateNode(AE, *I, State, nullptr,
2352                       ProgramPoint::PostStmtKind);
2353   }
2354 
2355   getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2356 }
2357 
2358 // A value escapes in three possible cases:
2359 // (1) We are binding to something that is not a memory region.
2360 // (2) We are binding to a MemrRegion that does not have stack storage.
2361 // (3) We are binding to a MemRegion with stack storage that the store
2362 //     does not understand.
2363 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2364                                                         SVal Loc,
2365                                                         SVal Val,
2366                                                         const LocationContext *LCtx) {
2367   // Are we storing to something that causes the value to "escape"?
2368   bool escapes = true;
2369 
2370   // TODO: Move to StoreManager.
2371   if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2372     escapes = !regionLoc->getRegion()->hasStackStorage();
2373 
2374     if (!escapes) {
2375       // To test (3), generate a new state with the binding added.  If it is
2376       // the same state, then it escapes (since the store cannot represent
2377       // the binding).
2378       // Do this only if we know that the store is not supposed to generate the
2379       // same state.
2380       SVal StoredVal = State->getSVal(regionLoc->getRegion());
2381       if (StoredVal != Val)
2382         escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2383     }
2384   }
2385 
2386   // If our store can represent the binding and we aren't storing to something
2387   // that doesn't have local storage then just return and have the simulation
2388   // state continue as is.
2389   if (!escapes)
2390     return State;
2391 
2392   // Otherwise, find all symbols referenced by 'val' that we are tracking
2393   // and stop tracking them.
2394   CollectReachableSymbolsCallback Scanner =
2395       State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2396   const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2397   State = getCheckerManager().runCheckersForPointerEscape(State,
2398                                                           EscapedSymbols,
2399                                                           /*CallEvent*/ nullptr,
2400                                                           PSK_EscapeOnBind,
2401                                                           nullptr);
2402 
2403   return State;
2404 }
2405 
2406 ProgramStateRef
2407 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2408     const InvalidatedSymbols *Invalidated,
2409     ArrayRef<const MemRegion *> ExplicitRegions,
2410     ArrayRef<const MemRegion *> Regions,
2411     const CallEvent *Call,
2412     RegionAndSymbolInvalidationTraits &ITraits) {
2413 
2414   if (!Invalidated || Invalidated->empty())
2415     return State;
2416 
2417   if (!Call)
2418     return getCheckerManager().runCheckersForPointerEscape(State,
2419                                                            *Invalidated,
2420                                                            nullptr,
2421                                                            PSK_EscapeOther,
2422                                                            &ITraits);
2423 
2424   // If the symbols were invalidated by a call, we want to find out which ones
2425   // were invalidated directly due to being arguments to the call.
2426   InvalidatedSymbols SymbolsDirectlyInvalidated;
2427   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2428       E = ExplicitRegions.end(); I != E; ++I) {
2429     if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2430       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2431   }
2432 
2433   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2434   for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2435       E = Invalidated->end(); I!=E; ++I) {
2436     SymbolRef sym = *I;
2437     if (SymbolsDirectlyInvalidated.count(sym))
2438       continue;
2439     SymbolsIndirectlyInvalidated.insert(sym);
2440   }
2441 
2442   if (!SymbolsDirectlyInvalidated.empty())
2443     State = getCheckerManager().runCheckersForPointerEscape(State,
2444         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2445 
2446   // Notify about the symbols that get indirectly invalidated by the call.
2447   if (!SymbolsIndirectlyInvalidated.empty())
2448     State = getCheckerManager().runCheckersForPointerEscape(State,
2449         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2450 
2451   return State;
2452 }
2453 
2454 /// evalBind - Handle the semantics of binding a value to a specific location.
2455 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2456 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2457                           ExplodedNode *Pred,
2458                           SVal location, SVal Val,
2459                           bool atDeclInit, const ProgramPoint *PP) {
2460 
2461   const LocationContext *LC = Pred->getLocationContext();
2462   PostStmt PS(StoreE, LC);
2463   if (!PP)
2464     PP = &PS;
2465 
2466   // Do a previsit of the bind.
2467   ExplodedNodeSet CheckedSet;
2468   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2469                                          StoreE, *this, *PP);
2470 
2471   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2472 
2473   // If the location is not a 'Loc', it will already be handled by
2474   // the checkers.  There is nothing left to do.
2475   if (!location.getAs<Loc>()) {
2476     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2477                                      /*tag*/nullptr);
2478     ProgramStateRef state = Pred->getState();
2479     state = processPointerEscapedOnBind(state, location, Val, LC);
2480     Bldr.generateNode(L, state, Pred);
2481     return;
2482   }
2483 
2484   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2485        I!=E; ++I) {
2486     ExplodedNode *PredI = *I;
2487     ProgramStateRef state = PredI->getState();
2488 
2489     state = processPointerEscapedOnBind(state, location, Val, LC);
2490 
2491     // When binding the value, pass on the hint that this is a initialization.
2492     // For initializations, we do not need to inform clients of region
2493     // changes.
2494     state = state->bindLoc(location.castAs<Loc>(),
2495                            Val, LC, /* notifyChanges = */ !atDeclInit);
2496 
2497     const MemRegion *LocReg = nullptr;
2498     if (Optional<loc::MemRegionVal> LocRegVal =
2499             location.getAs<loc::MemRegionVal>()) {
2500       LocReg = LocRegVal->getRegion();
2501     }
2502 
2503     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2504     Bldr.generateNode(L, state, PredI);
2505   }
2506 }
2507 
2508 /// evalStore - Handle the semantics of a store via an assignment.
2509 ///  @param Dst The node set to store generated state nodes
2510 ///  @param AssignE The assignment expression if the store happens in an
2511 ///         assignment.
2512 ///  @param LocationE The location expression that is stored to.
2513 ///  @param state The current simulation state
2514 ///  @param location The location to store the value
2515 ///  @param Val The value to be stored
2516 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2517                              const Expr *LocationE,
2518                              ExplodedNode *Pred,
2519                              ProgramStateRef state, SVal location, SVal Val,
2520                              const ProgramPointTag *tag) {
2521   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2522   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2523   const Expr *StoreE = AssignE ? AssignE : LocationE;
2524 
2525   // Evaluate the location (checks for bad dereferences).
2526   ExplodedNodeSet Tmp;
2527   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2528 
2529   if (Tmp.empty())
2530     return;
2531 
2532   if (location.isUndef())
2533     return;
2534 
2535   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2536     evalBind(Dst, StoreE, *NI, location, Val, false);
2537 }
2538 
2539 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2540                           const Expr *NodeEx,
2541                           const Expr *BoundEx,
2542                           ExplodedNode *Pred,
2543                           ProgramStateRef state,
2544                           SVal location,
2545                           const ProgramPointTag *tag,
2546                           QualType LoadTy)
2547 {
2548   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2549 
2550   // Are we loading from a region?  This actually results in two loads; one
2551   // to fetch the address of the referenced value and one to fetch the
2552   // referenced value.
2553   if (const TypedValueRegion *TR =
2554         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2555 
2556     QualType ValTy = TR->getValueType();
2557     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2558       static SimpleProgramPointTag
2559              loadReferenceTag(TagProviderName, "Load Reference");
2560       ExplodedNodeSet Tmp;
2561       evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2562                      location, &loadReferenceTag,
2563                      getContext().getPointerType(RT->getPointeeType()));
2564 
2565       // Perform the load from the referenced value.
2566       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2567         state = (*I)->getState();
2568         location = state->getSVal(BoundEx, (*I)->getLocationContext());
2569         evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2570       }
2571       return;
2572     }
2573   }
2574 
2575   evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2576 }
2577 
2578 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2579                                 const Expr *NodeEx,
2580                                 const Expr *BoundEx,
2581                                 ExplodedNode *Pred,
2582                                 ProgramStateRef state,
2583                                 SVal location,
2584                                 const ProgramPointTag *tag,
2585                                 QualType LoadTy) {
2586   assert(NodeEx);
2587   assert(BoundEx);
2588   // Evaluate the location (checks for bad dereferences).
2589   ExplodedNodeSet Tmp;
2590   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2591   if (Tmp.empty())
2592     return;
2593 
2594   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2595   if (location.isUndef())
2596     return;
2597 
2598   // Proceed with the load.
2599   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2600     state = (*NI)->getState();
2601     const LocationContext *LCtx = (*NI)->getLocationContext();
2602 
2603     SVal V = UnknownVal();
2604     if (location.isValid()) {
2605       if (LoadTy.isNull())
2606         LoadTy = BoundEx->getType();
2607       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2608     }
2609 
2610     Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2611                       ProgramPoint::PostLoadKind);
2612   }
2613 }
2614 
2615 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2616                               const Stmt *NodeEx,
2617                               const Stmt *BoundEx,
2618                               ExplodedNode *Pred,
2619                               ProgramStateRef state,
2620                               SVal location,
2621                               const ProgramPointTag *tag,
2622                               bool isLoad) {
2623   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2624   // Early checks for performance reason.
2625   if (location.isUnknown()) {
2626     return;
2627   }
2628 
2629   ExplodedNodeSet Src;
2630   BldrTop.takeNodes(Pred);
2631   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2632   if (Pred->getState() != state) {
2633     // Associate this new state with an ExplodedNode.
2634     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2635     //   int *p;
2636     //   p = 0;
2637     //   *p = 0xDEADBEEF;
2638     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2639     // instead "int *p" is noted as
2640     // "Variable 'p' initialized to a null pointer value"
2641 
2642     static SimpleProgramPointTag tag(TagProviderName, "Location");
2643     Bldr.generateNode(NodeEx, Pred, state, &tag);
2644   }
2645   ExplodedNodeSet Tmp;
2646   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2647                                              NodeEx, BoundEx, *this);
2648   BldrTop.addNodes(Tmp);
2649 }
2650 
2651 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2652 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2653   static SimpleProgramPointTag
2654          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2655                                            "Eagerly Assume True"),
2656          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2657                                             "Eagerly Assume False");
2658   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2659                         &eagerlyAssumeBinOpBifurcationFalse);
2660 }
2661 
2662 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2663                                                    ExplodedNodeSet &Src,
2664                                                    const Expr *Ex) {
2665   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2666 
2667   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2668     ExplodedNode *Pred = *I;
2669     // Test if the previous node was as the same expression.  This can happen
2670     // when the expression fails to evaluate to anything meaningful and
2671     // (as an optimization) we don't generate a node.
2672     ProgramPoint P = Pred->getLocation();
2673     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2674       continue;
2675     }
2676 
2677     ProgramStateRef state = Pred->getState();
2678     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2679     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2680     if (SEV && SEV->isExpression()) {
2681       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2682         geteagerlyAssumeBinOpBifurcationTags();
2683 
2684       ProgramStateRef StateTrue, StateFalse;
2685       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2686 
2687       // First assume that the condition is true.
2688       if (StateTrue) {
2689         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2690         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2691         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2692       }
2693 
2694       // Next, assume that the condition is false.
2695       if (StateFalse) {
2696         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2697         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2698         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2699       }
2700     }
2701   }
2702 }
2703 
2704 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2705                                  ExplodedNodeSet &Dst) {
2706   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2707   // We have processed both the inputs and the outputs.  All of the outputs
2708   // should evaluate to Locs.  Nuke all of their values.
2709 
2710   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2711   // which interprets the inline asm and stores proper results in the
2712   // outputs.
2713 
2714   ProgramStateRef state = Pred->getState();
2715 
2716   for (const Expr *O : A->outputs()) {
2717     SVal X = state->getSVal(O, Pred->getLocationContext());
2718     assert (!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2719 
2720     if (Optional<Loc> LV = X.getAs<Loc>())
2721       state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2722   }
2723 
2724   Bldr.generateNode(A, Pred, state);
2725 }
2726 
2727 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2728                                 ExplodedNodeSet &Dst) {
2729   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2730   Bldr.generateNode(A, Pred, Pred->getState());
2731 }
2732 
2733 //===----------------------------------------------------------------------===//
2734 // Visualization.
2735 //===----------------------------------------------------------------------===//
2736 
2737 #ifndef NDEBUG
2738 static ExprEngine* GraphPrintCheckerState;
2739 static SourceManager* GraphPrintSourceManager;
2740 
2741 namespace llvm {
2742 template<>
2743 struct DOTGraphTraits<ExplodedNode*> :
2744   public DefaultDOTGraphTraits {
2745 
2746   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2747 
2748   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2749   // work.
2750   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2751     return "";
2752   }
2753 
2754   // De-duplicate some source location pretty-printing.
2755   static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2756     if (SLoc.isFileID()) {
2757       Out << "\\lline="
2758         << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2759         << " col="
2760         << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2761         << "\\l";
2762     }
2763   }
2764   static void printLocation2(raw_ostream &Out, SourceLocation SLoc) {
2765     if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc))
2766       Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc);
2767     else
2768       SLoc.print(Out, *GraphPrintSourceManager);
2769   }
2770 
2771   static std::string getNodeLabel(const ExplodedNode *N, void*){
2772 
2773     std::string sbuf;
2774     llvm::raw_string_ostream Out(sbuf);
2775 
2776     // Program Location.
2777     ProgramPoint Loc = N->getLocation();
2778 
2779     switch (Loc.getKind()) {
2780       case ProgramPoint::BlockEntranceKind: {
2781         Out << "Block Entrance: B"
2782             << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2783         break;
2784       }
2785 
2786       case ProgramPoint::BlockExitKind:
2787         assert (false);
2788         break;
2789 
2790       case ProgramPoint::CallEnterKind:
2791         Out << "CallEnter";
2792         break;
2793 
2794       case ProgramPoint::CallExitBeginKind:
2795         Out << "CallExitBegin";
2796         break;
2797 
2798       case ProgramPoint::CallExitEndKind:
2799         Out << "CallExitEnd";
2800         break;
2801 
2802       case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2803         Out << "PostStmtPurgeDeadSymbols";
2804         break;
2805 
2806       case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2807         Out << "PreStmtPurgeDeadSymbols";
2808         break;
2809 
2810       case ProgramPoint::EpsilonKind:
2811         Out << "Epsilon Point";
2812         break;
2813 
2814       case ProgramPoint::LoopExitKind: {
2815         LoopExit LE = Loc.castAs<LoopExit>();
2816         Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
2817         break;
2818       }
2819 
2820       case ProgramPoint::PreImplicitCallKind: {
2821         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2822         Out << "PreCall: ";
2823 
2824         // FIXME: Get proper printing options.
2825         PC.getDecl()->print(Out, LangOptions());
2826         printLocation(Out, PC.getLocation());
2827         break;
2828       }
2829 
2830       case ProgramPoint::PostImplicitCallKind: {
2831         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2832         Out << "PostCall: ";
2833 
2834         // FIXME: Get proper printing options.
2835         PC.getDecl()->print(Out, LangOptions());
2836         printLocation(Out, PC.getLocation());
2837         break;
2838       }
2839 
2840       case ProgramPoint::PostInitializerKind: {
2841         Out << "PostInitializer: ";
2842         const CXXCtorInitializer *Init =
2843           Loc.castAs<PostInitializer>().getInitializer();
2844         if (const FieldDecl *FD = Init->getAnyMember())
2845           Out << *FD;
2846         else {
2847           QualType Ty = Init->getTypeSourceInfo()->getType();
2848           Ty = Ty.getLocalUnqualifiedType();
2849           LangOptions LO; // FIXME.
2850           Ty.print(Out, LO);
2851         }
2852         break;
2853       }
2854 
2855       case ProgramPoint::BlockEdgeKind: {
2856         const BlockEdge &E = Loc.castAs<BlockEdge>();
2857         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2858             << E.getDst()->getBlockID()  << ')';
2859 
2860         if (const Stmt *T = E.getSrc()->getTerminator()) {
2861           SourceLocation SLoc = T->getLocStart();
2862 
2863           Out << "\\|Terminator: ";
2864           LangOptions LO; // FIXME.
2865           E.getSrc()->printTerminator(Out, LO);
2866 
2867           if (SLoc.isFileID()) {
2868             Out << "\\lline="
2869               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2870               << " col="
2871               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2872           }
2873 
2874           if (isa<SwitchStmt>(T)) {
2875             const Stmt *Label = E.getDst()->getLabel();
2876 
2877             if (Label) {
2878               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2879                 Out << "\\lcase ";
2880                 LangOptions LO; // FIXME.
2881                 if (C->getLHS())
2882                   C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2883 
2884                 if (const Stmt *RHS = C->getRHS()) {
2885                   Out << " .. ";
2886                   RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2887                 }
2888 
2889                 Out << ":";
2890               }
2891               else {
2892                 assert (isa<DefaultStmt>(Label));
2893                 Out << "\\ldefault:";
2894               }
2895             }
2896             else
2897               Out << "\\l(implicit) default:";
2898           }
2899           else if (isa<IndirectGotoStmt>(T)) {
2900             // FIXME
2901           }
2902           else {
2903             Out << "\\lCondition: ";
2904             if (*E.getSrc()->succ_begin() == E.getDst())
2905               Out << "true";
2906             else
2907               Out << "false";
2908           }
2909 
2910           Out << "\\l";
2911         }
2912 
2913         break;
2914       }
2915 
2916       default: {
2917         const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2918         assert(S != nullptr && "Expecting non-null Stmt");
2919 
2920         Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2921         LangOptions LO; // FIXME.
2922         S->printPretty(Out, nullptr, PrintingPolicy(LO));
2923         printLocation(Out, S->getLocStart());
2924 
2925         if (Loc.getAs<PreStmt>())
2926           Out << "\\lPreStmt\\l;";
2927         else if (Loc.getAs<PostLoad>())
2928           Out << "\\lPostLoad\\l;";
2929         else if (Loc.getAs<PostStore>())
2930           Out << "\\lPostStore\\l";
2931         else if (Loc.getAs<PostLValue>())
2932           Out << "\\lPostLValue\\l";
2933 
2934         break;
2935       }
2936     }
2937 
2938     ProgramStateRef state = N->getState();
2939     Out << "\\|StateID: " << (const void*) state.get()
2940         << " NodeID: " << (const void*) N << "\\|";
2941 
2942     // Analysis stack backtrace.
2943     Out << "Location context stack (from current to outer):\\l";
2944     const LocationContext *LC = Loc.getLocationContext();
2945     unsigned Idx = 0;
2946     for (; LC; LC = LC->getParent(), ++Idx) {
2947       Out << Idx << ". (" << (const void *)LC << ") ";
2948       switch (LC->getKind()) {
2949       case LocationContext::StackFrame:
2950         if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl()))
2951           Out << "Calling " << D->getQualifiedNameAsString();
2952         else
2953           Out << "Calling anonymous code";
2954         if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) {
2955           Out << " at ";
2956           printLocation2(Out, S->getLocStart());
2957         }
2958         break;
2959       case LocationContext::Block:
2960         Out << "Invoking block";
2961         if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) {
2962           Out << " defined at ";
2963           printLocation2(Out, D->getLocStart());
2964         }
2965         break;
2966       case LocationContext::Scope:
2967         Out << "Entering scope";
2968         // FIXME: Add more info once ScopeContext is activated.
2969         break;
2970       }
2971       Out << "\\l";
2972     }
2973     Out << "\\l";
2974 
2975     state->printDOT(Out);
2976 
2977     Out << "\\l";
2978 
2979     if (const ProgramPointTag *tag = Loc.getTag()) {
2980       Out << "\\|Tag: " << tag->getTagDescription();
2981       Out << "\\l";
2982     }
2983     return Out.str();
2984   }
2985 };
2986 } // end llvm namespace
2987 #endif
2988 
2989 void ExprEngine::ViewGraph(bool trim) {
2990 #ifndef NDEBUG
2991   if (trim) {
2992     std::vector<const ExplodedNode*> Src;
2993 
2994     // Flush any outstanding reports to make sure we cover all the nodes.
2995     // This does not cause them to get displayed.
2996     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2997       const_cast<BugType*>(*I)->FlushReports(BR);
2998 
2999     // Iterate through the reports and get their nodes.
3000     for (BugReporter::EQClasses_iterator
3001            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3002       ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
3003       if (N) Src.push_back(N);
3004     }
3005 
3006     ViewGraph(Src);
3007   }
3008   else {
3009     GraphPrintCheckerState = this;
3010     GraphPrintSourceManager = &getContext().getSourceManager();
3011 
3012     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
3013 
3014     GraphPrintCheckerState = nullptr;
3015     GraphPrintSourceManager = nullptr;
3016   }
3017 #endif
3018 }
3019 
3020 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
3021 #ifndef NDEBUG
3022   GraphPrintCheckerState = this;
3023   GraphPrintSourceManager = &getContext().getSourceManager();
3024 
3025   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3026 
3027   if (!TrimmedG.get())
3028     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3029   else
3030     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
3031 
3032   GraphPrintCheckerState = nullptr;
3033   GraphPrintSourceManager = nullptr;
3034 #endif
3035 }
3036