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