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