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