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