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