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