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