1 //= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--=
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements ProgramState and ProgramStateManager.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
14 #include "clang/Analysis/CFG.h"
15 #include "clang/Basic/JsonSupport.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace clang;
24 using namespace ento;
25 
26 namespace clang { namespace  ento {
27 /// Increments the number of times this state is referenced.
28 
29 void ProgramStateRetain(const ProgramState *state) {
30   ++const_cast<ProgramState*>(state)->refCount;
31 }
32 
33 /// Decrement the number of times this state is referenced.
34 void ProgramStateRelease(const ProgramState *state) {
35   assert(state->refCount > 0);
36   ProgramState *s = const_cast<ProgramState*>(state);
37   if (--s->refCount == 0) {
38     ProgramStateManager &Mgr = s->getStateManager();
39     Mgr.StateSet.RemoveNode(s);
40     s->~ProgramState();
41     Mgr.freeStates.push_back(s);
42   }
43 }
44 }}
45 
46 ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
47                  StoreRef st, GenericDataMap gdm)
48   : stateMgr(mgr),
49     Env(env),
50     store(st.getStore()),
51     GDM(gdm),
52     refCount(0) {
53   stateMgr->getStoreManager().incrementReferenceCount(store);
54 }
55 
56 ProgramState::ProgramState(const ProgramState &RHS)
57     : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
58       PosteriorlyOverconstrained(RHS.PosteriorlyOverconstrained), refCount(0) {
59   stateMgr->getStoreManager().incrementReferenceCount(store);
60 }
61 
62 ProgramState::~ProgramState() {
63   if (store)
64     stateMgr->getStoreManager().decrementReferenceCount(store);
65 }
66 
67 int64_t ProgramState::getID() const {
68   return getStateManager().Alloc.identifyKnownAlignedObject<ProgramState>(this);
69 }
70 
71 ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
72                                          StoreManagerCreator CreateSMgr,
73                                          ConstraintManagerCreator CreateCMgr,
74                                          llvm::BumpPtrAllocator &alloc,
75                                          ExprEngine *ExprEng)
76   : Eng(ExprEng), EnvMgr(alloc), GDMFactory(alloc),
77     svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
78     CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
79   StoreMgr = (*CreateSMgr)(*this);
80   ConstraintMgr = (*CreateCMgr)(*this, ExprEng);
81 }
82 
83 
84 ProgramStateManager::~ProgramStateManager() {
85   for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
86        I!=E; ++I)
87     I->second.second(I->second.first);
88 }
89 
90 ProgramStateRef ProgramStateManager::removeDeadBindingsFromEnvironmentAndStore(
91     ProgramStateRef state, const StackFrameContext *LCtx,
92     SymbolReaper &SymReaper) {
93 
94   // This code essentially performs a "mark-and-sweep" of the VariableBindings.
95   // The roots are any Block-level exprs and Decls that our liveness algorithm
96   // tells us are live.  We then see what Decls they may reference, and keep
97   // those around.  This code more than likely can be made faster, and the
98   // frequency of which this method is called should be experimented with
99   // for optimum performance.
100   ProgramState NewState = *state;
101 
102   NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
103 
104   // Clean up the store.
105   StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
106                                                    SymReaper);
107   NewState.setStore(newStore);
108   SymReaper.setReapedStore(newStore);
109 
110   return getPersistentState(NewState);
111 }
112 
113 ProgramStateRef ProgramState::bindLoc(Loc LV,
114                                       SVal V,
115                                       const LocationContext *LCtx,
116                                       bool notifyChanges) const {
117   ProgramStateManager &Mgr = getStateManager();
118   ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
119                                                              LV, V));
120   const MemRegion *MR = LV.getAsRegion();
121   if (MR && notifyChanges)
122     return Mgr.getOwningEngine().processRegionChange(newState, MR, LCtx);
123 
124   return newState;
125 }
126 
127 ProgramStateRef
128 ProgramState::bindDefaultInitial(SVal loc, SVal V,
129                                  const LocationContext *LCtx) const {
130   ProgramStateManager &Mgr = getStateManager();
131   const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
132   const StoreRef &newStore = Mgr.StoreMgr->BindDefaultInitial(getStore(), R, V);
133   ProgramStateRef new_state = makeWithStore(newStore);
134   return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
135 }
136 
137 ProgramStateRef
138 ProgramState::bindDefaultZero(SVal loc, const LocationContext *LCtx) const {
139   ProgramStateManager &Mgr = getStateManager();
140   const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
141   const StoreRef &newStore = Mgr.StoreMgr->BindDefaultZero(getStore(), R);
142   ProgramStateRef new_state = makeWithStore(newStore);
143   return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
144 }
145 
146 typedef ArrayRef<const MemRegion *> RegionList;
147 typedef ArrayRef<SVal> ValueList;
148 
149 ProgramStateRef
150 ProgramState::invalidateRegions(RegionList Regions,
151                              const Expr *E, unsigned Count,
152                              const LocationContext *LCtx,
153                              bool CausedByPointerEscape,
154                              InvalidatedSymbols *IS,
155                              const CallEvent *Call,
156                              RegionAndSymbolInvalidationTraits *ITraits) const {
157   SmallVector<SVal, 8> Values;
158   for (RegionList::const_iterator I = Regions.begin(),
159                                   End = Regions.end(); I != End; ++I)
160     Values.push_back(loc::MemRegionVal(*I));
161 
162   return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
163                                IS, ITraits, Call);
164 }
165 
166 ProgramStateRef
167 ProgramState::invalidateRegions(ValueList Values,
168                              const Expr *E, unsigned Count,
169                              const LocationContext *LCtx,
170                              bool CausedByPointerEscape,
171                              InvalidatedSymbols *IS,
172                              const CallEvent *Call,
173                              RegionAndSymbolInvalidationTraits *ITraits) const {
174 
175   return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
176                                IS, ITraits, Call);
177 }
178 
179 ProgramStateRef
180 ProgramState::invalidateRegionsImpl(ValueList Values,
181                                     const Expr *E, unsigned Count,
182                                     const LocationContext *LCtx,
183                                     bool CausedByPointerEscape,
184                                     InvalidatedSymbols *IS,
185                                     RegionAndSymbolInvalidationTraits *ITraits,
186                                     const CallEvent *Call) const {
187   ProgramStateManager &Mgr = getStateManager();
188   ExprEngine &Eng = Mgr.getOwningEngine();
189 
190   InvalidatedSymbols InvalidatedSyms;
191   if (!IS)
192     IS = &InvalidatedSyms;
193 
194   RegionAndSymbolInvalidationTraits ITraitsLocal;
195   if (!ITraits)
196     ITraits = &ITraitsLocal;
197 
198   StoreManager::InvalidatedRegions TopLevelInvalidated;
199   StoreManager::InvalidatedRegions Invalidated;
200   const StoreRef &newStore
201   = Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
202                                     *IS, *ITraits, &TopLevelInvalidated,
203                                     &Invalidated);
204 
205   ProgramStateRef newState = makeWithStore(newStore);
206 
207   if (CausedByPointerEscape) {
208     newState = Eng.notifyCheckersOfPointerEscape(newState, IS,
209                                                  TopLevelInvalidated,
210                                                  Call,
211                                                  *ITraits);
212   }
213 
214   return Eng.processRegionChanges(newState, IS, TopLevelInvalidated,
215                                   Invalidated, LCtx, Call);
216 }
217 
218 ProgramStateRef ProgramState::killBinding(Loc LV) const {
219   assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
220 
221   Store OldStore = getStore();
222   const StoreRef &newStore =
223     getStateManager().StoreMgr->killBinding(OldStore, LV);
224 
225   if (newStore.getStore() == OldStore)
226     return this;
227 
228   return makeWithStore(newStore);
229 }
230 
231 ProgramStateRef
232 ProgramState::enterStackFrame(const CallEvent &Call,
233                               const StackFrameContext *CalleeCtx) const {
234   const StoreRef &NewStore =
235     getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx);
236   return makeWithStore(NewStore);
237 }
238 
239 SVal ProgramState::getSelfSVal(const LocationContext *LCtx) const {
240   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
241   if (!SelfDecl)
242     return SVal();
243   return getSVal(getRegion(SelfDecl, LCtx));
244 }
245 
246 SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
247   // We only want to do fetches from regions that we can actually bind
248   // values.  For example, SymbolicRegions of type 'id<...>' cannot
249   // have direct bindings (but their can be bindings on their subregions).
250   if (!R->isBoundable())
251     return UnknownVal();
252 
253   if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
254     QualType T = TR->getValueType();
255     if (Loc::isLocType(T) || T->isIntegralOrEnumerationType())
256       return getSVal(R);
257   }
258 
259   return UnknownVal();
260 }
261 
262 SVal ProgramState::getSVal(Loc location, QualType T) const {
263   SVal V = getRawSVal(location, T);
264 
265   // If 'V' is a symbolic value that is *perfectly* constrained to
266   // be a constant value, use that value instead to lessen the burden
267   // on later analysis stages (so we have less symbolic values to reason
268   // about).
269   // We only go into this branch if we can convert the APSInt value we have
270   // to the type of T, which is not always the case (e.g. for void).
271   if (!T.isNull() && (T->isIntegralOrEnumerationType() || Loc::isLocType(T))) {
272     if (SymbolRef sym = V.getAsSymbol()) {
273       if (const llvm::APSInt *Int = getStateManager()
274                                     .getConstraintManager()
275                                     .getSymVal(this, sym)) {
276         // FIXME: Because we don't correctly model (yet) sign-extension
277         // and truncation of symbolic values, we need to convert
278         // the integer value to the correct signedness and bitwidth.
279         //
280         // This shows up in the following:
281         //
282         //   char foo();
283         //   unsigned x = foo();
284         //   if (x == 54)
285         //     ...
286         //
287         //  The symbolic value stored to 'x' is actually the conjured
288         //  symbol for the call to foo(); the type of that symbol is 'char',
289         //  not unsigned.
290         const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
291 
292         if (V.getAs<Loc>())
293           return loc::ConcreteInt(NewV);
294         else
295           return nonloc::ConcreteInt(NewV);
296       }
297     }
298   }
299 
300   return V;
301 }
302 
303 ProgramStateRef ProgramState::BindExpr(const Stmt *S,
304                                            const LocationContext *LCtx,
305                                            SVal V, bool Invalidate) const{
306   Environment NewEnv =
307     getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
308                                       Invalidate);
309   if (NewEnv == Env)
310     return this;
311 
312   ProgramState NewSt = *this;
313   NewSt.Env = NewEnv;
314   return getStateManager().getPersistentState(NewSt);
315 }
316 
317 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
318 ProgramState::assumeInBoundDual(DefinedOrUnknownSVal Idx,
319                                 DefinedOrUnknownSVal UpperBound,
320                                 QualType indexTy) const {
321   if (Idx.isUnknown() || UpperBound.isUnknown())
322     return {this, this};
323 
324   // Build an expression for 0 <= Idx < UpperBound.
325   // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
326   // FIXME: This should probably be part of SValBuilder.
327   ProgramStateManager &SM = getStateManager();
328   SValBuilder &svalBuilder = SM.getSValBuilder();
329   ASTContext &Ctx = svalBuilder.getContext();
330 
331   // Get the offset: the minimum value of the array index type.
332   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
333   if (indexTy.isNull())
334     indexTy = svalBuilder.getArrayIndexType();
335   nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
336 
337   // Adjust the index.
338   SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
339                                         Idx.castAs<NonLoc>(), Min, indexTy);
340   if (newIdx.isUnknownOrUndef())
341     return {this, this};
342 
343   // Adjust the upper bound.
344   SVal newBound =
345     svalBuilder.evalBinOpNN(this, BO_Add, UpperBound.castAs<NonLoc>(),
346                             Min, indexTy);
347 
348   if (newBound.isUnknownOrUndef())
349     return {this, this};
350 
351   // Build the actual comparison.
352   SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs<NonLoc>(),
353                                          newBound.castAs<NonLoc>(), Ctx.IntTy);
354   if (inBound.isUnknownOrUndef())
355     return {this, this};
356 
357   // Finally, let the constraint manager take care of it.
358   ConstraintManager &CM = SM.getConstraintManager();
359   return CM.assumeDual(this, inBound.castAs<DefinedSVal>());
360 }
361 
362 ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
363                                             DefinedOrUnknownSVal UpperBound,
364                                             bool Assumption,
365                                             QualType indexTy) const {
366   std::pair<ProgramStateRef, ProgramStateRef> R =
367       assumeInBoundDual(Idx, UpperBound, indexTy);
368   return Assumption ? R.first : R.second;
369 }
370 
371 ConditionTruthVal ProgramState::isNonNull(SVal V) const {
372   ConditionTruthVal IsNull = isNull(V);
373   if (IsNull.isUnderconstrained())
374     return IsNull;
375   return ConditionTruthVal(!IsNull.getValue());
376 }
377 
378 ConditionTruthVal ProgramState::areEqual(SVal Lhs, SVal Rhs) const {
379   return stateMgr->getSValBuilder().areEqual(this, Lhs, Rhs);
380 }
381 
382 ConditionTruthVal ProgramState::isNull(SVal V) const {
383   if (V.isZeroConstant())
384     return true;
385 
386   if (V.isConstant())
387     return false;
388 
389   SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ true);
390   if (!Sym)
391     return ConditionTruthVal();
392 
393   return getStateManager().ConstraintMgr->isNull(this, Sym);
394 }
395 
396 ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
397   ProgramState State(this,
398                 EnvMgr.getInitialEnvironment(),
399                 StoreMgr->getInitialStore(InitLoc),
400                 GDMFactory.getEmptyMap());
401 
402   return getPersistentState(State);
403 }
404 
405 ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
406                                                      ProgramStateRef FromState,
407                                                      ProgramStateRef GDMState) {
408   ProgramState NewState(*FromState);
409   NewState.GDM = GDMState->GDM;
410   return getPersistentState(NewState);
411 }
412 
413 ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
414 
415   llvm::FoldingSetNodeID ID;
416   State.Profile(ID);
417   void *InsertPos;
418 
419   if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
420     return I;
421 
422   ProgramState *newState = nullptr;
423   if (!freeStates.empty()) {
424     newState = freeStates.back();
425     freeStates.pop_back();
426   }
427   else {
428     newState = (ProgramState*) Alloc.Allocate<ProgramState>();
429   }
430   new (newState) ProgramState(State);
431   StateSet.InsertNode(newState, InsertPos);
432   return newState;
433 }
434 
435 ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
436   ProgramState NewSt(*this);
437   NewSt.setStore(store);
438   return getStateManager().getPersistentState(NewSt);
439 }
440 
441 ProgramStateRef ProgramState::cloneAsPosteriorlyOverconstrained() const {
442   ProgramState NewSt(*this);
443   NewSt.PosteriorlyOverconstrained = true;
444   return getStateManager().getPersistentState(NewSt);
445 }
446 
447 void ProgramState::setStore(const StoreRef &newStore) {
448   Store newStoreStore = newStore.getStore();
449   if (newStoreStore)
450     stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
451   if (store)
452     stateMgr->getStoreManager().decrementReferenceCount(store);
453   store = newStoreStore;
454 }
455 
456 //===----------------------------------------------------------------------===//
457 //  State pretty-printing.
458 //===----------------------------------------------------------------------===//
459 
460 void ProgramState::printJson(raw_ostream &Out, const LocationContext *LCtx,
461                              const char *NL, unsigned int Space,
462                              bool IsDot) const {
463   Indent(Out, Space, IsDot) << "\"program_state\": {" << NL;
464   ++Space;
465 
466   ProgramStateManager &Mgr = getStateManager();
467 
468   // Print the store.
469   Mgr.getStoreManager().printJson(Out, getStore(), NL, Space, IsDot);
470 
471   // Print out the environment.
472   Env.printJson(Out, Mgr.getContext(), LCtx, NL, Space, IsDot);
473 
474   // Print out the constraints.
475   Mgr.getConstraintManager().printJson(Out, this, NL, Space, IsDot);
476 
477   // Print out the tracked dynamic types.
478   printDynamicTypeInfoJson(Out, this, NL, Space, IsDot);
479 
480   // Print checker-specific data.
481   Mgr.getOwningEngine().printJson(Out, this, LCtx, NL, Space, IsDot);
482 
483   --Space;
484   Indent(Out, Space, IsDot) << '}';
485 }
486 
487 void ProgramState::printDOT(raw_ostream &Out, const LocationContext *LCtx,
488                             unsigned int Space) const {
489   printJson(Out, LCtx, /*NL=*/"\\l", Space, /*IsDot=*/true);
490 }
491 
492 LLVM_DUMP_METHOD void ProgramState::dump() const {
493   printJson(llvm::errs());
494 }
495 
496 AnalysisManager& ProgramState::getAnalysisManager() const {
497   return stateMgr->getOwningEngine().getAnalysisManager();
498 }
499 
500 //===----------------------------------------------------------------------===//
501 // Generic Data Map.
502 //===----------------------------------------------------------------------===//
503 
504 void *const* ProgramState::FindGDM(void *K) const {
505   return GDM.lookup(K);
506 }
507 
508 void*
509 ProgramStateManager::FindGDMContext(void *K,
510                                void *(*CreateContext)(llvm::BumpPtrAllocator&),
511                                void (*DeleteContext)(void*)) {
512 
513   std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
514   if (!p.first) {
515     p.first = CreateContext(Alloc);
516     p.second = DeleteContext;
517   }
518 
519   return p.first;
520 }
521 
522 ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
523   ProgramState::GenericDataMap M1 = St->getGDM();
524   ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
525 
526   if (M1 == M2)
527     return St;
528 
529   ProgramState NewSt = *St;
530   NewSt.GDM = M2;
531   return getPersistentState(NewSt);
532 }
533 
534 ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
535   ProgramState::GenericDataMap OldM = state->getGDM();
536   ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
537 
538   if (NewM == OldM)
539     return state;
540 
541   ProgramState NewState = *state;
542   NewState.GDM = NewM;
543   return getPersistentState(NewState);
544 }
545 
546 bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
547   bool wasVisited = !visited.insert(val.getCVData()).second;
548   if (wasVisited)
549     return true;
550 
551   StoreManager &StoreMgr = state->getStateManager().getStoreManager();
552   // FIXME: We don't really want to use getBaseRegion() here because pointer
553   // arithmetic doesn't apply, but scanReachableSymbols only accepts base
554   // regions right now.
555   const MemRegion *R = val.getRegion()->getBaseRegion();
556   return StoreMgr.scanReachableSymbols(val.getStore(), R, *this);
557 }
558 
559 bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
560   for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
561     if (!scan(*I))
562       return false;
563 
564   return true;
565 }
566 
567 bool ScanReachableSymbols::scan(const SymExpr *sym) {
568   for (SymExpr::symbol_iterator SI = sym->symbol_begin(),
569                                 SE = sym->symbol_end();
570        SI != SE; ++SI) {
571     bool wasVisited = !visited.insert(*SI).second;
572     if (wasVisited)
573       continue;
574 
575     if (!visitor.VisitSymbol(*SI))
576       return false;
577   }
578 
579   return true;
580 }
581 
582 bool ScanReachableSymbols::scan(SVal val) {
583   if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
584     return scan(X->getRegion());
585 
586   if (Optional<nonloc::LazyCompoundVal> X =
587           val.getAs<nonloc::LazyCompoundVal>())
588     return scan(*X);
589 
590   if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
591     return scan(X->getLoc());
592 
593   if (SymbolRef Sym = val.getAsSymbol())
594     return scan(Sym);
595 
596   if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
597     return scan(*X);
598 
599   return true;
600 }
601 
602 bool ScanReachableSymbols::scan(const MemRegion *R) {
603   if (isa<MemSpaceRegion>(R))
604     return true;
605 
606   bool wasVisited = !visited.insert(R).second;
607   if (wasVisited)
608     return true;
609 
610   if (!visitor.VisitMemRegion(R))
611     return false;
612 
613   // If this is a symbolic region, visit the symbol for the region.
614   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
615     if (!visitor.VisitSymbol(SR->getSymbol()))
616       return false;
617 
618   // If this is a subregion, also visit the parent regions.
619   if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
620     const MemRegion *Super = SR->getSuperRegion();
621     if (!scan(Super))
622       return false;
623 
624     // When we reach the topmost region, scan all symbols in it.
625     if (isa<MemSpaceRegion>(Super)) {
626       StoreManager &StoreMgr = state->getStateManager().getStoreManager();
627       if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
628         return false;
629     }
630   }
631 
632   // Regions captured by a block are also implicitly reachable.
633   if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
634     BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
635                                               E = BDR->referenced_vars_end();
636     for ( ; I != E; ++I) {
637       if (!scan(I.getCapturedRegion()))
638         return false;
639     }
640   }
641 
642   return true;
643 }
644 
645 bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
646   ScanReachableSymbols S(this, visitor);
647   return S.scan(val);
648 }
649 
650 bool ProgramState::scanReachableSymbols(
651     llvm::iterator_range<region_iterator> Reachable,
652     SymbolVisitor &visitor) const {
653   ScanReachableSymbols S(this, visitor);
654   for (const MemRegion *R : Reachable) {
655     if (!S.scan(R))
656       return false;
657   }
658   return true;
659 }
660