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