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/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/Analysis/Analyses/LiveVariables.h"
20 #include "clang/Analysis/AnalysisContext.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
28 #include "llvm/ADT/ImmutableList.h"
29 #include "llvm/ADT/ImmutableMap.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace clang;
34 using namespace ento;
35 
36 //===----------------------------------------------------------------------===//
37 // Representation of binding keys.
38 //===----------------------------------------------------------------------===//
39 
40 namespace {
41 class BindingKey {
42 public:
43   enum Kind { Default = 0x0, Direct = 0x1 };
44 private:
45   enum { Symbolic = 0x2 };
46 
47   llvm::PointerIntPair<const MemRegion *, 2> P;
48   uint64_t Data;
49 
50   /// Create a key for a binding to region \p r, which has a symbolic offset
51   /// from region \p Base.
52   explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k)
53     : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
54     assert(r && Base && "Must have known regions.");
55     assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
56   }
57 
58   /// Create a key for a binding at \p offset from base region \p r.
59   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
60     : P(r, k), Data(offset) {
61     assert(r && "Must have known regions.");
62     assert(getOffset() == offset && "Failed to store offset");
63     assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base");
64   }
65 public:
66 
67   bool isDirect() const { return P.getInt() & Direct; }
68   bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
69 
70   const MemRegion *getRegion() const { return P.getPointer(); }
71   uint64_t getOffset() const {
72     assert(!hasSymbolicOffset());
73     return Data;
74   }
75 
76   const SubRegion *getConcreteOffsetRegion() const {
77     assert(hasSymbolicOffset());
78     return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
79   }
80 
81   const MemRegion *getBaseRegion() const {
82     if (hasSymbolicOffset())
83       return getConcreteOffsetRegion()->getBaseRegion();
84     return getRegion()->getBaseRegion();
85   }
86 
87   void Profile(llvm::FoldingSetNodeID& ID) const {
88     ID.AddPointer(P.getOpaqueValue());
89     ID.AddInteger(Data);
90   }
91 
92   static BindingKey Make(const MemRegion *R, Kind k);
93 
94   bool operator<(const BindingKey &X) const {
95     if (P.getOpaqueValue() < X.P.getOpaqueValue())
96       return true;
97     if (P.getOpaqueValue() > X.P.getOpaqueValue())
98       return false;
99     return Data < X.Data;
100   }
101 
102   bool operator==(const BindingKey &X) const {
103     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
104            Data == X.Data;
105   }
106 
107   LLVM_ATTRIBUTE_USED void dump() const;
108 };
109 } // end anonymous namespace
110 
111 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
112   const RegionOffset &RO = R->getAsOffset();
113   if (RO.hasSymbolicOffset())
114     return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
115 
116   return BindingKey(RO.getRegion(), RO.getOffset(), k);
117 }
118 
119 namespace llvm {
120   static inline
121   raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
122     os << '(' << K.getRegion();
123     if (!K.hasSymbolicOffset())
124       os << ',' << K.getOffset();
125     os << ',' << (K.isDirect() ? "direct" : "default")
126        << ')';
127     return os;
128   }
129 
130   template <typename T> struct isPodLike;
131   template <> struct isPodLike<BindingKey> {
132     static const bool value = true;
133   };
134 } // end llvm namespace
135 
136 void BindingKey::dump() const {
137   llvm::errs() << *this;
138 }
139 
140 //===----------------------------------------------------------------------===//
141 // Actual Store type.
142 //===----------------------------------------------------------------------===//
143 
144 typedef llvm::ImmutableMap<BindingKey, SVal>    ClusterBindings;
145 typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef;
146 typedef std::pair<BindingKey, SVal> BindingPair;
147 
148 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings>
149         RegionBindings;
150 
151 namespace {
152 class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
153                                  ClusterBindings> {
154  ClusterBindings::Factory &CBFactory;
155 public:
156   typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>
157           ParentTy;
158 
159   RegionBindingsRef(ClusterBindings::Factory &CBFactory,
160                     const RegionBindings::TreeTy *T,
161                     RegionBindings::TreeTy::Factory *F)
162     : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F),
163       CBFactory(CBFactory) {}
164 
165   RegionBindingsRef(const ParentTy &P, ClusterBindings::Factory &CBFactory)
166     : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P),
167       CBFactory(CBFactory) {}
168 
169   RegionBindingsRef add(key_type_ref K, data_type_ref D) const {
170     return RegionBindingsRef(static_cast<const ParentTy*>(this)->add(K, D),
171                              CBFactory);
172   }
173 
174   RegionBindingsRef remove(key_type_ref K) const {
175     return RegionBindingsRef(static_cast<const ParentTy*>(this)->remove(K),
176                              CBFactory);
177   }
178 
179   RegionBindingsRef addBinding(BindingKey K, SVal V) const;
180 
181   RegionBindingsRef addBinding(const MemRegion *R,
182                                BindingKey::Kind k, SVal V) const;
183 
184   RegionBindingsRef &operator=(const RegionBindingsRef &X) {
185     *static_cast<ParentTy*>(this) = X;
186     return *this;
187   }
188 
189   const SVal *lookup(BindingKey K) const;
190   const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const;
191   const ClusterBindings *lookup(const MemRegion *R) const {
192     return static_cast<const ParentTy*>(this)->lookup(R);
193   }
194 
195   RegionBindingsRef removeBinding(BindingKey K);
196 
197   RegionBindingsRef removeBinding(const MemRegion *R,
198                                   BindingKey::Kind k);
199 
200   RegionBindingsRef removeBinding(const MemRegion *R) {
201     return removeBinding(R, BindingKey::Direct).
202            removeBinding(R, BindingKey::Default);
203   }
204 
205   Optional<SVal> getDirectBinding(const MemRegion *R) const;
206 
207   /// getDefaultBinding - Returns an SVal* representing an optional default
208   ///  binding associated with a region and its subregions.
209   Optional<SVal> getDefaultBinding(const MemRegion *R) const;
210 
211   /// Return the internal tree as a Store.
212   Store asStore() const {
213     return asImmutableMap().getRootWithoutRetain();
214   }
215 
216   void dump(raw_ostream &OS, const char *nl) const {
217    for (iterator I = begin(), E = end(); I != E; ++I) {
218      const ClusterBindings &Cluster = I.getData();
219      for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
220           CI != CE; ++CI) {
221        OS << ' ' << CI.getKey() << " : " << CI.getData() << nl;
222      }
223      OS << nl;
224    }
225   }
226 
227   LLVM_ATTRIBUTE_USED void dump() const {
228     dump(llvm::errs(), "\n");
229   }
230 };
231 } // end anonymous namespace
232 
233 typedef const RegionBindingsRef& RegionBindingsConstRef;
234 
235 Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
236   return Optional<SVal>::create(lookup(R, BindingKey::Direct));
237 }
238 
239 Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
240   if (R->isBoundable())
241     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
242       if (TR->getValueType()->isUnionType())
243         return UnknownVal();
244 
245   return Optional<SVal>::create(lookup(R, BindingKey::Default));
246 }
247 
248 RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
249   const MemRegion *Base = K.getBaseRegion();
250 
251   const ClusterBindings *ExistingCluster = lookup(Base);
252   ClusterBindings Cluster = (ExistingCluster ? *ExistingCluster
253                              : CBFactory.getEmptyMap());
254 
255   ClusterBindings NewCluster = CBFactory.add(Cluster, K, V);
256   return add(Base, NewCluster);
257 }
258 
259 
260 RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
261                                                 BindingKey::Kind k,
262                                                 SVal V) const {
263   return addBinding(BindingKey::Make(R, k), V);
264 }
265 
266 const SVal *RegionBindingsRef::lookup(BindingKey K) const {
267   const ClusterBindings *Cluster = lookup(K.getBaseRegion());
268   if (!Cluster)
269     return 0;
270   return Cluster->lookup(K);
271 }
272 
273 const SVal *RegionBindingsRef::lookup(const MemRegion *R,
274                                       BindingKey::Kind k) const {
275   return lookup(BindingKey::Make(R, k));
276 }
277 
278 RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
279   const MemRegion *Base = K.getBaseRegion();
280   const ClusterBindings *Cluster = lookup(Base);
281   if (!Cluster)
282     return *this;
283 
284   ClusterBindings NewCluster = CBFactory.remove(*Cluster, K);
285   if (NewCluster.isEmpty())
286     return remove(Base);
287   return add(Base, NewCluster);
288 }
289 
290 RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
291                                                 BindingKey::Kind k){
292   return removeBinding(BindingKey::Make(R, k));
293 }
294 
295 //===----------------------------------------------------------------------===//
296 // Fine-grained control of RegionStoreManager.
297 //===----------------------------------------------------------------------===//
298 
299 namespace {
300 struct minimal_features_tag {};
301 struct maximal_features_tag {};
302 
303 class RegionStoreFeatures {
304   bool SupportsFields;
305 public:
306   RegionStoreFeatures(minimal_features_tag) :
307     SupportsFields(false) {}
308 
309   RegionStoreFeatures(maximal_features_tag) :
310     SupportsFields(true) {}
311 
312   void enableFields(bool t) { SupportsFields = t; }
313 
314   bool supportsFields() const { return SupportsFields; }
315 };
316 }
317 
318 //===----------------------------------------------------------------------===//
319 // Main RegionStore logic.
320 //===----------------------------------------------------------------------===//
321 
322 namespace {
323 class invalidateRegionsWorker;
324 
325 class RegionStoreManager : public StoreManager {
326 public:
327   const RegionStoreFeatures Features;
328 
329   RegionBindings::Factory RBFactory;
330   mutable ClusterBindings::Factory CBFactory;
331 
332   typedef std::vector<SVal> SValListTy;
333 private:
334   typedef llvm::DenseMap<const LazyCompoundValData *,
335                          SValListTy> LazyBindingsMapTy;
336   LazyBindingsMapTy LazyBindingsMap;
337 
338   /// The largest number of fields a struct can have and still be
339   /// considered "small".
340   ///
341   /// This is currently used to decide whether or not it is worth "forcing" a
342   /// LazyCompoundVal on bind.
343   ///
344   /// This is controlled by 'region-store-small-struct-limit' option.
345   /// To disable all small-struct-dependent behavior, set the option to "0".
346   unsigned SmallStructLimit;
347 
348   /// \brief A helper used to populate the work list with the given set of
349   /// regions.
350   void populateWorkList(invalidateRegionsWorker &W,
351                         ArrayRef<SVal> Values,
352                         bool IsArrayOfConstRegions,
353                         InvalidatedRegions *TopLevelRegions);
354 
355 public:
356   RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
357     : StoreManager(mgr), Features(f),
358       RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()),
359       SmallStructLimit(0) {
360     if (SubEngine *Eng = StateMgr.getOwningEngine()) {
361       AnalyzerOptions &Options = Eng->getAnalysisManager().options;
362       SmallStructLimit =
363         Options.getOptionAsInteger("region-store-small-struct-limit", 2);
364     }
365   }
366 
367 
368   /// setImplicitDefaultValue - Set the default binding for the provided
369   ///  MemRegion to the value implicitly defined for compound literals when
370   ///  the value is not specified.
371   RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B,
372                                             const MemRegion *R, QualType T);
373 
374   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
375   ///  type.  'Array' represents the lvalue of the array being decayed
376   ///  to a pointer, and the returned SVal represents the decayed
377   ///  version of that lvalue (i.e., a pointer to the first element of
378   ///  the array).  This is called by ExprEngine when evaluating
379   ///  casts from arrays to pointers.
380   SVal ArrayToPointer(Loc Array);
381 
382   StoreRef getInitialStore(const LocationContext *InitLoc) {
383     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
384   }
385 
386   //===-------------------------------------------------------------------===//
387   // Binding values to regions.
388   //===-------------------------------------------------------------------===//
389   RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
390                                            const Expr *Ex,
391                                            unsigned Count,
392                                            const LocationContext *LCtx,
393                                            RegionBindingsRef B,
394                                            InvalidatedRegions *Invalidated);
395 
396   StoreRef invalidateRegions(Store store,
397                              ArrayRef<SVal> Values,
398                              ArrayRef<SVal> ConstValues,
399                              const Expr *E, unsigned Count,
400                              const LocationContext *LCtx,
401                              const CallEvent *Call,
402                              InvalidatedSymbols &IS,
403                              InvalidatedSymbols &ConstIS,
404                              InvalidatedRegions *Invalidated,
405                              InvalidatedRegions *InvalidatedTopLevel,
406                              InvalidatedRegions *InvalidatedTopLevelConst);
407 
408   bool scanReachableSymbols(Store S, const MemRegion *R,
409                             ScanReachableSymbols &Callbacks);
410 
411   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
412                                             const SubRegion *R);
413 
414 public: // Part of public interface to class.
415 
416   virtual StoreRef Bind(Store store, Loc LV, SVal V) {
417     return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this);
418   }
419 
420   RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V);
421 
422   // BindDefault is only used to initialize a region with a default value.
423   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
424     RegionBindingsRef B = getRegionBindings(store);
425     assert(!B.lookup(R, BindingKey::Default));
426     assert(!B.lookup(R, BindingKey::Direct));
427     return StoreRef(B.addBinding(R, BindingKey::Default, V)
428                      .asImmutableMap()
429                      .getRootWithoutRetain(), *this);
430   }
431 
432   /// \brief Create a new store that binds a value to a compound literal.
433   ///
434   /// \param ST The original store whose bindings are the basis for the new
435   ///        store.
436   ///
437   /// \param CL The compound literal to bind (the binding key).
438   ///
439   /// \param LC The LocationContext for the binding.
440   ///
441   /// \param V The value to bind to the compound literal.
442   StoreRef bindCompoundLiteral(Store ST,
443                                const CompoundLiteralExpr *CL,
444                                const LocationContext *LC, SVal V);
445 
446   /// Attempt to extract the fields of \p LCV and bind them to the struct region
447   /// \p R.
448   ///
449   /// This path is used when it seems advantageous to "force" loading the values
450   /// within a LazyCompoundVal to bind memberwise to the struct region, rather
451   /// than using a Default binding at the base of the entire region. This is a
452   /// heuristic attempting to avoid building long chains of LazyCompoundVals.
453   ///
454   /// \returns The updated store bindings, or \c None if binding non-lazily
455   ///          would be too expensive.
456   Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B,
457                                                  const TypedValueRegion *R,
458                                                  const RecordDecl *RD,
459                                                  nonloc::LazyCompoundVal LCV);
460 
461   /// BindStruct - Bind a compound value to a structure.
462   RegionBindingsRef bindStruct(RegionBindingsConstRef B,
463                                const TypedValueRegion* R, SVal V);
464 
465   /// BindVector - Bind a compound value to a vector.
466   RegionBindingsRef bindVector(RegionBindingsConstRef B,
467                                const TypedValueRegion* R, SVal V);
468 
469   RegionBindingsRef bindArray(RegionBindingsConstRef B,
470                               const TypedValueRegion* R,
471                               SVal V);
472 
473   /// Clears out all bindings in the given region and assigns a new value
474   /// as a Default binding.
475   RegionBindingsRef bindAggregate(RegionBindingsConstRef B,
476                                   const TypedRegion *R,
477                                   SVal DefaultVal);
478 
479   /// \brief Create a new store with the specified binding removed.
480   /// \param ST the original store, that is the basis for the new store.
481   /// \param L the location whose binding should be removed.
482   virtual StoreRef killBinding(Store ST, Loc L);
483 
484   void incrementReferenceCount(Store store) {
485     getRegionBindings(store).manualRetain();
486   }
487 
488   /// If the StoreManager supports it, decrement the reference count of
489   /// the specified Store object.  If the reference count hits 0, the memory
490   /// associated with the object is recycled.
491   void decrementReferenceCount(Store store) {
492     getRegionBindings(store).manualRelease();
493   }
494 
495   bool includedInBindings(Store store, const MemRegion *region) const;
496 
497   /// \brief Return the value bound to specified location in a given state.
498   ///
499   /// The high level logic for this method is this:
500   /// getBinding (L)
501   ///   if L has binding
502   ///     return L's binding
503   ///   else if L is in killset
504   ///     return unknown
505   ///   else
506   ///     if L is on stack or heap
507   ///       return undefined
508   ///     else
509   ///       return symbolic
510   virtual SVal getBinding(Store S, Loc L, QualType T) {
511     return getBinding(getRegionBindings(S), L, T);
512   }
513 
514   SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
515 
516   SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
517 
518   SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
519 
520   SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
521 
522   SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
523 
524   SVal getBindingForLazySymbol(const TypedValueRegion *R);
525 
526   SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
527                                          const TypedValueRegion *R,
528                                          QualType Ty);
529 
530   SVal getLazyBinding(const SubRegion *LazyBindingRegion,
531                       RegionBindingsRef LazyBinding);
532 
533   /// Get bindings for the values in a struct and return a CompoundVal, used
534   /// when doing struct copy:
535   /// struct s x, y;
536   /// x = y;
537   /// y's value is retrieved by this method.
538   SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
539   SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
540   NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
541 
542   /// Used to lazily generate derived symbols for bindings that are defined
543   /// implicitly by default bindings in a super region.
544   ///
545   /// Note that callers may need to specially handle LazyCompoundVals, which
546   /// are returned as is in case the caller needs to treat them differently.
547   Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
548                                                   const MemRegion *superR,
549                                                   const TypedValueRegion *R,
550                                                   QualType Ty);
551 
552   /// Get the state and region whose binding this region \p R corresponds to.
553   ///
554   /// If there is no lazy binding for \p R, the returned value will have a null
555   /// \c second. Note that a null pointer can represents a valid Store.
556   std::pair<Store, const SubRegion *>
557   findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
558                   const SubRegion *originalRegion);
559 
560   /// Returns the cached set of interesting SVals contained within a lazy
561   /// binding.
562   ///
563   /// The precise value of "interesting" is determined for the purposes of
564   /// RegionStore's internal analysis. It must always contain all regions and
565   /// symbols, but may omit constants and other kinds of SVal.
566   const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
567 
568   //===------------------------------------------------------------------===//
569   // State pruning.
570   //===------------------------------------------------------------------===//
571 
572   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
573   ///  It returns a new Store with these values removed.
574   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
575                               SymbolReaper& SymReaper);
576 
577   //===------------------------------------------------------------------===//
578   // Region "extents".
579   //===------------------------------------------------------------------===//
580 
581   // FIXME: This method will soon be eliminated; see the note in Store.h.
582   DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
583                                          const MemRegion* R, QualType EleTy);
584 
585   //===------------------------------------------------------------------===//
586   // Utility methods.
587   //===------------------------------------------------------------------===//
588 
589   RegionBindingsRef getRegionBindings(Store store) const {
590     return RegionBindingsRef(CBFactory,
591                              static_cast<const RegionBindings::TreeTy*>(store),
592                              RBFactory.getTreeFactory());
593   }
594 
595   void print(Store store, raw_ostream &Out, const char* nl,
596              const char *sep);
597 
598   void iterBindings(Store store, BindingsHandler& f) {
599     RegionBindingsRef B = getRegionBindings(store);
600     for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
601       const ClusterBindings &Cluster = I.getData();
602       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
603            CI != CE; ++CI) {
604         const BindingKey &K = CI.getKey();
605         if (!K.isDirect())
606           continue;
607         if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
608           // FIXME: Possibly incorporate the offset?
609           if (!f.HandleBinding(*this, store, R, CI.getData()))
610             return;
611         }
612       }
613     }
614   }
615 };
616 
617 } // end anonymous namespace
618 
619 //===----------------------------------------------------------------------===//
620 // RegionStore creation.
621 //===----------------------------------------------------------------------===//
622 
623 StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
624   RegionStoreFeatures F = maximal_features_tag();
625   return new RegionStoreManager(StMgr, F);
626 }
627 
628 StoreManager *
629 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
630   RegionStoreFeatures F = minimal_features_tag();
631   F.enableFields(true);
632   return new RegionStoreManager(StMgr, F);
633 }
634 
635 
636 //===----------------------------------------------------------------------===//
637 // Region Cluster analysis.
638 //===----------------------------------------------------------------------===//
639 
640 namespace {
641 /// Used to determine which global regions are automatically included in the
642 /// initial worklist of a ClusterAnalysis.
643 enum GlobalsFilterKind {
644   /// Don't include any global regions.
645   GFK_None,
646   /// Only include system globals.
647   GFK_SystemOnly,
648   /// Include all global regions.
649   GFK_All
650 };
651 
652 template <typename DERIVED>
653 class ClusterAnalysis  {
654 protected:
655   typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
656   typedef llvm::PointerIntPair<const MemRegion *, 1, bool> WorkListElement;
657   typedef SmallVector<WorkListElement, 10> WorkList;
658 
659   llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
660 
661   WorkList WL;
662 
663   RegionStoreManager &RM;
664   ASTContext &Ctx;
665   SValBuilder &svalBuilder;
666 
667   RegionBindingsRef B;
668 
669 private:
670   GlobalsFilterKind GlobalsFilter;
671 
672 protected:
673   const ClusterBindings *getCluster(const MemRegion *R) {
674     return B.lookup(R);
675   }
676 
677   /// Returns true if the memory space of the given region is one of the global
678   /// regions specially included at the start of analysis.
679   bool isInitiallyIncludedGlobalRegion(const MemRegion *R) {
680     switch (GlobalsFilter) {
681     case GFK_None:
682       return false;
683     case GFK_SystemOnly:
684       return isa<GlobalSystemSpaceRegion>(R->getMemorySpace());
685     case GFK_All:
686       return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace());
687     }
688 
689     llvm_unreachable("unknown globals filter");
690   }
691 
692 public:
693   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
694                   RegionBindingsRef b, GlobalsFilterKind GFK)
695     : RM(rm), Ctx(StateMgr.getContext()),
696       svalBuilder(StateMgr.getSValBuilder()),
697       B(b), GlobalsFilter(GFK) {}
698 
699   RegionBindingsRef getRegionBindings() const { return B; }
700 
701   bool isVisited(const MemRegion *R) {
702     return Visited.count(getCluster(R));
703   }
704 
705   void GenerateClusters() {
706     // Scan the entire set of bindings and record the region clusters.
707     for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
708          RI != RE; ++RI){
709       const MemRegion *Base = RI.getKey();
710 
711       const ClusterBindings &Cluster = RI.getData();
712       assert(!Cluster.isEmpty() && "Empty clusters should be removed");
713       static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
714 
715       // If this is an interesting global region, add it the work list up front.
716       if (isInitiallyIncludedGlobalRegion(Base))
717         AddToWorkList(WorkListElement(Base), &Cluster);
718     }
719   }
720 
721   bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
722     if (C && !Visited.insert(C))
723       return false;
724     WL.push_back(E);
725     return true;
726   }
727 
728   bool AddToWorkList(const MemRegion *R, bool Flag = false) {
729     const MemRegion *BaseR = R->getBaseRegion();
730     return AddToWorkList(WorkListElement(BaseR, Flag), getCluster(BaseR));
731   }
732 
733   void RunWorkList() {
734     while (!WL.empty()) {
735       WorkListElement E = WL.pop_back_val();
736       const MemRegion *BaseR = E.getPointer();
737 
738       static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR),
739                                                 E.getInt());
740     }
741   }
742 
743   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
744   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
745 
746   void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
747                     bool Flag) {
748     static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
749   }
750 };
751 }
752 
753 //===----------------------------------------------------------------------===//
754 // Binding invalidation.
755 //===----------------------------------------------------------------------===//
756 
757 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
758                                               ScanReachableSymbols &Callbacks) {
759   assert(R == R->getBaseRegion() && "Should only be called for base regions");
760   RegionBindingsRef B = getRegionBindings(S);
761   const ClusterBindings *Cluster = B.lookup(R);
762 
763   if (!Cluster)
764     return true;
765 
766   for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
767        RI != RE; ++RI) {
768     if (!Callbacks.scan(RI.getData()))
769       return false;
770   }
771 
772   return true;
773 }
774 
775 static inline bool isUnionField(const FieldRegion *FR) {
776   return FR->getDecl()->getParent()->isUnion();
777 }
778 
779 typedef SmallVector<const FieldDecl *, 8> FieldVector;
780 
781 void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
782   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
783 
784   const MemRegion *Base = K.getConcreteOffsetRegion();
785   const MemRegion *R = K.getRegion();
786 
787   while (R != Base) {
788     if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
789       if (!isUnionField(FR))
790         Fields.push_back(FR->getDecl());
791 
792     R = cast<SubRegion>(R)->getSuperRegion();
793   }
794 }
795 
796 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
797   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
798 
799   if (Fields.empty())
800     return true;
801 
802   FieldVector FieldsInBindingKey;
803   getSymbolicOffsetFields(K, FieldsInBindingKey);
804 
805   ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
806   if (Delta >= 0)
807     return std::equal(FieldsInBindingKey.begin() + Delta,
808                       FieldsInBindingKey.end(),
809                       Fields.begin());
810   else
811     return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
812                       Fields.begin() - Delta);
813 }
814 
815 /// Collects all bindings in \p Cluster that may refer to bindings within
816 /// \p Top.
817 ///
818 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose
819 /// \c second is the value (an SVal).
820 ///
821 /// The \p IncludeAllDefaultBindings parameter specifies whether to include
822 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
823 /// an aggregate within a larger aggregate with a default binding.
824 static void
825 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
826                          SValBuilder &SVB, const ClusterBindings &Cluster,
827                          const SubRegion *Top, BindingKey TopKey,
828                          bool IncludeAllDefaultBindings) {
829   FieldVector FieldsInSymbolicSubregions;
830   if (TopKey.hasSymbolicOffset()) {
831     getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
832     Top = cast<SubRegion>(TopKey.getConcreteOffsetRegion());
833     TopKey = BindingKey::Make(Top, BindingKey::Default);
834   }
835 
836   // Find the length (in bits) of the region being invalidated.
837   uint64_t Length = UINT64_MAX;
838   SVal Extent = Top->getExtent(SVB);
839   if (Optional<nonloc::ConcreteInt> ExtentCI =
840           Extent.getAs<nonloc::ConcreteInt>()) {
841     const llvm::APSInt &ExtentInt = ExtentCI->getValue();
842     assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
843     // Extents are in bytes but region offsets are in bits. Be careful!
844     Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
845   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) {
846     if (FR->getDecl()->isBitField())
847       Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
848   }
849 
850   for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
851        I != E; ++I) {
852     BindingKey NextKey = I.getKey();
853     if (NextKey.getRegion() == TopKey.getRegion()) {
854       // FIXME: This doesn't catch the case where we're really invalidating a
855       // region with a symbolic offset. Example:
856       //      R: points[i].y
857       //   Next: points[0].x
858 
859       if (NextKey.getOffset() > TopKey.getOffset() &&
860           NextKey.getOffset() - TopKey.getOffset() < Length) {
861         // Case 1: The next binding is inside the region we're invalidating.
862         // Include it.
863         Bindings.push_back(*I);
864 
865       } else if (NextKey.getOffset() == TopKey.getOffset()) {
866         // Case 2: The next binding is at the same offset as the region we're
867         // invalidating. In this case, we need to leave default bindings alone,
868         // since they may be providing a default value for a regions beyond what
869         // we're invalidating.
870         // FIXME: This is probably incorrect; consider invalidating an outer
871         // struct whose first field is bound to a LazyCompoundVal.
872         if (IncludeAllDefaultBindings || NextKey.isDirect())
873           Bindings.push_back(*I);
874       }
875 
876     } else if (NextKey.hasSymbolicOffset()) {
877       const MemRegion *Base = NextKey.getConcreteOffsetRegion();
878       if (Top->isSubRegionOf(Base)) {
879         // Case 3: The next key is symbolic and we just changed something within
880         // its concrete region. We don't know if the binding is still valid, so
881         // we'll be conservative and include it.
882         if (IncludeAllDefaultBindings || NextKey.isDirect())
883           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
884             Bindings.push_back(*I);
885       } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
886         // Case 4: The next key is symbolic, but we changed a known
887         // super-region. In this case the binding is certainly included.
888         if (Top == Base || BaseSR->isSubRegionOf(Top))
889           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
890             Bindings.push_back(*I);
891       }
892     }
893   }
894 }
895 
896 static void
897 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
898                          SValBuilder &SVB, const ClusterBindings &Cluster,
899                          const SubRegion *Top, bool IncludeAllDefaultBindings) {
900   collectSubRegionBindings(Bindings, SVB, Cluster, Top,
901                            BindingKey::Make(Top, BindingKey::Default),
902                            IncludeAllDefaultBindings);
903 }
904 
905 RegionBindingsRef
906 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
907                                             const SubRegion *Top) {
908   BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
909   const MemRegion *ClusterHead = TopKey.getBaseRegion();
910 
911   if (Top == ClusterHead) {
912     // We can remove an entire cluster's bindings all in one go.
913     return B.remove(Top);
914   }
915 
916   const ClusterBindings *Cluster = B.lookup(ClusterHead);
917   if (!Cluster) {
918     // If we're invalidating a region with a symbolic offset, we need to make
919     // sure we don't treat the base region as uninitialized anymore.
920     if (TopKey.hasSymbolicOffset()) {
921       const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
922       return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
923     }
924     return B;
925   }
926 
927   SmallVector<BindingPair, 32> Bindings;
928   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
929                            /*IncludeAllDefaultBindings=*/false);
930 
931   ClusterBindingsRef Result(*Cluster, CBFactory);
932   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
933                                                     E = Bindings.end();
934        I != E; ++I)
935     Result = Result.remove(I->first);
936 
937   // If we're invalidating a region with a symbolic offset, we need to make sure
938   // we don't treat the base region as uninitialized anymore.
939   // FIXME: This isn't very precise; see the example in
940   // collectSubRegionBindings.
941   if (TopKey.hasSymbolicOffset()) {
942     const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
943     Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
944                         UnknownVal());
945   }
946 
947   if (Result.isEmpty())
948     return B.remove(ClusterHead);
949   return B.add(ClusterHead, Result.asImmutableMap());
950 }
951 
952 namespace {
953 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
954 {
955   const Expr *Ex;
956   unsigned Count;
957   const LocationContext *LCtx;
958   InvalidatedSymbols &IS;
959   InvalidatedSymbols &ConstIS;
960   StoreManager::InvalidatedRegions *Regions;
961 public:
962   invalidateRegionsWorker(RegionStoreManager &rm,
963                           ProgramStateManager &stateMgr,
964                           RegionBindingsRef b,
965                           const Expr *ex, unsigned count,
966                           const LocationContext *lctx,
967                           InvalidatedSymbols &is,
968                           InvalidatedSymbols &inConstIS,
969                           StoreManager::InvalidatedRegions *r,
970                           GlobalsFilterKind GFK)
971     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, GFK),
972       Ex(ex), Count(count), LCtx(lctx), IS(is), ConstIS(inConstIS), Regions(r){}
973 
974   /// \param IsConst Specifies if the region we are invalidating is constant.
975   /// If it is, we invalidate all subregions, but not the base region itself.
976   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C,
977                     bool IsConst);
978   void VisitBinding(SVal V);
979 };
980 }
981 
982 void invalidateRegionsWorker::VisitBinding(SVal V) {
983   // A symbol?  Mark it touched by the invalidation.
984   if (SymbolRef Sym = V.getAsSymbol())
985     IS.insert(Sym);
986 
987   if (const MemRegion *R = V.getAsRegion()) {
988     AddToWorkList(R);
989     return;
990   }
991 
992   // Is it a LazyCompoundVal?  All references get invalidated as well.
993   if (Optional<nonloc::LazyCompoundVal> LCS =
994           V.getAs<nonloc::LazyCompoundVal>()) {
995 
996     const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
997 
998     for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
999                                                         E = Vals.end();
1000          I != E; ++I)
1001       VisitBinding(*I);
1002 
1003     return;
1004   }
1005 }
1006 
1007 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
1008                                            const ClusterBindings *C,
1009                                            bool IsConst) {
1010   if (C) {
1011     for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
1012       VisitBinding(I.getData());
1013 
1014     if (!IsConst)
1015       B = B.remove(baseR);
1016   }
1017 
1018   // BlockDataRegion?  If so, invalidate captured variables that are passed
1019   // by reference.
1020   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
1021     for (BlockDataRegion::referenced_vars_iterator
1022          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
1023          BI != BE; ++BI) {
1024       const VarRegion *VR = BI.getCapturedRegion();
1025       const VarDecl *VD = VR->getDecl();
1026       if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
1027         AddToWorkList(VR);
1028       }
1029       else if (Loc::isLocType(VR->getValueType())) {
1030         // Map the current bindings to a Store to retrieve the value
1031         // of the binding.  If that binding itself is a region, we should
1032         // invalidate that region.  This is because a block may capture
1033         // a pointer value, but the thing pointed by that pointer may
1034         // get invalidated.
1035         SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
1036         if (Optional<Loc> L = V.getAs<Loc>()) {
1037           if (const MemRegion *LR = L->getAsRegion())
1038             AddToWorkList(LR);
1039         }
1040       }
1041     }
1042     return;
1043   }
1044 
1045   // Symbolic region?
1046   SymbolRef RegionSym = 0;
1047   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
1048     RegionSym = SR->getSymbol();
1049 
1050   if (IsConst) {
1051     // Mark that symbol touched by the invalidation.
1052     ConstIS.insert(RegionSym);
1053     return;
1054   }
1055 
1056   // Mark that symbol touched by the invalidation.
1057   IS.insert(RegionSym);
1058 
1059   // Otherwise, we have a normal data region. Record that we touched the region.
1060   if (Regions)
1061     Regions->push_back(baseR);
1062 
1063   if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
1064     // Invalidate the region by setting its default value to
1065     // conjured symbol. The type of the symbol is irrelavant.
1066     DefinedOrUnknownSVal V =
1067       svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
1068     B = B.addBinding(baseR, BindingKey::Default, V);
1069     return;
1070   }
1071 
1072   if (!baseR->isBoundable())
1073     return;
1074 
1075   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
1076   QualType T = TR->getValueType();
1077 
1078   if (isInitiallyIncludedGlobalRegion(baseR)) {
1079     // If the region is a global and we are invalidating all globals,
1080     // erasing the entry is good enough.  This causes all globals to be lazily
1081     // symbolicated from the same base symbol.
1082     return;
1083   }
1084 
1085   if (T->isStructureOrClassType()) {
1086     // Invalidate the region by setting its default value to
1087     // conjured symbol. The type of the symbol is irrelavant.
1088     DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1089                                                           Ctx.IntTy, Count);
1090     B = B.addBinding(baseR, BindingKey::Default, V);
1091     return;
1092   }
1093 
1094   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
1095       // Set the default value of the array to conjured symbol.
1096     DefinedOrUnknownSVal V =
1097     svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1098                                      AT->getElementType(), Count);
1099     B = B.addBinding(baseR, BindingKey::Default, V);
1100     return;
1101   }
1102 
1103   DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1104                                                         T,Count);
1105   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
1106   B = B.addBinding(baseR, BindingKey::Direct, V);
1107 }
1108 
1109 RegionBindingsRef
1110 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
1111                                            const Expr *Ex,
1112                                            unsigned Count,
1113                                            const LocationContext *LCtx,
1114                                            RegionBindingsRef B,
1115                                            InvalidatedRegions *Invalidated) {
1116   // Bind the globals memory space to a new symbol that we will use to derive
1117   // the bindings for all globals.
1118   const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
1119   SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx,
1120                                         /* type does not matter */ Ctx.IntTy,
1121                                         Count);
1122 
1123   B = B.removeBinding(GS)
1124        .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
1125 
1126   // Even if there are no bindings in the global scope, we still need to
1127   // record that we touched it.
1128   if (Invalidated)
1129     Invalidated->push_back(GS);
1130 
1131   return B;
1132 }
1133 
1134 void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W,
1135                                           ArrayRef<SVal> Values,
1136                                           bool IsArrayOfConstRegions,
1137                                           InvalidatedRegions *TopLevelRegions) {
1138   for (ArrayRef<SVal>::iterator I = Values.begin(),
1139                                 E = Values.end(); I != E; ++I) {
1140     SVal V = *I;
1141     if (Optional<nonloc::LazyCompoundVal> LCS =
1142         V.getAs<nonloc::LazyCompoundVal>()) {
1143 
1144       const SValListTy &Vals = getInterestingValues(*LCS);
1145 
1146       for (SValListTy::const_iterator I = Vals.begin(),
1147                                       E = Vals.end(); I != E; ++I) {
1148         // Note: the last argument is false here because these are
1149         // non-top-level regions.
1150         if (const MemRegion *R = (*I).getAsRegion())
1151           W.AddToWorkList(R, /*IsConst=*/ false);
1152       }
1153       continue;
1154     }
1155 
1156     if (const MemRegion *R = V.getAsRegion()) {
1157       if (TopLevelRegions)
1158         TopLevelRegions->push_back(R);
1159       W.AddToWorkList(R, /*IsConst=*/ IsArrayOfConstRegions);
1160       continue;
1161     }
1162   }
1163 }
1164 
1165 StoreRef
1166 RegionStoreManager::invalidateRegions(Store store,
1167                                       ArrayRef<SVal> Values,
1168                                       ArrayRef<SVal> ConstValues,
1169                                       const Expr *Ex, unsigned Count,
1170                                       const LocationContext *LCtx,
1171                                       const CallEvent *Call,
1172                                       InvalidatedSymbols &IS,
1173                                       InvalidatedSymbols &ConstIS,
1174                                       InvalidatedRegions *TopLevelRegions,
1175                                       InvalidatedRegions *TopLevelConstRegions,
1176                                       InvalidatedRegions *Invalidated) {
1177   GlobalsFilterKind GlobalsFilter;
1178   if (Call) {
1179     if (Call->isInSystemHeader())
1180       GlobalsFilter = GFK_SystemOnly;
1181     else
1182       GlobalsFilter = GFK_All;
1183   } else {
1184     GlobalsFilter = GFK_None;
1185   }
1186 
1187   RegionBindingsRef B = getRegionBindings(store);
1188   invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ConstIS,
1189                             Invalidated, GlobalsFilter);
1190 
1191   // Scan the bindings and generate the clusters.
1192   W.GenerateClusters();
1193 
1194   // Add the regions to the worklist.
1195   populateWorkList(W, Values, /*IsArrayOfConstRegions*/ false,
1196                    TopLevelRegions);
1197   populateWorkList(W, ConstValues, /*IsArrayOfConstRegions*/ true,
1198                    TopLevelConstRegions);
1199 
1200   W.RunWorkList();
1201 
1202   // Return the new bindings.
1203   B = W.getRegionBindings();
1204 
1205   // For calls, determine which global regions should be invalidated and
1206   // invalidate them. (Note that function-static and immutable globals are never
1207   // invalidated by this.)
1208   // TODO: This could possibly be more precise with modules.
1209   switch (GlobalsFilter) {
1210   case GFK_All:
1211     B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
1212                                Ex, Count, LCtx, B, Invalidated);
1213     // FALLTHROUGH
1214   case GFK_SystemOnly:
1215     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
1216                                Ex, Count, LCtx, B, Invalidated);
1217     // FALLTHROUGH
1218   case GFK_None:
1219     break;
1220   }
1221 
1222   return StoreRef(B.asStore(), *this);
1223 }
1224 
1225 //===----------------------------------------------------------------------===//
1226 // Extents for regions.
1227 //===----------------------------------------------------------------------===//
1228 
1229 DefinedOrUnknownSVal
1230 RegionStoreManager::getSizeInElements(ProgramStateRef state,
1231                                       const MemRegion *R,
1232                                       QualType EleTy) {
1233   SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
1234   const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
1235   if (!SizeInt)
1236     return UnknownVal();
1237 
1238   CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
1239 
1240   if (Ctx.getAsVariableArrayType(EleTy)) {
1241     // FIXME: We need to track extra state to properly record the size
1242     // of VLAs.  Returning UnknownVal here, however, is a stop-gap so that
1243     // we don't have a divide-by-zero below.
1244     return UnknownVal();
1245   }
1246 
1247   CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
1248 
1249   // If a variable is reinterpreted as a type that doesn't fit into a larger
1250   // type evenly, round it down.
1251   // This is a signed value, since it's used in arithmetic with signed indices.
1252   return svalBuilder.makeIntVal(RegionSize / EleSize, false);
1253 }
1254 
1255 //===----------------------------------------------------------------------===//
1256 // Location and region casting.
1257 //===----------------------------------------------------------------------===//
1258 
1259 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
1260 ///  type.  'Array' represents the lvalue of the array being decayed
1261 ///  to a pointer, and the returned SVal represents the decayed
1262 ///  version of that lvalue (i.e., a pointer to the first element of
1263 ///  the array).  This is called by ExprEngine when evaluating casts
1264 ///  from arrays to pointers.
1265 SVal RegionStoreManager::ArrayToPointer(Loc Array) {
1266   if (!Array.getAs<loc::MemRegionVal>())
1267     return UnknownVal();
1268 
1269   const MemRegion* R = Array.castAs<loc::MemRegionVal>().getRegion();
1270   const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
1271 
1272   if (!ArrayR)
1273     return UnknownVal();
1274 
1275   // Strip off typedefs from the ArrayRegion's ValueType.
1276   QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
1277   const ArrayType *AT = cast<ArrayType>(T);
1278   T = AT->getElementType();
1279 
1280   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
1281   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
1282 }
1283 
1284 //===----------------------------------------------------------------------===//
1285 // Loading values from regions.
1286 //===----------------------------------------------------------------------===//
1287 
1288 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
1289   assert(!L.getAs<UnknownVal>() && "location unknown");
1290   assert(!L.getAs<UndefinedVal>() && "location undefined");
1291 
1292   // For access to concrete addresses, return UnknownVal.  Checks
1293   // for null dereferences (and similar errors) are done by checkers, not
1294   // the Store.
1295   // FIXME: We can consider lazily symbolicating such memory, but we really
1296   // should defer this when we can reason easily about symbolicating arrays
1297   // of bytes.
1298   if (L.getAs<loc::ConcreteInt>()) {
1299     return UnknownVal();
1300   }
1301   if (!L.getAs<loc::MemRegionVal>()) {
1302     return UnknownVal();
1303   }
1304 
1305   const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
1306 
1307   if (isa<AllocaRegion>(MR) ||
1308       isa<SymbolicRegion>(MR) ||
1309       isa<CodeTextRegion>(MR)) {
1310     if (T.isNull()) {
1311       if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
1312         T = TR->getLocationType();
1313       else {
1314         const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
1315         T = SR->getSymbol()->getType();
1316       }
1317     }
1318     MR = GetElementZeroRegion(MR, T);
1319   }
1320 
1321   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1322   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
1323   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1324   QualType RTy = R->getValueType();
1325 
1326   // FIXME: we do not yet model the parts of a complex type, so treat the
1327   // whole thing as "unknown".
1328   if (RTy->isAnyComplexType())
1329     return UnknownVal();
1330 
1331   // FIXME: We should eventually handle funny addressing.  e.g.:
1332   //
1333   //   int x = ...;
1334   //   int *p = &x;
1335   //   char *q = (char*) p;
1336   //   char c = *q;  // returns the first byte of 'x'.
1337   //
1338   // Such funny addressing will occur due to layering of regions.
1339   if (RTy->isStructureOrClassType())
1340     return getBindingForStruct(B, R);
1341 
1342   // FIXME: Handle unions.
1343   if (RTy->isUnionType())
1344     return UnknownVal();
1345 
1346   if (RTy->isArrayType()) {
1347     if (RTy->isConstantArrayType())
1348       return getBindingForArray(B, R);
1349     else
1350       return UnknownVal();
1351   }
1352 
1353   // FIXME: handle Vector types.
1354   if (RTy->isVectorType())
1355     return UnknownVal();
1356 
1357   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1358     return CastRetrievedVal(getBindingForField(B, FR), FR, T, false);
1359 
1360   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1361     // FIXME: Here we actually perform an implicit conversion from the loaded
1362     // value to the element type.  Eventually we want to compose these values
1363     // more intelligently.  For example, an 'element' can encompass multiple
1364     // bound regions (e.g., several bound bytes), or could be a subset of
1365     // a larger value.
1366     return CastRetrievedVal(getBindingForElement(B, ER), ER, T, false);
1367   }
1368 
1369   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1370     // FIXME: Here we actually perform an implicit conversion from the loaded
1371     // value to the ivar type.  What we should model is stores to ivars
1372     // that blow past the extent of the ivar.  If the address of the ivar is
1373     // reinterpretted, it is possible we stored a different value that could
1374     // fit within the ivar.  Either we need to cast these when storing them
1375     // or reinterpret them lazily (as we do here).
1376     return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T, false);
1377   }
1378 
1379   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1380     // FIXME: Here we actually perform an implicit conversion from the loaded
1381     // value to the variable type.  What we should model is stores to variables
1382     // that blow past the extent of the variable.  If the address of the
1383     // variable is reinterpretted, it is possible we stored a different value
1384     // that could fit within the variable.  Either we need to cast these when
1385     // storing them or reinterpret them lazily (as we do here).
1386     return CastRetrievedVal(getBindingForVar(B, VR), VR, T, false);
1387   }
1388 
1389   const SVal *V = B.lookup(R, BindingKey::Direct);
1390 
1391   // Check if the region has a binding.
1392   if (V)
1393     return *V;
1394 
1395   // The location does not have a bound value.  This means that it has
1396   // the value it had upon its creation and/or entry to the analyzed
1397   // function/method.  These are either symbolic values or 'undefined'.
1398   if (R->hasStackNonParametersStorage()) {
1399     // All stack variables are considered to have undefined values
1400     // upon creation.  All heap allocated blocks are considered to
1401     // have undefined values as well unless they are explicitly bound
1402     // to specific values.
1403     return UndefinedVal();
1404   }
1405 
1406   // All other values are symbolic.
1407   return svalBuilder.getRegionValueSymbolVal(R);
1408 }
1409 
1410 static QualType getUnderlyingType(const SubRegion *R) {
1411   QualType RegionTy;
1412   if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
1413     RegionTy = TVR->getValueType();
1414 
1415   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1416     RegionTy = SR->getSymbol()->getType();
1417 
1418   return RegionTy;
1419 }
1420 
1421 /// Checks to see if store \p B has a lazy binding for region \p R.
1422 ///
1423 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1424 /// if there are additional bindings within \p R.
1425 ///
1426 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1427 /// for lazy bindings for super-regions of \p R.
1428 static Optional<nonloc::LazyCompoundVal>
1429 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B,
1430                        const SubRegion *R, bool AllowSubregionBindings) {
1431   Optional<SVal> V = B.getDefaultBinding(R);
1432   if (!V)
1433     return None;
1434 
1435   Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>();
1436   if (!LCV)
1437     return None;
1438 
1439   // If the LCV is for a subregion, the types might not match, and we shouldn't
1440   // reuse the binding.
1441   QualType RegionTy = getUnderlyingType(R);
1442   if (!RegionTy.isNull() &&
1443       !RegionTy->isVoidPointerType()) {
1444     QualType SourceRegionTy = LCV->getRegion()->getValueType();
1445     if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
1446       return None;
1447   }
1448 
1449   if (!AllowSubregionBindings) {
1450     // If there are any other bindings within this region, we shouldn't reuse
1451     // the top-level binding.
1452     SmallVector<BindingPair, 16> Bindings;
1453     collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
1454                              /*IncludeAllDefaultBindings=*/true);
1455     if (Bindings.size() > 1)
1456       return None;
1457   }
1458 
1459   return *LCV;
1460 }
1461 
1462 
1463 std::pair<Store, const SubRegion *>
1464 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
1465                                    const SubRegion *R,
1466                                    const SubRegion *originalRegion) {
1467   if (originalRegion != R) {
1468     if (Optional<nonloc::LazyCompoundVal> V =
1469           getExistingLazyBinding(svalBuilder, B, R, true))
1470       return std::make_pair(V->getStore(), V->getRegion());
1471   }
1472 
1473   typedef std::pair<Store, const SubRegion *> StoreRegionPair;
1474   StoreRegionPair Result = StoreRegionPair();
1475 
1476   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1477     Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
1478                              originalRegion);
1479 
1480     if (Result.second)
1481       Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
1482 
1483   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1484     Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
1485                                        originalRegion);
1486 
1487     if (Result.second)
1488       Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
1489 
1490   } else if (const CXXBaseObjectRegion *BaseReg =
1491                dyn_cast<CXXBaseObjectRegion>(R)) {
1492     // C++ base object region is another kind of region that we should blast
1493     // through to look for lazy compound value. It is like a field region.
1494     Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
1495                              originalRegion);
1496 
1497     if (Result.second)
1498       Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
1499                                                             Result.second);
1500   }
1501 
1502   return Result;
1503 }
1504 
1505 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
1506                                               const ElementRegion* R) {
1507   // We do not currently model bindings of the CompoundLiteralregion.
1508   if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
1509     return UnknownVal();
1510 
1511   // Check if the region has a binding.
1512   if (const Optional<SVal> &V = B.getDirectBinding(R))
1513     return *V;
1514 
1515   const MemRegion* superR = R->getSuperRegion();
1516 
1517   // Check if the region is an element region of a string literal.
1518   if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
1519     // FIXME: Handle loads from strings where the literal is treated as
1520     // an integer, e.g., *((unsigned int*)"hello")
1521     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1522     if (T != Ctx.getCanonicalType(R->getElementType()))
1523       return UnknownVal();
1524 
1525     const StringLiteral *Str = StrR->getStringLiteral();
1526     SVal Idx = R->getIndex();
1527     if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) {
1528       int64_t i = CI->getValue().getSExtValue();
1529       // Abort on string underrun.  This can be possible by arbitrary
1530       // clients of getBindingForElement().
1531       if (i < 0)
1532         return UndefinedVal();
1533       int64_t length = Str->getLength();
1534       // Technically, only i == length is guaranteed to be null.
1535       // However, such overflows should be caught before reaching this point;
1536       // the only time such an access would be made is if a string literal was
1537       // used to initialize a larger array.
1538       char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
1539       return svalBuilder.makeIntVal(c, T);
1540     }
1541   }
1542 
1543   // Check for loads from a code text region.  For such loads, just give up.
1544   if (isa<CodeTextRegion>(superR))
1545     return UnknownVal();
1546 
1547   // Handle the case where we are indexing into a larger scalar object.
1548   // For example, this handles:
1549   //   int x = ...
1550   //   char *y = &x;
1551   //   return *y;
1552   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1553   const RegionRawOffset &O = R->getAsArrayOffset();
1554 
1555   // If we cannot reason about the offset, return an unknown value.
1556   if (!O.getRegion())
1557     return UnknownVal();
1558 
1559   if (const TypedValueRegion *baseR =
1560         dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1561     QualType baseT = baseR->getValueType();
1562     if (baseT->isScalarType()) {
1563       QualType elemT = R->getElementType();
1564       if (elemT->isScalarType()) {
1565         if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1566           if (const Optional<SVal> &V = B.getDirectBinding(superR)) {
1567             if (SymbolRef parentSym = V->getAsSymbol())
1568               return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1569 
1570             if (V->isUnknownOrUndef())
1571               return *V;
1572             // Other cases: give up.  We are indexing into a larger object
1573             // that has some value, but we don't know how to handle that yet.
1574             return UnknownVal();
1575           }
1576         }
1577       }
1578     }
1579   }
1580   return getBindingForFieldOrElementCommon(B, R, R->getElementType());
1581 }
1582 
1583 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
1584                                             const FieldRegion* R) {
1585 
1586   // Check if the region has a binding.
1587   if (const Optional<SVal> &V = B.getDirectBinding(R))
1588     return *V;
1589 
1590   QualType Ty = R->getValueType();
1591   return getBindingForFieldOrElementCommon(B, R, Ty);
1592 }
1593 
1594 Optional<SVal>
1595 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
1596                                                      const MemRegion *superR,
1597                                                      const TypedValueRegion *R,
1598                                                      QualType Ty) {
1599 
1600   if (const Optional<SVal> &D = B.getDefaultBinding(superR)) {
1601     const SVal &val = D.getValue();
1602     if (SymbolRef parentSym = val.getAsSymbol())
1603       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1604 
1605     if (val.isZeroConstant())
1606       return svalBuilder.makeZeroVal(Ty);
1607 
1608     if (val.isUnknownOrUndef())
1609       return val;
1610 
1611     // Lazy bindings are usually handled through getExistingLazyBinding().
1612     // We should unify these two code paths at some point.
1613     if (val.getAs<nonloc::LazyCompoundVal>())
1614       return val;
1615 
1616     llvm_unreachable("Unknown default value");
1617   }
1618 
1619   return None;
1620 }
1621 
1622 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
1623                                         RegionBindingsRef LazyBinding) {
1624   SVal Result;
1625   if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
1626     Result = getBindingForElement(LazyBinding, ER);
1627   else
1628     Result = getBindingForField(LazyBinding,
1629                                 cast<FieldRegion>(LazyBindingRegion));
1630 
1631   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1632   // default value for /part/ of an aggregate from a default value for the
1633   // /entire/ aggregate. The most common case of this is when struct Outer
1634   // has as its first member a struct Inner, which is copied in from a stack
1635   // variable. In this case, even if the Outer's default value is symbolic, 0,
1636   // or unknown, it gets overridden by the Inner's default value of undefined.
1637   //
1638   // This is a general problem -- if the Inner is zero-initialized, the Outer
1639   // will now look zero-initialized. The proper way to solve this is with a
1640   // new version of RegionStore that tracks the extent of a binding as well
1641   // as the offset.
1642   //
1643   // This hack only takes care of the undefined case because that can very
1644   // quickly result in a warning.
1645   if (Result.isUndef())
1646     Result = UnknownVal();
1647 
1648   return Result;
1649 }
1650 
1651 SVal
1652 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
1653                                                       const TypedValueRegion *R,
1654                                                       QualType Ty) {
1655 
1656   // At this point we have already checked in either getBindingForElement or
1657   // getBindingForField if 'R' has a direct binding.
1658 
1659   // Lazy binding?
1660   Store lazyBindingStore = NULL;
1661   const SubRegion *lazyBindingRegion = NULL;
1662   llvm::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
1663   if (lazyBindingRegion)
1664     return getLazyBinding(lazyBindingRegion,
1665                           getRegionBindings(lazyBindingStore));
1666 
1667   // Record whether or not we see a symbolic index.  That can completely
1668   // be out of scope of our lookup.
1669   bool hasSymbolicIndex = false;
1670 
1671   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1672   // default value for /part/ of an aggregate from a default value for the
1673   // /entire/ aggregate. The most common case of this is when struct Outer
1674   // has as its first member a struct Inner, which is copied in from a stack
1675   // variable. In this case, even if the Outer's default value is symbolic, 0,
1676   // or unknown, it gets overridden by the Inner's default value of undefined.
1677   //
1678   // This is a general problem -- if the Inner is zero-initialized, the Outer
1679   // will now look zero-initialized. The proper way to solve this is with a
1680   // new version of RegionStore that tracks the extent of a binding as well
1681   // as the offset.
1682   //
1683   // This hack only takes care of the undefined case because that can very
1684   // quickly result in a warning.
1685   bool hasPartialLazyBinding = false;
1686 
1687   const SubRegion *SR = dyn_cast<SubRegion>(R);
1688   while (SR) {
1689     const MemRegion *Base = SR->getSuperRegion();
1690     if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
1691       if (D->getAs<nonloc::LazyCompoundVal>()) {
1692         hasPartialLazyBinding = true;
1693         break;
1694       }
1695 
1696       return *D;
1697     }
1698 
1699     if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
1700       NonLoc index = ER->getIndex();
1701       if (!index.isConstant())
1702         hasSymbolicIndex = true;
1703     }
1704 
1705     // If our super region is a field or element itself, walk up the region
1706     // hierarchy to see if there is a default value installed in an ancestor.
1707     SR = dyn_cast<SubRegion>(Base);
1708   }
1709 
1710   if (R->hasStackNonParametersStorage()) {
1711     if (isa<ElementRegion>(R)) {
1712       // Currently we don't reason specially about Clang-style vectors.  Check
1713       // if superR is a vector and if so return Unknown.
1714       if (const TypedValueRegion *typedSuperR =
1715             dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
1716         if (typedSuperR->getValueType()->isVectorType())
1717           return UnknownVal();
1718       }
1719     }
1720 
1721     // FIXME: We also need to take ElementRegions with symbolic indexes into
1722     // account.  This case handles both directly accessing an ElementRegion
1723     // with a symbolic offset, but also fields within an element with
1724     // a symbolic offset.
1725     if (hasSymbolicIndex)
1726       return UnknownVal();
1727 
1728     if (!hasPartialLazyBinding)
1729       return UndefinedVal();
1730   }
1731 
1732   // All other values are symbolic.
1733   return svalBuilder.getRegionValueSymbolVal(R);
1734 }
1735 
1736 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
1737                                                const ObjCIvarRegion* R) {
1738   // Check if the region has a binding.
1739   if (const Optional<SVal> &V = B.getDirectBinding(R))
1740     return *V;
1741 
1742   const MemRegion *superR = R->getSuperRegion();
1743 
1744   // Check if the super region has a default binding.
1745   if (const Optional<SVal> &V = B.getDefaultBinding(superR)) {
1746     if (SymbolRef parentSym = V->getAsSymbol())
1747       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1748 
1749     // Other cases: give up.
1750     return UnknownVal();
1751   }
1752 
1753   return getBindingForLazySymbol(R);
1754 }
1755 
1756 static Optional<SVal> getConstValue(SValBuilder &SVB, const VarDecl *VD) {
1757   ASTContext &Ctx = SVB.getContext();
1758   if (!VD->getType().isConstQualified())
1759     return None;
1760 
1761   const Expr *Init = VD->getInit();
1762   if (!Init)
1763     return None;
1764 
1765   llvm::APSInt Result;
1766   if (!Init->isGLValue() && Init->EvaluateAsInt(Result, Ctx))
1767     return SVB.makeIntVal(Result);
1768 
1769   if (Init->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1770     return SVB.makeNull();
1771 
1772   // FIXME: Handle other possible constant expressions.
1773   return None;
1774 }
1775 
1776 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
1777                                           const VarRegion *R) {
1778 
1779   // Check if the region has a binding.
1780   if (const Optional<SVal> &V = B.getDirectBinding(R))
1781     return *V;
1782 
1783   // Lazily derive a value for the VarRegion.
1784   const VarDecl *VD = R->getDecl();
1785   const MemSpaceRegion *MS = R->getMemorySpace();
1786 
1787   // Arguments are always symbolic.
1788   if (isa<StackArgumentsSpaceRegion>(MS))
1789     return svalBuilder.getRegionValueSymbolVal(R);
1790 
1791   // Is 'VD' declared constant?  If so, retrieve the constant value.
1792   if (Optional<SVal> V = getConstValue(svalBuilder, VD))
1793     return *V;
1794 
1795   // This must come after the check for constants because closure-captured
1796   // constant variables may appear in UnknownSpaceRegion.
1797   if (isa<UnknownSpaceRegion>(MS))
1798     return svalBuilder.getRegionValueSymbolVal(R);
1799 
1800   if (isa<GlobalsSpaceRegion>(MS)) {
1801     QualType T = VD->getType();
1802 
1803     // Function-scoped static variables are default-initialized to 0; if they
1804     // have an initializer, it would have been processed by now.
1805     if (isa<StaticGlobalSpaceRegion>(MS))
1806       return svalBuilder.makeZeroVal(T);
1807 
1808     if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
1809       assert(!V->getAs<nonloc::LazyCompoundVal>());
1810       return V.getValue();
1811     }
1812 
1813     return svalBuilder.getRegionValueSymbolVal(R);
1814   }
1815 
1816   return UndefinedVal();
1817 }
1818 
1819 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
1820   // All other values are symbolic.
1821   return svalBuilder.getRegionValueSymbolVal(R);
1822 }
1823 
1824 const RegionStoreManager::SValListTy &
1825 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
1826   // First, check the cache.
1827   LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
1828   if (I != LazyBindingsMap.end())
1829     return I->second;
1830 
1831   // If we don't have a list of values cached, start constructing it.
1832   SValListTy List;
1833 
1834   const SubRegion *LazyR = LCV.getRegion();
1835   RegionBindingsRef B = getRegionBindings(LCV.getStore());
1836 
1837   // If this region had /no/ bindings at the time, there are no interesting
1838   // values to return.
1839   const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
1840   if (!Cluster)
1841     return (LazyBindingsMap[LCV.getCVData()] = llvm_move(List));
1842 
1843   SmallVector<BindingPair, 32> Bindings;
1844   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
1845                            /*IncludeAllDefaultBindings=*/true);
1846   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
1847                                                     E = Bindings.end();
1848        I != E; ++I) {
1849     SVal V = I->second;
1850     if (V.isUnknownOrUndef() || V.isConstant())
1851       continue;
1852 
1853     if (Optional<nonloc::LazyCompoundVal> InnerLCV =
1854             V.getAs<nonloc::LazyCompoundVal>()) {
1855       const SValListTy &InnerList = getInterestingValues(*InnerLCV);
1856       List.insert(List.end(), InnerList.begin(), InnerList.end());
1857       continue;
1858     }
1859 
1860     List.push_back(V);
1861   }
1862 
1863   return (LazyBindingsMap[LCV.getCVData()] = llvm_move(List));
1864 }
1865 
1866 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
1867                                              const TypedValueRegion *R) {
1868   if (Optional<nonloc::LazyCompoundVal> V =
1869         getExistingLazyBinding(svalBuilder, B, R, false))
1870     return *V;
1871 
1872   return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
1873 }
1874 
1875 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
1876                                              const TypedValueRegion *R) {
1877   const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
1878   if (RD->field_empty())
1879     return UnknownVal();
1880 
1881   return createLazyBinding(B, R);
1882 }
1883 
1884 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
1885                                             const TypedValueRegion *R) {
1886   assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
1887          "Only constant array types can have compound bindings.");
1888 
1889   return createLazyBinding(B, R);
1890 }
1891 
1892 bool RegionStoreManager::includedInBindings(Store store,
1893                                             const MemRegion *region) const {
1894   RegionBindingsRef B = getRegionBindings(store);
1895   region = region->getBaseRegion();
1896 
1897   // Quick path: if the base is the head of a cluster, the region is live.
1898   if (B.lookup(region))
1899     return true;
1900 
1901   // Slow path: if the region is the VALUE of any binding, it is live.
1902   for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
1903     const ClusterBindings &Cluster = RI.getData();
1904     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1905          CI != CE; ++CI) {
1906       const SVal &D = CI.getData();
1907       if (const MemRegion *R = D.getAsRegion())
1908         if (R->getBaseRegion() == region)
1909           return true;
1910     }
1911   }
1912 
1913   return false;
1914 }
1915 
1916 //===----------------------------------------------------------------------===//
1917 // Binding values to regions.
1918 //===----------------------------------------------------------------------===//
1919 
1920 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
1921   if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
1922     if (const MemRegion* R = LV->getRegion())
1923       return StoreRef(getRegionBindings(ST).removeBinding(R)
1924                                            .asImmutableMap()
1925                                            .getRootWithoutRetain(),
1926                       *this);
1927 
1928   return StoreRef(ST, *this);
1929 }
1930 
1931 RegionBindingsRef
1932 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) {
1933   if (L.getAs<loc::ConcreteInt>())
1934     return B;
1935 
1936   // If we get here, the location should be a region.
1937   const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion();
1938 
1939   // Check if the region is a struct region.
1940   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
1941     QualType Ty = TR->getValueType();
1942     if (Ty->isArrayType())
1943       return bindArray(B, TR, V);
1944     if (Ty->isStructureOrClassType())
1945       return bindStruct(B, TR, V);
1946     if (Ty->isVectorType())
1947       return bindVector(B, TR, V);
1948   }
1949 
1950   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1951     // Binding directly to a symbolic region should be treated as binding
1952     // to element 0.
1953     QualType T = SR->getSymbol()->getType();
1954     if (T->isAnyPointerType() || T->isReferenceType())
1955       T = T->getPointeeType();
1956 
1957     R = GetElementZeroRegion(SR, T);
1958   }
1959 
1960   // Clear out bindings that may overlap with this binding.
1961   RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
1962   return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
1963 }
1964 
1965 // FIXME: this method should be merged into Bind().
1966 StoreRef RegionStoreManager::bindCompoundLiteral(Store ST,
1967                                                  const CompoundLiteralExpr *CL,
1968                                                  const LocationContext *LC,
1969                                                  SVal V) {
1970   return Bind(ST, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)), V);
1971 }
1972 
1973 RegionBindingsRef
1974 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
1975                                             const MemRegion *R,
1976                                             QualType T) {
1977   SVal V;
1978 
1979   if (Loc::isLocType(T))
1980     V = svalBuilder.makeNull();
1981   else if (T->isIntegralOrEnumerationType())
1982     V = svalBuilder.makeZeroVal(T);
1983   else if (T->isStructureOrClassType() || T->isArrayType()) {
1984     // Set the default value to a zero constant when it is a structure
1985     // or array.  The type doesn't really matter.
1986     V = svalBuilder.makeZeroVal(Ctx.IntTy);
1987   }
1988   else {
1989     // We can't represent values of this type, but we still need to set a value
1990     // to record that the region has been initialized.
1991     // If this assertion ever fires, a new case should be added above -- we
1992     // should know how to default-initialize any value we can symbolicate.
1993     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
1994     V = UnknownVal();
1995   }
1996 
1997   return B.addBinding(R, BindingKey::Default, V);
1998 }
1999 
2000 RegionBindingsRef
2001 RegionStoreManager::bindArray(RegionBindingsConstRef B,
2002                               const TypedValueRegion* R,
2003                               SVal Init) {
2004 
2005   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
2006   QualType ElementTy = AT->getElementType();
2007   Optional<uint64_t> Size;
2008 
2009   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
2010     Size = CAT->getSize().getZExtValue();
2011 
2012   // Check if the init expr is a string literal.
2013   if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
2014     const StringRegion *S = cast<StringRegion>(MRV->getRegion());
2015 
2016     // Treat the string as a lazy compound value.
2017     StoreRef store(B.asStore(), *this);
2018     nonloc::LazyCompoundVal LCV = svalBuilder.makeLazyCompoundVal(store, S)
2019         .castAs<nonloc::LazyCompoundVal>();
2020     return bindAggregate(B, R, LCV);
2021   }
2022 
2023   // Handle lazy compound values.
2024   if (Init.getAs<nonloc::LazyCompoundVal>())
2025     return bindAggregate(B, R, Init);
2026 
2027   // Remaining case: explicit compound values.
2028 
2029   if (Init.isUnknown())
2030     return setImplicitDefaultValue(B, R, ElementTy);
2031 
2032   const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
2033   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2034   uint64_t i = 0;
2035 
2036   RegionBindingsRef NewB(B);
2037 
2038   for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
2039     // The init list might be shorter than the array length.
2040     if (VI == VE)
2041       break;
2042 
2043     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
2044     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
2045 
2046     if (ElementTy->isStructureOrClassType())
2047       NewB = bindStruct(NewB, ER, *VI);
2048     else if (ElementTy->isArrayType())
2049       NewB = bindArray(NewB, ER, *VI);
2050     else
2051       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2052   }
2053 
2054   // If the init list is shorter than the array length, set the
2055   // array default value.
2056   if (Size.hasValue() && i < Size.getValue())
2057     NewB = setImplicitDefaultValue(NewB, R, ElementTy);
2058 
2059   return NewB;
2060 }
2061 
2062 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B,
2063                                                  const TypedValueRegion* R,
2064                                                  SVal V) {
2065   QualType T = R->getValueType();
2066   assert(T->isVectorType());
2067   const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
2068 
2069   // Handle lazy compound values and symbolic values.
2070   if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>())
2071     return bindAggregate(B, R, V);
2072 
2073   // We may get non-CompoundVal accidentally due to imprecise cast logic or
2074   // that we are binding symbolic struct value. Kill the field values, and if
2075   // the value is symbolic go and bind it as a "default" binding.
2076   if (!V.getAs<nonloc::CompoundVal>()) {
2077     return bindAggregate(B, R, UnknownVal());
2078   }
2079 
2080   QualType ElemType = VT->getElementType();
2081   nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
2082   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2083   unsigned index = 0, numElements = VT->getNumElements();
2084   RegionBindingsRef NewB(B);
2085 
2086   for ( ; index != numElements ; ++index) {
2087     if (VI == VE)
2088       break;
2089 
2090     NonLoc Idx = svalBuilder.makeArrayIndex(index);
2091     const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
2092 
2093     if (ElemType->isArrayType())
2094       NewB = bindArray(NewB, ER, *VI);
2095     else if (ElemType->isStructureOrClassType())
2096       NewB = bindStruct(NewB, ER, *VI);
2097     else
2098       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2099   }
2100   return NewB;
2101 }
2102 
2103 Optional<RegionBindingsRef>
2104 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B,
2105                                        const TypedValueRegion *R,
2106                                        const RecordDecl *RD,
2107                                        nonloc::LazyCompoundVal LCV) {
2108   FieldVector Fields;
2109 
2110   if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
2111     if (Class->getNumBases() != 0 || Class->getNumVBases() != 0)
2112       return None;
2113 
2114   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2115        I != E; ++I) {
2116     const FieldDecl *FD = *I;
2117     if (FD->isUnnamedBitfield())
2118       continue;
2119 
2120     // If there are too many fields, or if any of the fields are aggregates,
2121     // just use the LCV as a default binding.
2122     if (Fields.size() == SmallStructLimit)
2123       return None;
2124 
2125     QualType Ty = FD->getType();
2126     if (!(Ty->isScalarType() || Ty->isReferenceType()))
2127       return None;
2128 
2129     Fields.push_back(*I);
2130   }
2131 
2132   RegionBindingsRef NewB = B;
2133 
2134   for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){
2135     const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
2136     SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
2137 
2138     const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
2139     NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
2140   }
2141 
2142   return NewB;
2143 }
2144 
2145 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B,
2146                                                  const TypedValueRegion* R,
2147                                                  SVal V) {
2148   if (!Features.supportsFields())
2149     return B;
2150 
2151   QualType T = R->getValueType();
2152   assert(T->isStructureOrClassType());
2153 
2154   const RecordType* RT = T->getAs<RecordType>();
2155   const RecordDecl *RD = RT->getDecl();
2156 
2157   if (!RD->isCompleteDefinition())
2158     return B;
2159 
2160   // Handle lazy compound values and symbolic values.
2161   if (Optional<nonloc::LazyCompoundVal> LCV =
2162         V.getAs<nonloc::LazyCompoundVal>()) {
2163     if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV))
2164       return *NewB;
2165     return bindAggregate(B, R, V);
2166   }
2167   if (V.getAs<nonloc::SymbolVal>())
2168     return bindAggregate(B, R, V);
2169 
2170   // We may get non-CompoundVal accidentally due to imprecise cast logic or
2171   // that we are binding symbolic struct value. Kill the field values, and if
2172   // the value is symbolic go and bind it as a "default" binding.
2173   if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>())
2174     return bindAggregate(B, R, UnknownVal());
2175 
2176   const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
2177   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2178 
2179   RecordDecl::field_iterator FI, FE;
2180   RegionBindingsRef NewB(B);
2181 
2182   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
2183 
2184     if (VI == VE)
2185       break;
2186 
2187     // Skip any unnamed bitfields to stay in sync with the initializers.
2188     if (FI->isUnnamedBitfield())
2189       continue;
2190 
2191     QualType FTy = FI->getType();
2192     const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
2193 
2194     if (FTy->isArrayType())
2195       NewB = bindArray(NewB, FR, *VI);
2196     else if (FTy->isStructureOrClassType())
2197       NewB = bindStruct(NewB, FR, *VI);
2198     else
2199       NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
2200     ++VI;
2201   }
2202 
2203   // There may be fewer values in the initialize list than the fields of struct.
2204   if (FI != FE) {
2205     NewB = NewB.addBinding(R, BindingKey::Default,
2206                            svalBuilder.makeIntVal(0, false));
2207   }
2208 
2209   return NewB;
2210 }
2211 
2212 RegionBindingsRef
2213 RegionStoreManager::bindAggregate(RegionBindingsConstRef B,
2214                                   const TypedRegion *R,
2215                                   SVal Val) {
2216   // Remove the old bindings, using 'R' as the root of all regions
2217   // we will invalidate. Then add the new binding.
2218   return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
2219 }
2220 
2221 //===----------------------------------------------------------------------===//
2222 // State pruning.
2223 //===----------------------------------------------------------------------===//
2224 
2225 namespace {
2226 class removeDeadBindingsWorker :
2227   public ClusterAnalysis<removeDeadBindingsWorker> {
2228   SmallVector<const SymbolicRegion*, 12> Postponed;
2229   SymbolReaper &SymReaper;
2230   const StackFrameContext *CurrentLCtx;
2231 
2232 public:
2233   removeDeadBindingsWorker(RegionStoreManager &rm,
2234                            ProgramStateManager &stateMgr,
2235                            RegionBindingsRef b, SymbolReaper &symReaper,
2236                            const StackFrameContext *LCtx)
2237     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b, GFK_None),
2238       SymReaper(symReaper), CurrentLCtx(LCtx) {}
2239 
2240   // Called by ClusterAnalysis.
2241   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
2242   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
2243   using ClusterAnalysis<removeDeadBindingsWorker>::VisitCluster;
2244 
2245   bool UpdatePostponed();
2246   void VisitBinding(SVal V);
2247 };
2248 }
2249 
2250 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
2251                                                    const ClusterBindings &C) {
2252 
2253   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
2254     if (SymReaper.isLive(VR))
2255       AddToWorkList(baseR, &C);
2256 
2257     return;
2258   }
2259 
2260   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
2261     if (SymReaper.isLive(SR->getSymbol()))
2262       AddToWorkList(SR, &C);
2263     else
2264       Postponed.push_back(SR);
2265 
2266     return;
2267   }
2268 
2269   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
2270     AddToWorkList(baseR, &C);
2271     return;
2272   }
2273 
2274   // CXXThisRegion in the current or parent location context is live.
2275   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
2276     const StackArgumentsSpaceRegion *StackReg =
2277       cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
2278     const StackFrameContext *RegCtx = StackReg->getStackFrame();
2279     if (CurrentLCtx &&
2280         (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)))
2281       AddToWorkList(TR, &C);
2282   }
2283 }
2284 
2285 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
2286                                             const ClusterBindings *C) {
2287   if (!C)
2288     return;
2289 
2290   // Mark the symbol for any SymbolicRegion with live bindings as live itself.
2291   // This means we should continue to track that symbol.
2292   if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
2293     SymReaper.markLive(SymR->getSymbol());
2294 
2295   for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
2296     VisitBinding(I.getData());
2297 }
2298 
2299 void removeDeadBindingsWorker::VisitBinding(SVal V) {
2300   // Is it a LazyCompoundVal?  All referenced regions are live as well.
2301   if (Optional<nonloc::LazyCompoundVal> LCS =
2302           V.getAs<nonloc::LazyCompoundVal>()) {
2303 
2304     const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
2305 
2306     for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
2307                                                         E = Vals.end();
2308          I != E; ++I)
2309       VisitBinding(*I);
2310 
2311     return;
2312   }
2313 
2314   // If V is a region, then add it to the worklist.
2315   if (const MemRegion *R = V.getAsRegion()) {
2316     AddToWorkList(R);
2317 
2318     // All regions captured by a block are also live.
2319     if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
2320       BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
2321                                                 E = BR->referenced_vars_end();
2322       for ( ; I != E; ++I)
2323         AddToWorkList(I.getCapturedRegion());
2324     }
2325   }
2326 
2327 
2328   // Update the set of live symbols.
2329   for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
2330        SI!=SE; ++SI)
2331     SymReaper.markLive(*SI);
2332 }
2333 
2334 bool removeDeadBindingsWorker::UpdatePostponed() {
2335   // See if any postponed SymbolicRegions are actually live now, after
2336   // having done a scan.
2337   bool changed = false;
2338 
2339   for (SmallVectorImpl<const SymbolicRegion*>::iterator
2340         I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
2341     if (const SymbolicRegion *SR = *I) {
2342       if (SymReaper.isLive(SR->getSymbol())) {
2343         changed |= AddToWorkList(SR);
2344         *I = NULL;
2345       }
2346     }
2347   }
2348 
2349   return changed;
2350 }
2351 
2352 StoreRef RegionStoreManager::removeDeadBindings(Store store,
2353                                                 const StackFrameContext *LCtx,
2354                                                 SymbolReaper& SymReaper) {
2355   RegionBindingsRef B = getRegionBindings(store);
2356   removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
2357   W.GenerateClusters();
2358 
2359   // Enqueue the region roots onto the worklist.
2360   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
2361        E = SymReaper.region_end(); I != E; ++I) {
2362     W.AddToWorkList(*I);
2363   }
2364 
2365   do W.RunWorkList(); while (W.UpdatePostponed());
2366 
2367   // We have now scanned the store, marking reachable regions and symbols
2368   // as live.  We now remove all the regions that are dead from the store
2369   // as well as update DSymbols with the set symbols that are now dead.
2370   for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2371     const MemRegion *Base = I.getKey();
2372 
2373     // If the cluster has been visited, we know the region has been marked.
2374     if (W.isVisited(Base))
2375       continue;
2376 
2377     // Remove the dead entry.
2378     B = B.remove(Base);
2379 
2380     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base))
2381       SymReaper.maybeDead(SymR->getSymbol());
2382 
2383     // Mark all non-live symbols that this binding references as dead.
2384     const ClusterBindings &Cluster = I.getData();
2385     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
2386          CI != CE; ++CI) {
2387       SVal X = CI.getData();
2388       SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
2389       for (; SI != SE; ++SI)
2390         SymReaper.maybeDead(*SI);
2391     }
2392   }
2393 
2394   return StoreRef(B.asStore(), *this);
2395 }
2396 
2397 //===----------------------------------------------------------------------===//
2398 // Utility methods.
2399 //===----------------------------------------------------------------------===//
2400 
2401 void RegionStoreManager::print(Store store, raw_ostream &OS,
2402                                const char* nl, const char *sep) {
2403   RegionBindingsRef B = getRegionBindings(store);
2404   OS << "Store (direct and default bindings), "
2405      << B.asStore()
2406      << " :" << nl;
2407   B.dump(OS, nl);
2408 }
2409