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