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