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