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