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