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