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