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