1 //== RegionStore.cpp - Field-sensitive store model --------------*- 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 basic region store model. In this model, we do have field
11 // sensitivity. But we assume nothing about the heap shape. So recursive data
12 // structures are largely ignored. Basically we do 1-limiting analysis.
13 // Parameter pointers are assumed with no aliasing. Pointee objects of
14 // parameters are created lazily.
15 //
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/CharUnits.h"
18 #include "clang/Analysis/Analyses/LiveVariables.h"
19 #include "clang/Analysis/AnalysisContext.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
25 #include "llvm/ADT/ImmutableList.h"
26 #include "llvm/ADT/ImmutableMap.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace clang;
31 using namespace ento;
32 using llvm::Optional;
33 
34 //===----------------------------------------------------------------------===//
35 // Representation of binding keys.
36 //===----------------------------------------------------------------------===//
37 
38 namespace {
39 class BindingKey {
40 public:
41   enum Kind { Default = 0x0, Direct = 0x1 };
42 private:
43   enum { Symbolic = 0x2 };
44 
45   llvm::PointerIntPair<const MemRegion *, 2> P;
46   uint64_t Data;
47 
48   explicit BindingKey(const MemRegion *r, const MemRegion *Base, Kind k)
49     : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
50     assert(r && Base && "Must have known regions.");
51     assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
52   }
53   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
54     : P(r, k), Data(offset) {
55     assert(r && "Must have known regions.");
56     assert(getOffset() == offset && "Failed to store offset");
57     assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base");
58   }
59 public:
60 
61   bool isDirect() const { return P.getInt() & Direct; }
62   bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
63 
64   const MemRegion *getRegion() const { return P.getPointer(); }
65   uint64_t getOffset() const {
66     assert(!hasSymbolicOffset());
67     return Data;
68   }
69 
70   const MemRegion *getConcreteOffsetRegion() const {
71     assert(hasSymbolicOffset());
72     return reinterpret_cast<const MemRegion *>(static_cast<uintptr_t>(Data));
73   }
74 
75   const MemRegion *getBaseRegion() const {
76     if (hasSymbolicOffset())
77       return getConcreteOffsetRegion()->getBaseRegion();
78     return getRegion()->getBaseRegion();
79   }
80 
81   void Profile(llvm::FoldingSetNodeID& ID) const {
82     ID.AddPointer(P.getOpaqueValue());
83     ID.AddInteger(Data);
84   }
85 
86   static BindingKey Make(const MemRegion *R, Kind k);
87 
88   bool operator<(const BindingKey &X) const {
89     if (P.getOpaqueValue() < X.P.getOpaqueValue())
90       return true;
91     if (P.getOpaqueValue() > X.P.getOpaqueValue())
92       return false;
93     return Data < X.Data;
94   }
95 
96   bool operator==(const BindingKey &X) const {
97     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
98            Data == X.Data;
99   }
100 
101   LLVM_ATTRIBUTE_USED void dump() const;
102 };
103 } // end anonymous namespace
104 
105 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
106   const RegionOffset &RO = R->getAsOffset();
107   if (RO.hasSymbolicOffset())
108     return BindingKey(R, RO.getRegion(), k);
109 
110   return BindingKey(RO.getRegion(), RO.getOffset(), k);
111 }
112 
113 namespace llvm {
114   static inline
115   raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
116     os << '(' << K.getRegion();
117     if (!K.hasSymbolicOffset())
118       os << ',' << K.getOffset();
119     os << ',' << (K.isDirect() ? "direct" : "default")
120        << ')';
121     return os;
122   }
123 } // end llvm namespace
124 
125 void BindingKey::dump() const {
126   llvm::errs() << *this;
127 }
128 
129 //===----------------------------------------------------------------------===//
130 // Actual Store type.
131 //===----------------------------------------------------------------------===//
132 
133 typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings;
134 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings> RegionBindings;
135 
136 //===----------------------------------------------------------------------===//
137 // Fine-grained control of RegionStoreManager.
138 //===----------------------------------------------------------------------===//
139 
140 namespace {
141 struct minimal_features_tag {};
142 struct maximal_features_tag {};
143 
144 class RegionStoreFeatures {
145   bool SupportsFields;
146 public:
147   RegionStoreFeatures(minimal_features_tag) :
148     SupportsFields(false) {}
149 
150   RegionStoreFeatures(maximal_features_tag) :
151     SupportsFields(true) {}
152 
153   void enableFields(bool t) { SupportsFields = t; }
154 
155   bool supportsFields() const { return SupportsFields; }
156 };
157 }
158 
159 //===----------------------------------------------------------------------===//
160 // Main RegionStore logic.
161 //===----------------------------------------------------------------------===//
162 
163 namespace {
164 
165 class RegionStoreManager : public StoreManager {
166   const RegionStoreFeatures Features;
167   RegionBindings::Factory RBFactory;
168   ClusterBindings::Factory CBFactory;
169 
170 public:
171   RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
172     : StoreManager(mgr), Features(f),
173       RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()) {}
174 
175   Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R);
176   /// getDefaultBinding - Returns an SVal* representing an optional default
177   ///  binding associated with a region and its subregions.
178   Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R);
179 
180   /// setImplicitDefaultValue - Set the default binding for the provided
181   ///  MemRegion to the value implicitly defined for compound literals when
182   ///  the value is not specified.
183   StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T);
184 
185   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
186   ///  type.  'Array' represents the lvalue of the array being decayed
187   ///  to a pointer, and the returned SVal represents the decayed
188   ///  version of that lvalue (i.e., a pointer to the first element of
189   ///  the array).  This is called by ExprEngine when evaluating
190   ///  casts from arrays to pointers.
191   SVal ArrayToPointer(Loc Array);
192 
193   StoreRef getInitialStore(const LocationContext *InitLoc) {
194     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
195   }
196 
197   //===-------------------------------------------------------------------===//
198   // Binding values to regions.
199   //===-------------------------------------------------------------------===//
200   RegionBindings invalidateGlobalRegion(MemRegion::Kind K,
201                                         const Expr *Ex,
202                                         unsigned Count,
203                                         const LocationContext *LCtx,
204                                         RegionBindings B,
205                                         InvalidatedRegions *Invalidated);
206 
207   StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions,
208                              const Expr *E, unsigned Count,
209                              const LocationContext *LCtx,
210                              InvalidatedSymbols &IS,
211                              const CallEvent *Call,
212                              InvalidatedRegions *Invalidated);
213 
214   bool scanReachableSymbols(Store S, const MemRegion *R,
215                             ScanReachableSymbols &Callbacks);
216 
217 public:   // Made public for helper classes.
218 
219   RegionBindings removeSubRegionBindings(RegionBindings B, const SubRegion *R);
220 
221   RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V);
222 
223   RegionBindings addBinding(RegionBindings B, const MemRegion *R,
224                      BindingKey::Kind k, SVal V);
225 
226   const SVal *lookup(RegionBindings B, BindingKey K);
227   const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k);
228 
229   RegionBindings removeBinding(RegionBindings B, BindingKey K);
230   RegionBindings removeBinding(RegionBindings B, const MemRegion *R,
231                                BindingKey::Kind k);
232 
233   RegionBindings removeBinding(RegionBindings B, const MemRegion *R) {
234     return removeBinding(removeBinding(B, R, BindingKey::Direct), R,
235                         BindingKey::Default);
236   }
237 
238   RegionBindings removeCluster(RegionBindings B, const MemRegion *R);
239 
240 public: // Part of public interface to class.
241 
242   StoreRef Bind(Store store, Loc LV, SVal V);
243 
244   // BindDefault is only used to initialize a region with a default value.
245   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
246     RegionBindings B = GetRegionBindings(store);
247     assert(!lookup(B, R, BindingKey::Default));
248     assert(!lookup(B, R, BindingKey::Direct));
249     return StoreRef(addBinding(B, R, BindingKey::Default, V)
250                       .getRootWithoutRetain(), *this);
251   }
252 
253   /// \brief Create a new store that binds a value to a compound literal.
254   ///
255   /// \param ST The original store whose bindings are the basis for the new
256   ///        store.
257   ///
258   /// \param CL The compound literal to bind (the binding key).
259   ///
260   /// \param LC The LocationContext for the binding.
261   ///
262   /// \param V The value to bind to the compound literal.
263   StoreRef bindCompoundLiteral(Store ST,
264                                const CompoundLiteralExpr *CL,
265                                const LocationContext *LC, SVal V);
266 
267   /// BindStruct - Bind a compound value to a structure.
268   StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V);
269 
270   /// BindVector - Bind a compound value to a vector.
271   StoreRef BindVector(Store store, const TypedValueRegion* R, SVal V);
272 
273   StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V);
274 
275   /// Clears out all bindings in the given region and assigns a new value
276   /// as a Default binding.
277   StoreRef BindAggregate(Store store, const TypedRegion *R, SVal DefaultVal);
278 
279   /// \brief Create a new store with the specified binding removed.
280   /// \param ST the original store, that is the basis for the new store.
281   /// \param L the location whose binding should be removed.
282   StoreRef killBinding(Store ST, Loc L);
283 
284   void incrementReferenceCount(Store store) {
285     GetRegionBindings(store).manualRetain();
286   }
287 
288   /// If the StoreManager supports it, decrement the reference count of
289   /// the specified Store object.  If the reference count hits 0, the memory
290   /// associated with the object is recycled.
291   void decrementReferenceCount(Store store) {
292     GetRegionBindings(store).manualRelease();
293   }
294 
295   bool includedInBindings(Store store, const MemRegion *region) const;
296 
297   /// \brief Return the value bound to specified location in a given state.
298   ///
299   /// The high level logic for this method is this:
300   /// getBinding (L)
301   ///   if L has binding
302   ///     return L's binding
303   ///   else if L is in killset
304   ///     return unknown
305   ///   else
306   ///     if L is on stack or heap
307   ///       return undefined
308   ///     else
309   ///       return symbolic
310   SVal getBinding(Store store, Loc L, QualType T = QualType());
311 
312   SVal getBindingForElement(Store store, const ElementRegion *R);
313 
314   SVal getBindingForField(Store store, const FieldRegion *R);
315 
316   SVal getBindingForObjCIvar(Store store, const ObjCIvarRegion *R);
317 
318   SVal getBindingForVar(Store store, const VarRegion *R);
319 
320   SVal getBindingForLazySymbol(const TypedValueRegion *R);
321 
322   SVal getBindingForFieldOrElementCommon(Store store, const TypedValueRegion *R,
323                                          QualType Ty, const MemRegion *superR);
324 
325   SVal getLazyBinding(const MemRegion *lazyBindingRegion,
326                       Store lazyBindingStore);
327 
328   /// Get bindings for the values in a struct and return a CompoundVal, used
329   /// when doing struct copy:
330   /// struct s x, y;
331   /// x = y;
332   /// y's value is retrieved by this method.
333   SVal getBindingForStruct(Store store, const TypedValueRegion* R);
334 
335   SVal getBindingForArray(Store store, const TypedValueRegion* R);
336 
337   /// Used to lazily generate derived symbols for bindings that are defined
338   ///  implicitly by default bindings in a super region.
339   Optional<SVal> getBindingForDerivedDefaultValue(RegionBindings B,
340                                                   const MemRegion *superR,
341                                                   const TypedValueRegion *R,
342                                                   QualType Ty);
343 
344   /// Get the state and region whose binding this region R corresponds to.
345   std::pair<Store, const MemRegion*>
346   GetLazyBinding(RegionBindings B, const MemRegion *R,
347                  const MemRegion *originalRegion,
348                  bool includeSuffix = false);
349 
350   //===------------------------------------------------------------------===//
351   // State pruning.
352   //===------------------------------------------------------------------===//
353 
354   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
355   ///  It returns a new Store with these values removed.
356   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
357                               SymbolReaper& SymReaper);
358 
359   //===------------------------------------------------------------------===//
360   // Region "extents".
361   //===------------------------------------------------------------------===//
362 
363   // FIXME: This method will soon be eliminated; see the note in Store.h.
364   DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
365                                          const MemRegion* R, QualType EleTy);
366 
367   //===------------------------------------------------------------------===//
368   // Utility methods.
369   //===------------------------------------------------------------------===//
370 
371   static inline RegionBindings GetRegionBindings(Store store) {
372     return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store));
373   }
374 
375   void print(Store store, raw_ostream &Out, const char* nl,
376              const char *sep);
377 
378   void iterBindings(Store store, BindingsHandler& f) {
379     RegionBindings B = GetRegionBindings(store);
380     for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
381       const ClusterBindings &Cluster = I.getData();
382       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
383            CI != CE; ++CI) {
384         const BindingKey &K = CI.getKey();
385         if (!K.isDirect())
386           continue;
387         if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
388           // FIXME: Possibly incorporate the offset?
389           if (!f.HandleBinding(*this, store, R, CI.getData()))
390             return;
391         }
392       }
393     }
394   }
395 };
396 
397 } // end anonymous namespace
398 
399 //===----------------------------------------------------------------------===//
400 // RegionStore creation.
401 //===----------------------------------------------------------------------===//
402 
403 StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
404   RegionStoreFeatures F = maximal_features_tag();
405   return new RegionStoreManager(StMgr, F);
406 }
407 
408 StoreManager *
409 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
410   RegionStoreFeatures F = minimal_features_tag();
411   F.enableFields(true);
412   return new RegionStoreManager(StMgr, F);
413 }
414 
415 
416 //===----------------------------------------------------------------------===//
417 // Region Cluster analysis.
418 //===----------------------------------------------------------------------===//
419 
420 namespace {
421 template <typename DERIVED>
422 class ClusterAnalysis  {
423 protected:
424   typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
425   typedef SmallVector<const MemRegion *, 10> WorkList;
426 
427   llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
428 
429   WorkList WL;
430 
431   RegionStoreManager &RM;
432   ASTContext &Ctx;
433   SValBuilder &svalBuilder;
434 
435   RegionBindings B;
436 
437   const bool includeGlobals;
438 
439   const ClusterBindings *getCluster(const MemRegion *R) {
440     return B.lookup(R);
441   }
442 
443 public:
444   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
445                   RegionBindings b, const bool includeGlobals)
446     : RM(rm), Ctx(StateMgr.getContext()),
447       svalBuilder(StateMgr.getSValBuilder()),
448       B(b), includeGlobals(includeGlobals) {}
449 
450   RegionBindings getRegionBindings() const { return B; }
451 
452   bool isVisited(const MemRegion *R) {
453     return Visited.count(getCluster(R));
454   }
455 
456   void GenerateClusters() {
457     // Scan the entire set of bindings and record the region clusters.
458     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
459       const MemRegion *Base = RI.getKey();
460 
461       const ClusterBindings &Cluster = RI.getData();
462       assert(!Cluster.isEmpty() && "Empty clusters should be removed");
463       static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
464 
465       if (includeGlobals)
466         if (isa<NonStaticGlobalSpaceRegion>(Base->getMemorySpace()))
467           AddToWorkList(Base, &Cluster);
468     }
469   }
470 
471   bool AddToWorkList(const MemRegion *R, const ClusterBindings *C) {
472     if (C && !Visited.insert(C))
473       return false;
474     WL.push_back(R);
475     return true;
476   }
477 
478   bool AddToWorkList(const MemRegion *R) {
479     const MemRegion *baseR = R->getBaseRegion();
480     return AddToWorkList(baseR, getCluster(baseR));
481   }
482 
483   void RunWorkList() {
484     while (!WL.empty()) {
485       const MemRegion *baseR = WL.pop_back_val();
486 
487       // First visit the cluster.
488       if (const ClusterBindings *Cluster = getCluster(baseR))
489         static_cast<DERIVED*>(this)->VisitCluster(baseR, *Cluster);
490 
491       // Next, visit the base region.
492       static_cast<DERIVED*>(this)->VisitBaseRegion(baseR);
493     }
494   }
495 
496 public:
497   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
498   void VisitCluster(const MemRegion *baseR, const ClusterBindings &C) {}
499   void VisitBaseRegion(const MemRegion *baseR) {}
500 };
501 }
502 
503 //===----------------------------------------------------------------------===//
504 // Binding invalidation.
505 //===----------------------------------------------------------------------===//
506 
507 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
508                                               ScanReachableSymbols &Callbacks) {
509   assert(R == R->getBaseRegion() && "Should only be called for base regions");
510   RegionBindings B = GetRegionBindings(S);
511   const ClusterBindings *Cluster = B.lookup(R);
512 
513   if (!Cluster)
514     return true;
515 
516   for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
517        RI != RE; ++RI) {
518     if (!Callbacks.scan(RI.getData()))
519       return false;
520   }
521 
522   return true;
523 }
524 
525 RegionBindings RegionStoreManager::removeSubRegionBindings(RegionBindings B,
526                                                            const SubRegion *R) {
527   BindingKey SRKey = BindingKey::Make(R, BindingKey::Default);
528   const MemRegion *ClusterHead = SRKey.getBaseRegion();
529   if (R == ClusterHead) {
530     // We can remove an entire cluster's bindings all in one go.
531     return RBFactory.remove(B, R);
532   }
533 
534   if (SRKey.hasSymbolicOffset()) {
535     const SubRegion *Base = cast<SubRegion>(SRKey.getConcreteOffsetRegion());
536     B = removeSubRegionBindings(B, Base);
537     return addBinding(B, Base, BindingKey::Default, UnknownVal());
538   }
539 
540   // This assumes the region being invalidated is char-aligned. This isn't
541   // true for bitfields, but since bitfields have no subregions they shouldn't
542   // be using this function anyway.
543   uint64_t Length = UINT64_MAX;
544 
545   SVal Extent = R->getExtent(svalBuilder);
546   if (nonloc::ConcreteInt *ExtentCI = dyn_cast<nonloc::ConcreteInt>(&Extent)) {
547     const llvm::APSInt &ExtentInt = ExtentCI->getValue();
548     assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
549     // Extents are in bytes but region offsets are in bits. Be careful!
550     Length = ExtentInt.getLimitedValue() * Ctx.getCharWidth();
551   }
552 
553   const ClusterBindings *Cluster = B.lookup(ClusterHead);
554   if (!Cluster)
555     return B;
556 
557   ClusterBindings Result = *Cluster;
558 
559   // It is safe to iterate over the bindings as they are being changed
560   // because they are in an ImmutableMap.
561   for (ClusterBindings::iterator I = Cluster->begin(), E = Cluster->end();
562        I != E; ++I) {
563     BindingKey NextKey = I.getKey();
564     if (NextKey.getRegion() == SRKey.getRegion()) {
565       if (NextKey.getOffset() > SRKey.getOffset() &&
566           NextKey.getOffset() - SRKey.getOffset() < Length) {
567         // Case 1: The next binding is inside the region we're invalidating.
568         // Remove it.
569         Result = CBFactory.remove(Result, NextKey);
570       } else if (NextKey.getOffset() == SRKey.getOffset()) {
571         // Case 2: The next binding is at the same offset as the region we're
572         // invalidating. In this case, we need to leave default bindings alone,
573         // since they may be providing a default value for a regions beyond what
574         // we're invalidating.
575         // FIXME: This is probably incorrect; consider invalidating an outer
576         // struct whose first field is bound to a LazyCompoundVal.
577         if (NextKey.isDirect())
578           Result = CBFactory.remove(Result, NextKey);
579       }
580     } else if (NextKey.hasSymbolicOffset()) {
581       const MemRegion *Base = NextKey.getConcreteOffsetRegion();
582       if (R->isSubRegionOf(Base)) {
583         // Case 3: The next key is symbolic and we just changed something within
584         // its concrete region. We don't know if the binding is still valid, so
585         // we'll be conservative and remove it.
586         if (NextKey.isDirect())
587           Result = CBFactory.remove(Result, NextKey);
588       } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
589         // Case 4: The next key is symbolic, but we changed a known
590         // super-region. In this case the binding is certainly no longer valid.
591         if (R == Base || BaseSR->isSubRegionOf(R))
592           Result = CBFactory.remove(Result, NextKey);
593       }
594     }
595   }
596 
597   if (Result.isEmpty())
598     return RBFactory.remove(B, ClusterHead);
599   return RBFactory.add(B, ClusterHead, Result);
600 }
601 
602 namespace {
603 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
604 {
605   const Expr *Ex;
606   unsigned Count;
607   const LocationContext *LCtx;
608   StoreManager::InvalidatedSymbols &IS;
609   StoreManager::InvalidatedRegions *Regions;
610 public:
611   invalidateRegionsWorker(RegionStoreManager &rm,
612                           ProgramStateManager &stateMgr,
613                           RegionBindings b,
614                           const Expr *ex, unsigned count,
615                           const LocationContext *lctx,
616                           StoreManager::InvalidatedSymbols &is,
617                           StoreManager::InvalidatedRegions *r,
618                           bool includeGlobals)
619     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals),
620       Ex(ex), Count(count), LCtx(lctx), IS(is), Regions(r) {}
621 
622   void VisitCluster(const MemRegion *baseR, const ClusterBindings &C);
623   void VisitBaseRegion(const MemRegion *baseR);
624 
625 private:
626   void VisitBinding(SVal V);
627 };
628 }
629 
630 void invalidateRegionsWorker::VisitBinding(SVal V) {
631   // A symbol?  Mark it touched by the invalidation.
632   if (SymbolRef Sym = V.getAsSymbol())
633     IS.insert(Sym);
634 
635   if (const MemRegion *R = V.getAsRegion()) {
636     AddToWorkList(R);
637     return;
638   }
639 
640   // Is it a LazyCompoundVal?  All references get invalidated as well.
641   if (const nonloc::LazyCompoundVal *LCS =
642         dyn_cast<nonloc::LazyCompoundVal>(&V)) {
643 
644     const MemRegion *LazyR = LCS->getRegion();
645     RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
646 
647     // FIXME: This should not have to walk all bindings in the old store.
648     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
649       const ClusterBindings &Cluster = RI.getData();
650       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
651            CI != CE; ++CI) {
652         BindingKey K = CI.getKey();
653         if (const SubRegion *BaseR = dyn_cast<SubRegion>(K.getRegion())) {
654           if (BaseR == LazyR)
655             VisitBinding(CI.getData());
656           else if (K.hasSymbolicOffset() && BaseR->isSubRegionOf(LazyR))
657             VisitBinding(CI.getData());
658         }
659       }
660     }
661 
662     return;
663   }
664 }
665 
666 void invalidateRegionsWorker::VisitCluster(const MemRegion *BaseR,
667                                            const ClusterBindings &C) {
668   for (ClusterBindings::iterator I = C.begin(), E = C.end(); I != E; ++I)
669     VisitBinding(I.getData());
670 
671   B = RM.removeCluster(B, BaseR);
672 }
673 
674 void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) {
675   // Symbolic region?  Mark that symbol touched by the invalidation.
676   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
677     IS.insert(SR->getSymbol());
678 
679   // BlockDataRegion?  If so, invalidate captured variables that are passed
680   // by reference.
681   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
682     for (BlockDataRegion::referenced_vars_iterator
683          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
684          BI != BE; ++BI) {
685       const VarRegion *VR = *BI;
686       const VarDecl *VD = VR->getDecl();
687       if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
688         AddToWorkList(VR);
689       }
690       else if (Loc::isLocType(VR->getValueType())) {
691         // Map the current bindings to a Store to retrieve the value
692         // of the binding.  If that binding itself is a region, we should
693         // invalidate that region.  This is because a block may capture
694         // a pointer value, but the thing pointed by that pointer may
695         // get invalidated.
696         Store store = B.getRootWithoutRetain();
697         SVal V = RM.getBinding(store, loc::MemRegionVal(VR));
698         if (const Loc *L = dyn_cast<Loc>(&V)) {
699           if (const MemRegion *LR = L->getAsRegion())
700             AddToWorkList(LR);
701         }
702       }
703     }
704     return;
705   }
706 
707   // Otherwise, we have a normal data region. Record that we touched the region.
708   if (Regions)
709     Regions->push_back(baseR);
710 
711   if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
712     // Invalidate the region by setting its default value to
713     // conjured symbol. The type of the symbol is irrelavant.
714     DefinedOrUnknownSVal V =
715       svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
716     B = RM.addBinding(B, baseR, BindingKey::Default, V);
717     return;
718   }
719 
720   if (!baseR->isBoundable())
721     return;
722 
723   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
724   QualType T = TR->getValueType();
725 
726     // Invalidate the binding.
727   if (T->isStructureOrClassType()) {
728     // Invalidate the region by setting its default value to
729     // conjured symbol. The type of the symbol is irrelavant.
730     DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
731                                                           Ctx.IntTy, Count);
732     B = RM.addBinding(B, baseR, BindingKey::Default, V);
733     return;
734   }
735 
736   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
737       // Set the default value of the array to conjured symbol.
738     DefinedOrUnknownSVal V =
739     svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
740                                      AT->getElementType(), Count);
741     B = RM.addBinding(B, baseR, BindingKey::Default, V);
742     return;
743   }
744 
745   if (includeGlobals &&
746       isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) {
747     // If the region is a global and we are invalidating all globals,
748     // just erase the entry.  This causes all globals to be lazily
749     // symbolicated from the same base symbol.
750     B = RM.removeBinding(B, baseR);
751     return;
752   }
753 
754 
755   DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
756                                                         T,Count);
757   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
758   B = RM.addBinding(B, baseR, BindingKey::Direct, V);
759 }
760 
761 RegionBindings RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
762                                                           const Expr *Ex,
763                                                           unsigned Count,
764                                                     const LocationContext *LCtx,
765                                                           RegionBindings B,
766                                             InvalidatedRegions *Invalidated) {
767   // Bind the globals memory space to a new symbol that we will use to derive
768   // the bindings for all globals.
769   const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
770   SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx,
771                                         /* type does not matter */ Ctx.IntTy,
772                                         Count);
773 
774   B = removeBinding(B, GS);
775   B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
776 
777   // Even if there are no bindings in the global scope, we still need to
778   // record that we touched it.
779   if (Invalidated)
780     Invalidated->push_back(GS);
781 
782   return B;
783 }
784 
785 StoreRef RegionStoreManager::invalidateRegions(Store store,
786                                             ArrayRef<const MemRegion *> Regions,
787                                                const Expr *Ex, unsigned Count,
788                                                const LocationContext *LCtx,
789                                                InvalidatedSymbols &IS,
790                                                const CallEvent *Call,
791                                               InvalidatedRegions *Invalidated) {
792   invalidateRegionsWorker W(*this, StateMgr,
793                             RegionStoreManager::GetRegionBindings(store),
794                             Ex, Count, LCtx, IS, Invalidated, false);
795 
796   // Scan the bindings and generate the clusters.
797   W.GenerateClusters();
798 
799   // Add the regions to the worklist.
800   for (ArrayRef<const MemRegion *>::iterator
801        I = Regions.begin(), E = Regions.end(); I != E; ++I)
802     W.AddToWorkList(*I);
803 
804   W.RunWorkList();
805 
806   // Return the new bindings.
807   RegionBindings B = W.getRegionBindings();
808 
809   // For all globals which are not static nor immutable: determine which global
810   // regions should be invalidated and invalidate them.
811   // TODO: This could possibly be more precise with modules.
812   //
813   // System calls invalidate only system globals.
814   if (Call && Call->isInSystemHeader()) {
815     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
816                                Ex, Count, LCtx, B, Invalidated);
817   // Internal calls might invalidate both system and internal globals.
818   } else {
819     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
820                                Ex, Count, LCtx, B, Invalidated);
821     B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
822                                Ex, Count, LCtx, B, Invalidated);
823   }
824 
825   return StoreRef(B.getRootWithoutRetain(), *this);
826 }
827 
828 //===----------------------------------------------------------------------===//
829 // Extents for regions.
830 //===----------------------------------------------------------------------===//
831 
832 DefinedOrUnknownSVal
833 RegionStoreManager::getSizeInElements(ProgramStateRef state,
834                                       const MemRegion *R,
835                                       QualType EleTy) {
836   SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
837   const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
838   if (!SizeInt)
839     return UnknownVal();
840 
841   CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
842 
843   if (Ctx.getAsVariableArrayType(EleTy)) {
844     // FIXME: We need to track extra state to properly record the size
845     // of VLAs.  Returning UnknownVal here, however, is a stop-gap so that
846     // we don't have a divide-by-zero below.
847     return UnknownVal();
848   }
849 
850   CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
851 
852   // If a variable is reinterpreted as a type that doesn't fit into a larger
853   // type evenly, round it down.
854   // This is a signed value, since it's used in arithmetic with signed indices.
855   return svalBuilder.makeIntVal(RegionSize / EleSize, false);
856 }
857 
858 //===----------------------------------------------------------------------===//
859 // Location and region casting.
860 //===----------------------------------------------------------------------===//
861 
862 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
863 ///  type.  'Array' represents the lvalue of the array being decayed
864 ///  to a pointer, and the returned SVal represents the decayed
865 ///  version of that lvalue (i.e., a pointer to the first element of
866 ///  the array).  This is called by ExprEngine when evaluating casts
867 ///  from arrays to pointers.
868 SVal RegionStoreManager::ArrayToPointer(Loc Array) {
869   if (!isa<loc::MemRegionVal>(Array))
870     return UnknownVal();
871 
872   const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
873   const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
874 
875   if (!ArrayR)
876     return UnknownVal();
877 
878   // Strip off typedefs from the ArrayRegion's ValueType.
879   QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
880   const ArrayType *AT = cast<ArrayType>(T);
881   T = AT->getElementType();
882 
883   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
884   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
885 }
886 
887 //===----------------------------------------------------------------------===//
888 // Loading values from regions.
889 //===----------------------------------------------------------------------===//
890 
891 Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B,
892                                                     const MemRegion *R) {
893 
894   if (const SVal *V = lookup(B, R, BindingKey::Direct))
895     return *V;
896 
897   return Optional<SVal>();
898 }
899 
900 Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B,
901                                                      const MemRegion *R) {
902   if (R->isBoundable())
903     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
904       if (TR->getValueType()->isUnionType())
905         return UnknownVal();
906 
907   if (const SVal *V = lookup(B, R, BindingKey::Default))
908     return *V;
909 
910   return Optional<SVal>();
911 }
912 
913 SVal RegionStoreManager::getBinding(Store store, Loc L, QualType T) {
914   assert(!isa<UnknownVal>(L) && "location unknown");
915   assert(!isa<UndefinedVal>(L) && "location undefined");
916 
917   // For access to concrete addresses, return UnknownVal.  Checks
918   // for null dereferences (and similar errors) are done by checkers, not
919   // the Store.
920   // FIXME: We can consider lazily symbolicating such memory, but we really
921   // should defer this when we can reason easily about symbolicating arrays
922   // of bytes.
923   if (isa<loc::ConcreteInt>(L)) {
924     return UnknownVal();
925   }
926   if (!isa<loc::MemRegionVal>(L)) {
927     return UnknownVal();
928   }
929 
930   const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion();
931 
932   if (isa<AllocaRegion>(MR) ||
933       isa<SymbolicRegion>(MR) ||
934       isa<CodeTextRegion>(MR)) {
935     if (T.isNull()) {
936       if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
937         T = TR->getLocationType();
938       else {
939         const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
940         T = SR->getSymbol()->getType();
941       }
942     }
943     MR = GetElementZeroRegion(MR, T);
944   }
945 
946   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
947   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
948   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
949   QualType RTy = R->getValueType();
950 
951   // FIXME: We should eventually handle funny addressing.  e.g.:
952   //
953   //   int x = ...;
954   //   int *p = &x;
955   //   char *q = (char*) p;
956   //   char c = *q;  // returns the first byte of 'x'.
957   //
958   // Such funny addressing will occur due to layering of regions.
959 
960   if (RTy->isStructureOrClassType())
961     return getBindingForStruct(store, R);
962 
963   // FIXME: Handle unions.
964   if (RTy->isUnionType())
965     return UnknownVal();
966 
967   if (RTy->isArrayType()) {
968     if (RTy->isConstantArrayType())
969       return getBindingForArray(store, R);
970     else
971       return UnknownVal();
972   }
973 
974   // FIXME: handle Vector types.
975   if (RTy->isVectorType())
976     return UnknownVal();
977 
978   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
979     return CastRetrievedVal(getBindingForField(store, FR), FR, T, false);
980 
981   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
982     // FIXME: Here we actually perform an implicit conversion from the loaded
983     // value to the element type.  Eventually we want to compose these values
984     // more intelligently.  For example, an 'element' can encompass multiple
985     // bound regions (e.g., several bound bytes), or could be a subset of
986     // a larger value.
987     return CastRetrievedVal(getBindingForElement(store, ER), ER, T, false);
988   }
989 
990   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
991     // FIXME: Here we actually perform an implicit conversion from the loaded
992     // value to the ivar type.  What we should model is stores to ivars
993     // that blow past the extent of the ivar.  If the address of the ivar is
994     // reinterpretted, it is possible we stored a different value that could
995     // fit within the ivar.  Either we need to cast these when storing them
996     // or reinterpret them lazily (as we do here).
997     return CastRetrievedVal(getBindingForObjCIvar(store, IVR), IVR, T, false);
998   }
999 
1000   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1001     // FIXME: Here we actually perform an implicit conversion from the loaded
1002     // value to the variable type.  What we should model is stores to variables
1003     // that blow past the extent of the variable.  If the address of the
1004     // variable is reinterpretted, it is possible we stored a different value
1005     // that could fit within the variable.  Either we need to cast these when
1006     // storing them or reinterpret them lazily (as we do here).
1007     return CastRetrievedVal(getBindingForVar(store, VR), VR, T, false);
1008   }
1009 
1010   RegionBindings B = GetRegionBindings(store);
1011   const SVal *V = lookup(B, R, BindingKey::Direct);
1012 
1013   // Check if the region has a binding.
1014   if (V)
1015     return *V;
1016 
1017   // The location does not have a bound value.  This means that it has
1018   // the value it had upon its creation and/or entry to the analyzed
1019   // function/method.  These are either symbolic values or 'undefined'.
1020   if (R->hasStackNonParametersStorage()) {
1021     // All stack variables are considered to have undefined values
1022     // upon creation.  All heap allocated blocks are considered to
1023     // have undefined values as well unless they are explicitly bound
1024     // to specific values.
1025     return UndefinedVal();
1026   }
1027 
1028   // All other values are symbolic.
1029   return svalBuilder.getRegionValueSymbolVal(R);
1030 }
1031 
1032 std::pair<Store, const MemRegion *>
1033 RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R,
1034                                    const MemRegion *originalRegion,
1035                                    bool includeSuffix) {
1036 
1037   if (originalRegion != R) {
1038     if (Optional<SVal> OV = getDefaultBinding(B, R)) {
1039       if (const nonloc::LazyCompoundVal *V =
1040           dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer()))
1041         return std::make_pair(V->getStore(), V->getRegion());
1042     }
1043   }
1044 
1045   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1046     const std::pair<Store, const MemRegion *> &X =
1047       GetLazyBinding(B, ER->getSuperRegion(), originalRegion);
1048 
1049     if (X.second)
1050       return std::make_pair(X.first,
1051                             MRMgr.getElementRegionWithSuper(ER, X.second));
1052   }
1053   else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1054     const std::pair<Store, const MemRegion *> &X =
1055       GetLazyBinding(B, FR->getSuperRegion(), originalRegion);
1056 
1057     if (X.second) {
1058       if (includeSuffix)
1059         return std::make_pair(X.first,
1060                               MRMgr.getFieldRegionWithSuper(FR, X.second));
1061       return X;
1062     }
1063 
1064   }
1065   // C++ base object region is another kind of region that we should blast
1066   // through to look for lazy compound value. It is like a field region.
1067   else if (const CXXBaseObjectRegion *baseReg =
1068                             dyn_cast<CXXBaseObjectRegion>(R)) {
1069     const std::pair<Store, const MemRegion *> &X =
1070       GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion);
1071 
1072     if (X.second) {
1073       if (includeSuffix)
1074         return std::make_pair(X.first,
1075                               MRMgr.getCXXBaseObjectRegionWithSuper(baseReg,
1076                                                                     X.second));
1077       return X;
1078     }
1079   }
1080 
1081   // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is
1082   // possible for a valid lazy binding.
1083   return std::make_pair((Store) 0, (const MemRegion *) 0);
1084 }
1085 
1086 SVal RegionStoreManager::getBindingForElement(Store store,
1087                                               const ElementRegion* R) {
1088   // We do not currently model bindings of the CompoundLiteralregion.
1089   if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
1090     return UnknownVal();
1091 
1092   // Check if the region has a binding.
1093   RegionBindings B = GetRegionBindings(store);
1094   if (const Optional<SVal> &V = getDirectBinding(B, R))
1095     return *V;
1096 
1097   const MemRegion* superR = R->getSuperRegion();
1098 
1099   // Check if the region is an element region of a string literal.
1100   if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
1101     // FIXME: Handle loads from strings where the literal is treated as
1102     // an integer, e.g., *((unsigned int*)"hello")
1103     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1104     if (T != Ctx.getCanonicalType(R->getElementType()))
1105       return UnknownVal();
1106 
1107     const StringLiteral *Str = StrR->getStringLiteral();
1108     SVal Idx = R->getIndex();
1109     if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) {
1110       int64_t i = CI->getValue().getSExtValue();
1111       // Abort on string underrun.  This can be possible by arbitrary
1112       // clients of getBindingForElement().
1113       if (i < 0)
1114         return UndefinedVal();
1115       int64_t length = Str->getLength();
1116       // Technically, only i == length is guaranteed to be null.
1117       // However, such overflows should be caught before reaching this point;
1118       // the only time such an access would be made is if a string literal was
1119       // used to initialize a larger array.
1120       char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
1121       return svalBuilder.makeIntVal(c, T);
1122     }
1123   }
1124 
1125   // Check for loads from a code text region.  For such loads, just give up.
1126   if (isa<CodeTextRegion>(superR))
1127     return UnknownVal();
1128 
1129   // Handle the case where we are indexing into a larger scalar object.
1130   // For example, this handles:
1131   //   int x = ...
1132   //   char *y = &x;
1133   //   return *y;
1134   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1135   const RegionRawOffset &O = R->getAsArrayOffset();
1136 
1137   // If we cannot reason about the offset, return an unknown value.
1138   if (!O.getRegion())
1139     return UnknownVal();
1140 
1141   if (const TypedValueRegion *baseR =
1142         dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1143     QualType baseT = baseR->getValueType();
1144     if (baseT->isScalarType()) {
1145       QualType elemT = R->getElementType();
1146       if (elemT->isScalarType()) {
1147         if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1148           if (const Optional<SVal> &V = getDirectBinding(B, superR)) {
1149             if (SymbolRef parentSym = V->getAsSymbol())
1150               return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1151 
1152             if (V->isUnknownOrUndef())
1153               return *V;
1154             // Other cases: give up.  We are indexing into a larger object
1155             // that has some value, but we don't know how to handle that yet.
1156             return UnknownVal();
1157           }
1158         }
1159       }
1160     }
1161   }
1162   return getBindingForFieldOrElementCommon(store, R, R->getElementType(),
1163                                            superR);
1164 }
1165 
1166 SVal RegionStoreManager::getBindingForField(Store store,
1167                                        const FieldRegion* R) {
1168 
1169   // Check if the region has a binding.
1170   RegionBindings B = GetRegionBindings(store);
1171   if (const Optional<SVal> &V = getDirectBinding(B, R))
1172     return *V;
1173 
1174   QualType Ty = R->getValueType();
1175   return getBindingForFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
1176 }
1177 
1178 Optional<SVal>
1179 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindings B,
1180                                                      const MemRegion *superR,
1181                                                      const TypedValueRegion *R,
1182                                                      QualType Ty) {
1183 
1184   if (const Optional<SVal> &D = getDefaultBinding(B, superR)) {
1185     const SVal &val = D.getValue();
1186     if (SymbolRef parentSym = val.getAsSymbol())
1187       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1188 
1189     if (val.isZeroConstant())
1190       return svalBuilder.makeZeroVal(Ty);
1191 
1192     if (val.isUnknownOrUndef())
1193       return val;
1194 
1195     // Lazy bindings are handled later.
1196     if (isa<nonloc::LazyCompoundVal>(val))
1197       return Optional<SVal>();
1198 
1199     llvm_unreachable("Unknown default value");
1200   }
1201 
1202   return Optional<SVal>();
1203 }
1204 
1205 SVal RegionStoreManager::getLazyBinding(const MemRegion *lazyBindingRegion,
1206                                              Store lazyBindingStore) {
1207   if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion))
1208     return getBindingForElement(lazyBindingStore, ER);
1209 
1210   return getBindingForField(lazyBindingStore,
1211                             cast<FieldRegion>(lazyBindingRegion));
1212 }
1213 
1214 SVal RegionStoreManager::getBindingForFieldOrElementCommon(Store store,
1215                                                       const TypedValueRegion *R,
1216                                                       QualType Ty,
1217                                                       const MemRegion *superR) {
1218 
1219   // At this point we have already checked in either getBindingForElement or
1220   // getBindingForField if 'R' has a direct binding.
1221   RegionBindings B = GetRegionBindings(store);
1222 
1223   // Lazy binding?
1224   Store lazyBindingStore = NULL;
1225   const MemRegion *lazyBindingRegion = NULL;
1226   llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R,
1227                                                                   true);
1228 
1229   if (lazyBindingRegion)
1230     return getLazyBinding(lazyBindingRegion, lazyBindingStore);
1231 
1232   // Record whether or not we see a symbolic index.  That can completely
1233   // be out of scope of our lookup.
1234   bool hasSymbolicIndex = false;
1235 
1236   while (superR) {
1237     if (const Optional<SVal> &D =
1238         getBindingForDerivedDefaultValue(B, superR, R, Ty))
1239       return *D;
1240 
1241     if (const ElementRegion *ER = dyn_cast<ElementRegion>(superR)) {
1242       NonLoc index = ER->getIndex();
1243       if (!index.isConstant())
1244         hasSymbolicIndex = true;
1245     }
1246 
1247     // If our super region is a field or element itself, walk up the region
1248     // hierarchy to see if there is a default value installed in an ancestor.
1249     if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) {
1250       superR = SR->getSuperRegion();
1251       continue;
1252     }
1253     break;
1254   }
1255 
1256   if (R->hasStackNonParametersStorage()) {
1257     if (isa<ElementRegion>(R)) {
1258       // Currently we don't reason specially about Clang-style vectors.  Check
1259       // if superR is a vector and if so return Unknown.
1260       if (const TypedValueRegion *typedSuperR =
1261             dyn_cast<TypedValueRegion>(superR)) {
1262         if (typedSuperR->getValueType()->isVectorType())
1263           return UnknownVal();
1264       }
1265     }
1266 
1267     // FIXME: We also need to take ElementRegions with symbolic indexes into
1268     // account.  This case handles both directly accessing an ElementRegion
1269     // with a symbolic offset, but also fields within an element with
1270     // a symbolic offset.
1271     if (hasSymbolicIndex)
1272       return UnknownVal();
1273 
1274     return UndefinedVal();
1275   }
1276 
1277   // All other values are symbolic.
1278   return svalBuilder.getRegionValueSymbolVal(R);
1279 }
1280 
1281 SVal RegionStoreManager::getBindingForObjCIvar(Store store,
1282                                                const ObjCIvarRegion* R) {
1283 
1284     // Check if the region has a binding.
1285   RegionBindings B = GetRegionBindings(store);
1286 
1287   if (const Optional<SVal> &V = getDirectBinding(B, R))
1288     return *V;
1289 
1290   const MemRegion *superR = R->getSuperRegion();
1291 
1292   // Check if the super region has a default binding.
1293   if (const Optional<SVal> &V = getDefaultBinding(B, superR)) {
1294     if (SymbolRef parentSym = V->getAsSymbol())
1295       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1296 
1297     // Other cases: give up.
1298     return UnknownVal();
1299   }
1300 
1301   return getBindingForLazySymbol(R);
1302 }
1303 
1304 SVal RegionStoreManager::getBindingForVar(Store store, const VarRegion *R) {
1305 
1306   // Check if the region has a binding.
1307   RegionBindings B = GetRegionBindings(store);
1308 
1309   if (const Optional<SVal> &V = getDirectBinding(B, R))
1310     return *V;
1311 
1312   // Lazily derive a value for the VarRegion.
1313   const VarDecl *VD = R->getDecl();
1314   QualType T = VD->getType();
1315   const MemSpaceRegion *MS = R->getMemorySpace();
1316 
1317   if (isa<UnknownSpaceRegion>(MS) ||
1318       isa<StackArgumentsSpaceRegion>(MS))
1319     return svalBuilder.getRegionValueSymbolVal(R);
1320 
1321   if (isa<GlobalsSpaceRegion>(MS)) {
1322     if (isa<NonStaticGlobalSpaceRegion>(MS)) {
1323       // Is 'VD' declared constant?  If so, retrieve the constant value.
1324       QualType CT = Ctx.getCanonicalType(T);
1325       if (CT.isConstQualified()) {
1326         const Expr *Init = VD->getInit();
1327         // Do the null check first, as we want to call 'IgnoreParenCasts'.
1328         if (Init)
1329           if (const IntegerLiteral *IL =
1330               dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) {
1331             const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL);
1332             return svalBuilder.evalCast(V, Init->getType(), IL->getType());
1333           }
1334       }
1335 
1336       if (const Optional<SVal> &V
1337             = getBindingForDerivedDefaultValue(B, MS, R, CT))
1338         return V.getValue();
1339 
1340       return svalBuilder.getRegionValueSymbolVal(R);
1341     }
1342 
1343     if (T->isIntegerType())
1344       return svalBuilder.makeIntVal(0, T);
1345     if (T->isPointerType())
1346       return svalBuilder.makeNull();
1347 
1348     return UnknownVal();
1349   }
1350 
1351   return UndefinedVal();
1352 }
1353 
1354 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
1355   // All other values are symbolic.
1356   return svalBuilder.getRegionValueSymbolVal(R);
1357 }
1358 
1359 static bool mayHaveLazyBinding(QualType Ty) {
1360   return Ty->isArrayType() || Ty->isStructureOrClassType();
1361 }
1362 
1363 SVal RegionStoreManager::getBindingForStruct(Store store,
1364                                         const TypedValueRegion* R) {
1365   const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
1366   if (RD->field_empty())
1367     return UnknownVal();
1368 
1369   // If we already have a lazy binding, don't create a new one,
1370   // unless the first field might have a lazy binding of its own.
1371   // (Right now we can't tell the difference.)
1372   QualType FirstFieldType = RD->field_begin()->getType();
1373   if (!mayHaveLazyBinding(FirstFieldType)) {
1374     RegionBindings B = GetRegionBindings(store);
1375     BindingKey K = BindingKey::Make(R, BindingKey::Default);
1376     if (const nonloc::LazyCompoundVal *V =
1377           dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) {
1378       return *V;
1379     }
1380   }
1381 
1382   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
1383 }
1384 
1385 SVal RegionStoreManager::getBindingForArray(Store store,
1386                                        const TypedValueRegion * R) {
1387   const ConstantArrayType *Ty = Ctx.getAsConstantArrayType(R->getValueType());
1388   assert(Ty && "Only constant array types can have compound bindings.");
1389 
1390   // If we already have a lazy binding, don't create a new one,
1391   // unless the first element might have a lazy binding of its own.
1392   // (Right now we can't tell the difference.)
1393   if (!mayHaveLazyBinding(Ty->getElementType())) {
1394     RegionBindings B = GetRegionBindings(store);
1395     BindingKey K = BindingKey::Make(R, BindingKey::Default);
1396     if (const nonloc::LazyCompoundVal *V =
1397         dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) {
1398       return *V;
1399     }
1400   }
1401 
1402   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
1403 }
1404 
1405 bool RegionStoreManager::includedInBindings(Store store,
1406                                             const MemRegion *region) const {
1407   RegionBindings B = GetRegionBindings(store);
1408   region = region->getBaseRegion();
1409 
1410   // Quick path: if the base is the head of a cluster, the region is live.
1411   if (B.lookup(region))
1412     return true;
1413 
1414   // Slow path: if the region is the VALUE of any binding, it is live.
1415   for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
1416     const ClusterBindings &Cluster = RI.getData();
1417     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1418          CI != CE; ++CI) {
1419       const SVal &D = CI.getData();
1420       if (const MemRegion *R = D.getAsRegion())
1421         if (R->getBaseRegion() == region)
1422           return true;
1423     }
1424   }
1425 
1426   return false;
1427 }
1428 
1429 //===----------------------------------------------------------------------===//
1430 // Binding values to regions.
1431 //===----------------------------------------------------------------------===//
1432 
1433 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
1434   if (isa<loc::MemRegionVal>(L))
1435     if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion())
1436       return StoreRef(removeBinding(GetRegionBindings(ST),
1437                                     R).getRootWithoutRetain(),
1438                       *this);
1439 
1440   return StoreRef(ST, *this);
1441 }
1442 
1443 StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) {
1444   if (isa<loc::ConcreteInt>(L))
1445     return StoreRef(store, *this);
1446 
1447   // If we get here, the location should be a region.
1448   const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion();
1449 
1450   // Check if the region is a struct region.
1451   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
1452     QualType Ty = TR->getValueType();
1453     if (Ty->isArrayType())
1454       return BindArray(store, TR, V);
1455     if (Ty->isStructureOrClassType())
1456       return BindStruct(store, TR, V);
1457     if (Ty->isVectorType())
1458       return BindVector(store, TR, V);
1459   }
1460 
1461   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1462     // Binding directly to a symbolic region should be treated as binding
1463     // to element 0.
1464     QualType T = SR->getSymbol()->getType();
1465     if (T->isAnyPointerType() || T->isReferenceType())
1466       T = T->getPointeeType();
1467 
1468     R = GetElementZeroRegion(SR, T);
1469   }
1470 
1471   // Clear out bindings that may overlap with this binding.
1472 
1473   // Perform the binding.
1474   RegionBindings B = GetRegionBindings(store);
1475   B = removeSubRegionBindings(B, cast<SubRegion>(R));
1476   BindingKey Key = BindingKey::Make(R, BindingKey::Direct);
1477   return StoreRef(addBinding(B, Key, V).getRootWithoutRetain(), *this);
1478 }
1479 
1480 // FIXME: this method should be merged into Bind().
1481 StoreRef RegionStoreManager::bindCompoundLiteral(Store ST,
1482                                                  const CompoundLiteralExpr *CL,
1483                                                  const LocationContext *LC,
1484                                                  SVal V) {
1485   return Bind(ST, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)), V);
1486 }
1487 
1488 StoreRef RegionStoreManager::setImplicitDefaultValue(Store store,
1489                                                      const MemRegion *R,
1490                                                      QualType T) {
1491   RegionBindings B = GetRegionBindings(store);
1492   SVal V;
1493 
1494   if (Loc::isLocType(T))
1495     V = svalBuilder.makeNull();
1496   else if (T->isIntegerType())
1497     V = svalBuilder.makeZeroVal(T);
1498   else if (T->isStructureOrClassType() || T->isArrayType()) {
1499     // Set the default value to a zero constant when it is a structure
1500     // or array.  The type doesn't really matter.
1501     V = svalBuilder.makeZeroVal(Ctx.IntTy);
1502   }
1503   else {
1504     // We can't represent values of this type, but we still need to set a value
1505     // to record that the region has been initialized.
1506     // If this assertion ever fires, a new case should be added above -- we
1507     // should know how to default-initialize any value we can symbolicate.
1508     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
1509     V = UnknownVal();
1510   }
1511 
1512   return StoreRef(addBinding(B, R, BindingKey::Default,
1513                              V).getRootWithoutRetain(), *this);
1514 }
1515 
1516 StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R,
1517                                        SVal Init) {
1518 
1519   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
1520   QualType ElementTy = AT->getElementType();
1521   Optional<uint64_t> Size;
1522 
1523   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
1524     Size = CAT->getSize().getZExtValue();
1525 
1526   // Check if the init expr is a string literal.
1527   if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) {
1528     const StringRegion *S = cast<StringRegion>(MRV->getRegion());
1529 
1530     // Treat the string as a lazy compound value.
1531     nonloc::LazyCompoundVal LCV =
1532       cast<nonloc::LazyCompoundVal>(svalBuilder.
1533                                 makeLazyCompoundVal(StoreRef(store, *this), S));
1534     return BindAggregate(store, R, LCV);
1535   }
1536 
1537   // Handle lazy compound values.
1538   if (isa<nonloc::LazyCompoundVal>(Init))
1539     return BindAggregate(store, R, Init);
1540 
1541   // Remaining case: explicit compound values.
1542 
1543   if (Init.isUnknown())
1544     return setImplicitDefaultValue(store, R, ElementTy);
1545 
1546   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
1547   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1548   uint64_t i = 0;
1549 
1550   StoreRef newStore(store, *this);
1551   for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
1552     // The init list might be shorter than the array length.
1553     if (VI == VE)
1554       break;
1555 
1556     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
1557     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
1558 
1559     if (ElementTy->isStructureOrClassType())
1560       newStore = BindStruct(newStore.getStore(), ER, *VI);
1561     else if (ElementTy->isArrayType())
1562       newStore = BindArray(newStore.getStore(), ER, *VI);
1563     else
1564       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
1565   }
1566 
1567   // If the init list is shorter than the array length, set the
1568   // array default value.
1569   if (Size.hasValue() && i < Size.getValue())
1570     newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy);
1571 
1572   return newStore;
1573 }
1574 
1575 StoreRef RegionStoreManager::BindVector(Store store, const TypedValueRegion* R,
1576                                         SVal V) {
1577   QualType T = R->getValueType();
1578   assert(T->isVectorType());
1579   const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
1580 
1581   // Handle lazy compound values and symbolic values.
1582   if (isa<nonloc::LazyCompoundVal>(V) || isa<nonloc::SymbolVal>(V))
1583     return BindAggregate(store, R, V);
1584 
1585   // We may get non-CompoundVal accidentally due to imprecise cast logic or
1586   // that we are binding symbolic struct value. Kill the field values, and if
1587   // the value is symbolic go and bind it as a "default" binding.
1588   if (!isa<nonloc::CompoundVal>(V)) {
1589     return BindAggregate(store, R, UnknownVal());
1590   }
1591 
1592   QualType ElemType = VT->getElementType();
1593   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
1594   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1595   unsigned index = 0, numElements = VT->getNumElements();
1596   StoreRef newStore(store, *this);
1597 
1598   for ( ; index != numElements ; ++index) {
1599     if (VI == VE)
1600       break;
1601 
1602     NonLoc Idx = svalBuilder.makeArrayIndex(index);
1603     const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
1604 
1605     if (ElemType->isArrayType())
1606       newStore = BindArray(newStore.getStore(), ER, *VI);
1607     else if (ElemType->isStructureOrClassType())
1608       newStore = BindStruct(newStore.getStore(), ER, *VI);
1609     else
1610       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
1611   }
1612   return newStore;
1613 }
1614 
1615 StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R,
1616                                         SVal V) {
1617 
1618   if (!Features.supportsFields())
1619     return StoreRef(store, *this);
1620 
1621   QualType T = R->getValueType();
1622   assert(T->isStructureOrClassType());
1623 
1624   const RecordType* RT = T->getAs<RecordType>();
1625   RecordDecl *RD = RT->getDecl();
1626 
1627   if (!RD->isCompleteDefinition())
1628     return StoreRef(store, *this);
1629 
1630   // Handle lazy compound values and symbolic values.
1631   if (isa<nonloc::LazyCompoundVal>(V) || isa<nonloc::SymbolVal>(V))
1632     return BindAggregate(store, R, V);
1633 
1634   // We may get non-CompoundVal accidentally due to imprecise cast logic or
1635   // that we are binding symbolic struct value. Kill the field values, and if
1636   // the value is symbolic go and bind it as a "default" binding.
1637   if (V.isUnknown() || !isa<nonloc::CompoundVal>(V))
1638     return BindAggregate(store, R, UnknownVal());
1639 
1640   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
1641   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1642 
1643   RecordDecl::field_iterator FI, FE;
1644   StoreRef newStore(store, *this);
1645 
1646   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
1647 
1648     if (VI == VE)
1649       break;
1650 
1651     // Skip any unnamed bitfields to stay in sync with the initializers.
1652     if (FI->isUnnamedBitfield())
1653       continue;
1654 
1655     QualType FTy = FI->getType();
1656     const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
1657 
1658     if (FTy->isArrayType())
1659       newStore = BindArray(newStore.getStore(), FR, *VI);
1660     else if (FTy->isStructureOrClassType())
1661       newStore = BindStruct(newStore.getStore(), FR, *VI);
1662     else
1663       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
1664     ++VI;
1665   }
1666 
1667   // There may be fewer values in the initialize list than the fields of struct.
1668   if (FI != FE) {
1669     RegionBindings B = GetRegionBindings(newStore.getStore());
1670     B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false));
1671     newStore = StoreRef(B.getRootWithoutRetain(), *this);
1672   }
1673 
1674   return newStore;
1675 }
1676 
1677 StoreRef RegionStoreManager::BindAggregate(Store store, const TypedRegion *R,
1678                                            SVal Val) {
1679   // Remove the old bindings, using 'R' as the root of all regions
1680   // we will invalidate. Then add the new binding.
1681   RegionBindings B = GetRegionBindings(store);
1682 
1683   B = removeSubRegionBindings(B, R);
1684   B = addBinding(B, R, BindingKey::Default, Val);
1685 
1686   return StoreRef(B.getRootWithoutRetain(), *this);
1687 }
1688 
1689 //===----------------------------------------------------------------------===//
1690 // "Raw" retrievals and bindings.
1691 //===----------------------------------------------------------------------===//
1692 
1693 
1694 RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K,
1695                                               SVal V) {
1696   const MemRegion *Base = K.getBaseRegion();
1697 
1698   const ClusterBindings *ExistingCluster = B.lookup(Base);
1699   ClusterBindings Cluster = (ExistingCluster ? *ExistingCluster
1700                                              : CBFactory.getEmptyMap());
1701 
1702   ClusterBindings NewCluster = CBFactory.add(Cluster, K, V);
1703   return RBFactory.add(B, Base, NewCluster);
1704 }
1705 
1706 RegionBindings RegionStoreManager::addBinding(RegionBindings B,
1707                                               const MemRegion *R,
1708                                               BindingKey::Kind k, SVal V) {
1709   return addBinding(B, BindingKey::Make(R, k), V);
1710 }
1711 
1712 const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) {
1713   const ClusterBindings *Cluster = B.lookup(K.getBaseRegion());
1714   if (!Cluster)
1715     return 0;
1716 
1717   return Cluster->lookup(K);
1718 }
1719 
1720 const SVal *RegionStoreManager::lookup(RegionBindings B,
1721                                        const MemRegion *R,
1722                                        BindingKey::Kind k) {
1723   return lookup(B, BindingKey::Make(R, k));
1724 }
1725 
1726 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
1727                                                  BindingKey K) {
1728   const MemRegion *Base = K.getBaseRegion();
1729   const ClusterBindings *Cluster = B.lookup(Base);
1730   if (!Cluster)
1731     return B;
1732 
1733   ClusterBindings NewCluster = CBFactory.remove(*Cluster, K);
1734   if (NewCluster.isEmpty())
1735     return RBFactory.remove(B, Base);
1736   return RBFactory.add(B, Base, NewCluster);
1737 }
1738 
1739 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
1740                                                  const MemRegion *R,
1741                                                  BindingKey::Kind k){
1742   return removeBinding(B, BindingKey::Make(R, k));
1743 }
1744 
1745 RegionBindings RegionStoreManager::removeCluster(RegionBindings B,
1746                                                  const MemRegion *Base) {
1747   return RBFactory.remove(B, Base);
1748 }
1749 
1750 //===----------------------------------------------------------------------===//
1751 // State pruning.
1752 //===----------------------------------------------------------------------===//
1753 
1754 namespace {
1755 class removeDeadBindingsWorker :
1756   public ClusterAnalysis<removeDeadBindingsWorker> {
1757   SmallVector<const SymbolicRegion*, 12> Postponed;
1758   SymbolReaper &SymReaper;
1759   const StackFrameContext *CurrentLCtx;
1760 
1761 public:
1762   removeDeadBindingsWorker(RegionStoreManager &rm,
1763                            ProgramStateManager &stateMgr,
1764                            RegionBindings b, SymbolReaper &symReaper,
1765                            const StackFrameContext *LCtx)
1766     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
1767                                                 /* includeGlobals = */ false),
1768       SymReaper(symReaper), CurrentLCtx(LCtx) {}
1769 
1770   // Called by ClusterAnalysis.
1771   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
1772   void VisitCluster(const MemRegion *baseR, const ClusterBindings &C);
1773 
1774   bool UpdatePostponed();
1775   void VisitBinding(SVal V);
1776 };
1777 }
1778 
1779 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
1780                                                    const ClusterBindings &C) {
1781 
1782   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
1783     if (SymReaper.isLive(VR))
1784       AddToWorkList(baseR, &C);
1785 
1786     return;
1787   }
1788 
1789   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
1790     if (SymReaper.isLive(SR->getSymbol()))
1791       AddToWorkList(SR, &C);
1792     else
1793       Postponed.push_back(SR);
1794 
1795     return;
1796   }
1797 
1798   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
1799     AddToWorkList(baseR, &C);
1800     return;
1801   }
1802 
1803   // CXXThisRegion in the current or parent location context is live.
1804   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
1805     const StackArgumentsSpaceRegion *StackReg =
1806       cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
1807     const StackFrameContext *RegCtx = StackReg->getStackFrame();
1808     if (CurrentLCtx &&
1809         (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)))
1810       AddToWorkList(TR, &C);
1811   }
1812 }
1813 
1814 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
1815                                             const ClusterBindings &C) {
1816   // Mark the symbol for any SymbolicRegion with live bindings as live itself.
1817   // This means we should continue to track that symbol.
1818   if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
1819     SymReaper.markLive(SymR->getSymbol());
1820 
1821   for (ClusterBindings::iterator I = C.begin(), E = C.end(); I != E; ++I)
1822     VisitBinding(I.getData());
1823 }
1824 
1825 void removeDeadBindingsWorker::VisitBinding(SVal V) {
1826   // Is it a LazyCompoundVal?  All referenced regions are live as well.
1827   if (const nonloc::LazyCompoundVal *LCS =
1828         dyn_cast<nonloc::LazyCompoundVal>(&V)) {
1829 
1830     const MemRegion *LazyR = LCS->getRegion();
1831     RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
1832 
1833     // FIXME: This should not have to walk all bindings in the old store.
1834     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
1835       const ClusterBindings &Cluster = RI.getData();
1836       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1837            CI != CE; ++CI) {
1838         BindingKey K = CI.getKey();
1839         if (const SubRegion *BaseR = dyn_cast<SubRegion>(K.getRegion())) {
1840           if (BaseR == LazyR)
1841             VisitBinding(CI.getData());
1842           else if (K.hasSymbolicOffset() && BaseR->isSubRegionOf(LazyR))
1843             VisitBinding(CI.getData());
1844         }
1845       }
1846     }
1847 
1848     return;
1849   }
1850 
1851   // If V is a region, then add it to the worklist.
1852   if (const MemRegion *R = V.getAsRegion()) {
1853     AddToWorkList(R);
1854 
1855     // All regions captured by a block are also live.
1856     if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
1857       BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
1858                                                 E = BR->referenced_vars_end();
1859       for ( ; I != E; ++I)
1860         AddToWorkList(I.getCapturedRegion());
1861     }
1862   }
1863 
1864 
1865   // Update the set of live symbols.
1866   for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
1867        SI!=SE; ++SI)
1868     SymReaper.markLive(*SI);
1869 }
1870 
1871 bool removeDeadBindingsWorker::UpdatePostponed() {
1872   // See if any postponed SymbolicRegions are actually live now, after
1873   // having done a scan.
1874   bool changed = false;
1875 
1876   for (SmallVectorImpl<const SymbolicRegion*>::iterator
1877         I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
1878     if (const SymbolicRegion *SR = *I) {
1879       if (SymReaper.isLive(SR->getSymbol())) {
1880         changed |= AddToWorkList(SR);
1881         *I = NULL;
1882       }
1883     }
1884   }
1885 
1886   return changed;
1887 }
1888 
1889 StoreRef RegionStoreManager::removeDeadBindings(Store store,
1890                                                 const StackFrameContext *LCtx,
1891                                                 SymbolReaper& SymReaper) {
1892   RegionBindings B = GetRegionBindings(store);
1893   removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
1894   W.GenerateClusters();
1895 
1896   // Enqueue the region roots onto the worklist.
1897   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
1898        E = SymReaper.region_end(); I != E; ++I) {
1899     W.AddToWorkList(*I);
1900   }
1901 
1902   do W.RunWorkList(); while (W.UpdatePostponed());
1903 
1904   // We have now scanned the store, marking reachable regions and symbols
1905   // as live.  We now remove all the regions that are dead from the store
1906   // as well as update DSymbols with the set symbols that are now dead.
1907   for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1908     const MemRegion *Base = I.getKey();
1909 
1910     // If the cluster has been visited, we know the region has been marked.
1911     if (W.isVisited(Base))
1912       continue;
1913 
1914     // Remove the dead entry.
1915     B = removeCluster(B, Base);
1916 
1917     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base))
1918       SymReaper.maybeDead(SymR->getSymbol());
1919 
1920     // Mark all non-live symbols that this binding references as dead.
1921     const ClusterBindings &Cluster = I.getData();
1922     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1923          CI != CE; ++CI) {
1924       SVal X = CI.getData();
1925       SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
1926       for (; SI != SE; ++SI)
1927         SymReaper.maybeDead(*SI);
1928     }
1929   }
1930 
1931   return StoreRef(B.getRootWithoutRetain(), *this);
1932 }
1933 
1934 //===----------------------------------------------------------------------===//
1935 // Utility methods.
1936 //===----------------------------------------------------------------------===//
1937 
1938 void RegionStoreManager::print(Store store, raw_ostream &OS,
1939                                const char* nl, const char *sep) {
1940   RegionBindings B = GetRegionBindings(store);
1941   OS << "Store (direct and default bindings), "
1942      << (void*) B.getRootWithoutRetain()
1943      << " :" << nl;
1944 
1945   for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1946     const ClusterBindings &Cluster = I.getData();
1947     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1948          CI != CE; ++CI) {
1949       OS << ' ' << CI.getKey() << " : " << CI.getData() << nl;
1950     }
1951     OS << nl;
1952   }
1953 }
1954