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