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