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