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