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