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