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