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