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