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