1 //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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/ObjCMessage.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
27 #include "llvm/ADT/ImmutableList.h"
28 #include "llvm/ADT/ImmutableMap.h"
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/Support/raw_ostream.h"
32 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // Representation of binding keys.
38 //===----------------------------------------------------------------------===//
43 enum Kind { Direct = 0x0, Default = 0x1 };
45 llvm ::PointerIntPair<const MemRegion*, 1> P;
48 explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
49 : P(r, (unsigned) k), Offset(offset) {}
52 bool isDirect() const { return P.getInt() == Direct; }
54 const MemRegion *getRegion() const { return P.getPointer(); }
55 uint64_t getOffset() const { return Offset; }
57 void Profile(llvm::FoldingSetNodeID& ID) const {
58 ID.AddPointer(P.getOpaqueValue());
59 ID.AddInteger(Offset);
62 static BindingKey Make(const MemRegion *R, Kind k);
64 bool operator<(const BindingKey &X) const {
65 if (P.getOpaqueValue() < X.P.getOpaqueValue())
67 if (P.getOpaqueValue() > X.P.getOpaqueValue())
69 return Offset < X.Offset;
72 bool operator==(const BindingKey &X) const {
73 return P.getOpaqueValue() == X.P.getOpaqueValue() &&
77 bool isValid() const {
78 return getRegion() != NULL;
81 } // end anonymous namespace
83 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
84 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
85 const RegionRawOffset &O = ER->getAsArrayOffset();
87 // FIXME: There are some ElementRegions for which we cannot compute
88 // raw offsets yet, including regions with symbolic offsets. These will be
89 // ignored by the store.
90 return BindingKey(O.getRegion(), O.getOffset().getQuantity(), k);
93 return BindingKey(R, 0, k);
98 raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
99 os << '(' << K.getRegion() << ',' << K.getOffset()
100 << ',' << (K.isDirect() ? "direct" : "default")
104 } // end llvm namespace
106 //===----------------------------------------------------------------------===//
107 // Actual Store type.
108 //===----------------------------------------------------------------------===//
110 typedef llvm::ImmutableMap<BindingKey, SVal> RegionBindings;
112 //===----------------------------------------------------------------------===//
113 // Fine-grained control of RegionStoreManager.
114 //===----------------------------------------------------------------------===//
117 struct minimal_features_tag {};
118 struct maximal_features_tag {};
120 class RegionStoreFeatures {
123 RegionStoreFeatures(minimal_features_tag) :
124 SupportsFields(false) {}
126 RegionStoreFeatures(maximal_features_tag) :
127 SupportsFields(true) {}
129 void enableFields(bool t) { SupportsFields = t; }
131 bool supportsFields() const { return SupportsFields; }
135 //===----------------------------------------------------------------------===//
136 // Main RegionStore logic.
137 //===----------------------------------------------------------------------===//
141 class RegionStoreSubRegionMap : public SubRegionMap {
143 typedef llvm::ImmutableSet<const MemRegion*> Set;
144 typedef llvm::DenseMap<const MemRegion*, Set> Map;
149 bool add(const MemRegion* Parent, const MemRegion* SubRegion) {
150 Map::iterator I = M.find(Parent);
153 M.insert(std::make_pair(Parent, F.add(F.getEmptySet(), SubRegion)));
157 I->second = F.add(I->second, SubRegion);
161 void process(SmallVectorImpl<const SubRegion*> &WL, const SubRegion *R);
163 ~RegionStoreSubRegionMap() {}
165 const Set *getSubRegions(const MemRegion *Parent) const {
166 Map::const_iterator I = M.find(Parent);
167 return I == M.end() ? NULL : &I->second;
170 bool iterSubRegions(const MemRegion* Parent, Visitor& V) const {
171 Map::const_iterator I = M.find(Parent);
177 for (Set::iterator SI=S.begin(),SE=S.end(); SI != SE; ++SI) {
178 if (!V.Visit(Parent, *SI))
187 RegionStoreSubRegionMap::process(SmallVectorImpl<const SubRegion*> &WL,
188 const SubRegion *R) {
189 const MemRegion *superR = R->getSuperRegion();
191 if (const SubRegion *sr = dyn_cast<SubRegion>(superR))
195 class RegionStoreManager : public StoreManager {
196 const RegionStoreFeatures Features;
197 RegionBindings::Factory RBFactory;
200 RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
203 RBFactory(mgr.getAllocator()) {}
205 SubRegionMap *getSubRegionMap(Store store) {
206 return getRegionStoreSubRegionMap(store);
209 RegionStoreSubRegionMap *getRegionStoreSubRegionMap(Store store);
211 Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R);
212 /// getDefaultBinding - Returns an SVal* representing an optional default
213 /// binding associated with a region and its subregions.
214 Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R);
216 /// setImplicitDefaultValue - Set the default binding for the provided
217 /// MemRegion to the value implicitly defined for compound literals when
218 /// the value is not specified.
219 StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T);
221 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
222 /// type. 'Array' represents the lvalue of the array being decayed
223 /// to a pointer, and the returned SVal represents the decayed
224 /// version of that lvalue (i.e., a pointer to the first element of
225 /// the array). This is called by ExprEngine when evaluating
226 /// casts from arrays to pointers.
227 SVal ArrayToPointer(Loc Array);
229 /// For DerivedToBase casts, create a CXXBaseObjectRegion and return it.
230 virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType);
232 /// \brief Evaluates C++ dynamic_cast cast.
233 /// The callback may result in the following 3 scenarios:
234 /// - Successful cast (ex: derived is subclass of base).
235 /// - Failed cast (ex: derived is definitely not a subclass of base).
236 /// - We don't know (base is a symbolic region and we don't have
237 /// enough info to determine if the cast will succeed at run time).
238 /// The function returns an SVal representing the derived class; it's
239 /// valid only if Failed flag is set to false.
240 virtual SVal evalDynamicCast(SVal base, QualType derivedPtrType,bool &Failed);
242 StoreRef getInitialStore(const LocationContext *InitLoc) {
243 return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
246 //===-------------------------------------------------------------------===//
247 // Binding values to regions.
248 //===-------------------------------------------------------------------===//
249 RegionBindings invalidateGlobalRegion(MemRegion::Kind K,
252 const LocationContext *LCtx,
254 InvalidatedRegions *Invalidated);
256 StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions,
257 const Expr *E, unsigned Count,
258 const LocationContext *LCtx,
259 InvalidatedSymbols &IS,
260 const CallOrObjCMessage *Call,
261 InvalidatedRegions *Invalidated);
263 public: // Made public for helper classes.
265 void RemoveSubRegionBindings(RegionBindings &B, const MemRegion *R,
266 RegionStoreSubRegionMap &M);
268 RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V);
270 RegionBindings addBinding(RegionBindings B, const MemRegion *R,
271 BindingKey::Kind k, SVal V);
273 const SVal *lookup(RegionBindings B, BindingKey K);
274 const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k);
276 RegionBindings removeBinding(RegionBindings B, BindingKey K);
277 RegionBindings removeBinding(RegionBindings B, const MemRegion *R,
280 RegionBindings removeBinding(RegionBindings B, const MemRegion *R) {
281 return removeBinding(removeBinding(B, R, BindingKey::Direct), R,
282 BindingKey::Default);
285 public: // Part of public interface to class.
287 StoreRef Bind(Store store, Loc LV, SVal V);
289 // BindDefault is only used to initialize a region with a default value.
290 StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
291 RegionBindings B = GetRegionBindings(store);
292 assert(!lookup(B, R, BindingKey::Default));
293 assert(!lookup(B, R, BindingKey::Direct));
294 return StoreRef(addBinding(B, R, BindingKey::Default, V)
295 .getRootWithoutRetain(), *this);
298 StoreRef BindCompoundLiteral(Store store, const CompoundLiteralExpr *CL,
299 const LocationContext *LC, SVal V);
301 StoreRef BindDecl(Store store, const VarRegion *VR, SVal InitVal);
303 StoreRef BindDeclWithNoInit(Store store, const VarRegion *) {
304 return StoreRef(store, *this);
307 /// BindStruct - Bind a compound value to a structure.
308 StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V);
310 StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V);
312 /// KillStruct - Set the entire struct to unknown.
313 StoreRef KillStruct(Store store, const TypedRegion* R, SVal DefaultVal);
315 StoreRef Remove(Store store, Loc LV);
317 void incrementReferenceCount(Store store) {
318 GetRegionBindings(store).manualRetain();
321 /// If the StoreManager supports it, decrement the reference count of
322 /// the specified Store object. If the reference count hits 0, the memory
323 /// associated with the object is recycled.
324 void decrementReferenceCount(Store store) {
325 GetRegionBindings(store).manualRelease();
328 bool includedInBindings(Store store, const MemRegion *region) const;
330 /// \brief Return the value bound to specified location in a given state.
332 /// The high level logic for this method is this:
335 /// return L's binding
336 /// else if L is in killset
339 /// if L is on stack or heap
343 SVal getBinding(Store store, Loc L, QualType T = QualType());
345 SVal getBindingForElement(Store store, const ElementRegion *R);
347 SVal getBindingForField(Store store, const FieldRegion *R);
349 SVal getBindingForObjCIvar(Store store, const ObjCIvarRegion *R);
351 SVal getBindingForVar(Store store, const VarRegion *R);
353 SVal getBindingForLazySymbol(const TypedValueRegion *R);
355 SVal getBindingForFieldOrElementCommon(Store store, const TypedValueRegion *R,
356 QualType Ty, const MemRegion *superR);
358 SVal getLazyBinding(const MemRegion *lazyBindingRegion,
359 Store lazyBindingStore);
361 /// Get bindings for the values in a struct and return a CompoundVal, used
362 /// when doing struct copy:
365 /// y's value is retrieved by this method.
366 SVal getBindingForStruct(Store store, const TypedValueRegion* R);
368 SVal getBindingForArray(Store store, const TypedValueRegion* R);
370 /// Used to lazily generate derived symbols for bindings that are defined
371 /// implicitly by default bindings in a super region.
372 Optional<SVal> getBindingForDerivedDefaultValue(RegionBindings B,
373 const MemRegion *superR,
374 const TypedValueRegion *R,
377 /// Get the state and region whose binding this region R corresponds to.
378 std::pair<Store, const MemRegion*>
379 GetLazyBinding(RegionBindings B, const MemRegion *R,
380 const MemRegion *originalRegion);
382 StoreRef CopyLazyBindings(nonloc::LazyCompoundVal V, Store store,
383 const TypedRegion *R);
385 //===------------------------------------------------------------------===//
387 //===------------------------------------------------------------------===//
389 /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
390 /// It returns a new Store with these values removed.
391 StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
392 SymbolReaper& SymReaper);
394 StoreRef enterStackFrame(ProgramStateRef state,
395 const LocationContext *callerCtx,
396 const StackFrameContext *calleeCtx);
398 //===------------------------------------------------------------------===//
400 //===------------------------------------------------------------------===//
402 // FIXME: This method will soon be eliminated; see the note in Store.h.
403 DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
404 const MemRegion* R, QualType EleTy);
406 //===------------------------------------------------------------------===//
408 //===------------------------------------------------------------------===//
410 static inline RegionBindings GetRegionBindings(Store store) {
411 return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store));
414 void print(Store store, raw_ostream &Out, const char* nl,
417 void iterBindings(Store store, BindingsHandler& f) {
418 RegionBindings B = GetRegionBindings(store);
419 for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
420 const BindingKey &K = I.getKey();
423 if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion())) {
424 // FIXME: Possibly incorporate the offset?
425 if (!f.HandleBinding(*this, store, R, I.getData()))
432 } // end anonymous namespace
434 //===----------------------------------------------------------------------===//
435 // RegionStore creation.
436 //===----------------------------------------------------------------------===//
438 StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
439 RegionStoreFeatures F = maximal_features_tag();
440 return new RegionStoreManager(StMgr, F);
444 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
445 RegionStoreFeatures F = minimal_features_tag();
446 F.enableFields(true);
447 return new RegionStoreManager(StMgr, F);
451 RegionStoreSubRegionMap*
452 RegionStoreManager::getRegionStoreSubRegionMap(Store store) {
453 RegionBindings B = GetRegionBindings(store);
454 RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap();
456 SmallVector<const SubRegion*, 10> WL;
458 for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I)
459 if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion()))
462 // We also need to record in the subregion map "intermediate" regions that
463 // don't have direct bindings but are super regions of those that do.
464 while (!WL.empty()) {
465 const SubRegion *R = WL.back();
473 //===----------------------------------------------------------------------===//
474 // Region Cluster analysis.
475 //===----------------------------------------------------------------------===//
478 template <typename DERIVED>
479 class ClusterAnalysis {
481 typedef BumpVector<BindingKey> RegionCluster;
482 typedef llvm::DenseMap<const MemRegion *, RegionCluster *> ClusterMap;
483 llvm::DenseMap<const RegionCluster*, unsigned> Visited;
484 typedef SmallVector<std::pair<const MemRegion *, RegionCluster*>, 10>
487 BumpVectorContext BVC;
491 RegionStoreManager &RM;
493 SValBuilder &svalBuilder;
497 const bool includeGlobals;
500 ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
501 RegionBindings b, const bool includeGlobals)
502 : RM(rm), Ctx(StateMgr.getContext()),
503 svalBuilder(StateMgr.getSValBuilder()),
504 B(b), includeGlobals(includeGlobals) {}
506 RegionBindings getRegionBindings() const { return B; }
508 RegionCluster &AddToCluster(BindingKey K) {
509 const MemRegion *R = K.getRegion();
510 const MemRegion *baseR = R->getBaseRegion();
511 RegionCluster &C = getCluster(baseR);
513 static_cast<DERIVED*>(this)->VisitAddedToCluster(baseR, C);
517 bool isVisited(const MemRegion *R) {
518 return (bool) Visited[&getCluster(R->getBaseRegion())];
521 RegionCluster& getCluster(const MemRegion *R) {
522 RegionCluster *&CRef = ClusterM[R];
524 void *Mem = BVC.getAllocator().template Allocate<RegionCluster>();
525 CRef = new (Mem) RegionCluster(BVC, 10);
530 void GenerateClusters() {
531 // Scan the entire set of bindings and make the region clusters.
532 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
533 RegionCluster &C = AddToCluster(RI.getKey());
534 if (const MemRegion *R = RI.getData().getAsRegion()) {
535 // Generate a cluster, but don't add the region to the cluster
536 // if there aren't any bindings.
537 getCluster(R->getBaseRegion());
539 if (includeGlobals) {
540 const MemRegion *R = RI.getKey().getRegion();
541 if (isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()))
547 bool AddToWorkList(const MemRegion *R, RegionCluster &C) {
548 if (unsigned &visited = Visited[&C])
553 WL.push_back(std::make_pair(R, &C));
557 bool AddToWorkList(BindingKey K) {
558 return AddToWorkList(K.getRegion());
561 bool AddToWorkList(const MemRegion *R) {
562 const MemRegion *baseR = R->getBaseRegion();
563 return AddToWorkList(baseR, getCluster(baseR));
567 while (!WL.empty()) {
568 const MemRegion *baseR;
570 llvm::tie(baseR, C) = WL.back();
573 // First visit the cluster.
574 static_cast<DERIVED*>(this)->VisitCluster(baseR, C->begin(), C->end());
576 // Next, visit the base region.
577 static_cast<DERIVED*>(this)->VisitBaseRegion(baseR);
582 void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C) {}
583 void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E) {}
584 void VisitBaseRegion(const MemRegion *baseR) {}
588 //===----------------------------------------------------------------------===//
589 // Binding invalidation.
590 //===----------------------------------------------------------------------===//
592 void RegionStoreManager::RemoveSubRegionBindings(RegionBindings &B,
594 RegionStoreSubRegionMap &M) {
596 if (const RegionStoreSubRegionMap::Set *S = M.getSubRegions(R))
597 for (RegionStoreSubRegionMap::Set::iterator I = S->begin(), E = S->end();
599 RemoveSubRegionBindings(B, *I, M);
601 B = removeBinding(B, R);
605 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
609 const LocationContext *LCtx;
610 StoreManager::InvalidatedSymbols &IS;
611 StoreManager::InvalidatedRegions *Regions;
613 invalidateRegionsWorker(RegionStoreManager &rm,
614 ProgramStateManager &stateMgr,
616 const Expr *ex, unsigned count,
617 const LocationContext *lctx,
618 StoreManager::InvalidatedSymbols &is,
619 StoreManager::InvalidatedRegions *r,
621 : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals),
622 Ex(ex), Count(count), LCtx(lctx), IS(is), Regions(r) {}
624 void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
625 void VisitBaseRegion(const MemRegion *baseR);
628 void VisitBinding(SVal V);
632 void invalidateRegionsWorker::VisitBinding(SVal V) {
633 // A symbol? Mark it touched by the invalidation.
634 if (SymbolRef Sym = V.getAsSymbol())
637 if (const MemRegion *R = V.getAsRegion()) {
642 // Is it a LazyCompoundVal? All references get invalidated as well.
643 if (const nonloc::LazyCompoundVal *LCS =
644 dyn_cast<nonloc::LazyCompoundVal>(&V)) {
646 const MemRegion *LazyR = LCS->getRegion();
647 RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
649 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
650 const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
651 if (baseR && baseR->isSubRegionOf(LazyR))
652 VisitBinding(RI.getData());
659 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
660 BindingKey *I, BindingKey *E) {
661 for ( ; I != E; ++I) {
662 // Get the old binding. Is it a region? If so, add it to the worklist.
663 const BindingKey &K = *I;
664 if (const SVal *V = RM.lookup(B, K))
667 B = RM.removeBinding(B, K);
671 void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) {
672 // Symbolic region? Mark that symbol touched by the invalidation.
673 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
674 IS.insert(SR->getSymbol());
676 // BlockDataRegion? If so, invalidate captured variables that are passed
678 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
679 for (BlockDataRegion::referenced_vars_iterator
680 BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
682 const VarRegion *VR = *BI;
683 const VarDecl *VD = VR->getDecl();
684 if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage())
690 // Otherwise, we have a normal data region. Record that we touched the region.
692 Regions->push_back(baseR);
694 if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
695 // Invalidate the region by setting its default value to
696 // conjured symbol. The type of the symbol is irrelavant.
697 DefinedOrUnknownSVal V =
698 svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
699 B = RM.addBinding(B, baseR, BindingKey::Default, V);
703 if (!baseR->isBoundable())
706 const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
707 QualType T = TR->getValueType();
709 // Invalidate the binding.
710 if (T->isStructureOrClassType()) {
711 // Invalidate the region by setting its default value to
712 // conjured symbol. The type of the symbol is irrelavant.
713 DefinedOrUnknownSVal V =
714 svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
715 B = RM.addBinding(B, baseR, BindingKey::Default, V);
719 if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
720 // Set the default value of the array to conjured symbol.
721 DefinedOrUnknownSVal V =
722 svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx,
723 AT->getElementType(), Count);
724 B = RM.addBinding(B, baseR, BindingKey::Default, V);
728 if (includeGlobals &&
729 isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) {
730 // If the region is a global and we are invalidating all globals,
731 // just erase the entry. This causes all globals to be lazily
732 // symbolicated from the same base symbol.
733 B = RM.removeBinding(B, baseR);
738 DefinedOrUnknownSVal V = svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx,
740 assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
741 B = RM.addBinding(B, baseR, BindingKey::Direct, V);
744 RegionBindings RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
747 const LocationContext *LCtx,
749 InvalidatedRegions *Invalidated) {
750 // Bind the globals memory space to a new symbol that we will use to derive
751 // the bindings for all globals.
752 const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
754 svalBuilder.getConjuredSymbolVal(/* SymbolTag = */ (void*) GS, Ex, LCtx,
755 /* symbol type, doesn't matter */ Ctx.IntTy,
758 B = removeBinding(B, GS);
759 B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
761 // Even if there are no bindings in the global scope, we still need to
762 // record that we touched it.
764 Invalidated->push_back(GS);
769 StoreRef RegionStoreManager::invalidateRegions(Store store,
770 ArrayRef<const MemRegion *> Regions,
771 const Expr *Ex, unsigned Count,
772 const LocationContext *LCtx,
773 InvalidatedSymbols &IS,
774 const CallOrObjCMessage *Call,
775 InvalidatedRegions *Invalidated) {
776 invalidateRegionsWorker W(*this, StateMgr,
777 RegionStoreManager::GetRegionBindings(store),
778 Ex, Count, LCtx, IS, Invalidated, false);
780 // Scan the bindings and generate the clusters.
781 W.GenerateClusters();
783 // Add the regions to the worklist.
784 for (ArrayRef<const MemRegion *>::iterator
785 I = Regions.begin(), E = Regions.end(); I != E; ++I)
790 // Return the new bindings.
791 RegionBindings B = W.getRegionBindings();
793 // For all globals which are not static nor immutable: determine which global
794 // regions should be invalidated and invalidate them.
795 // TODO: This could possibly be more precise with modules.
797 // System calls invalidate only system globals.
798 if (Call && Call->isInSystemHeader()) {
799 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
800 Ex, Count, LCtx, B, Invalidated);
801 // Internal calls might invalidate both system and internal globals.
803 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
804 Ex, Count, LCtx, B, Invalidated);
805 B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
806 Ex, Count, LCtx, B, Invalidated);
809 return StoreRef(B.getRootWithoutRetain(), *this);
812 //===----------------------------------------------------------------------===//
813 // Extents for regions.
814 //===----------------------------------------------------------------------===//
817 RegionStoreManager::getSizeInElements(ProgramStateRef state,
820 SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
821 const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
825 CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
827 if (Ctx.getAsVariableArrayType(EleTy)) {
828 // FIXME: We need to track extra state to properly record the size
829 // of VLAs. Returning UnknownVal here, however, is a stop-gap so that
830 // we don't have a divide-by-zero below.
834 CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
836 // If a variable is reinterpreted as a type that doesn't fit into a larger
837 // type evenly, round it down.
838 // This is a signed value, since it's used in arithmetic with signed indices.
839 return svalBuilder.makeIntVal(RegionSize / EleSize, false);
842 //===----------------------------------------------------------------------===//
843 // Location and region casting.
844 //===----------------------------------------------------------------------===//
846 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
847 /// type. 'Array' represents the lvalue of the array being decayed
848 /// to a pointer, and the returned SVal represents the decayed
849 /// version of that lvalue (i.e., a pointer to the first element of
850 /// the array). This is called by ExprEngine when evaluating casts
851 /// from arrays to pointers.
852 SVal RegionStoreManager::ArrayToPointer(Loc Array) {
853 if (!isa<loc::MemRegionVal>(Array))
856 const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
857 const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
862 // Strip off typedefs from the ArrayRegion's ValueType.
863 QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
864 const ArrayType *AT = cast<ArrayType>(T);
865 T = AT->getElementType();
867 NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
868 return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
871 SVal RegionStoreManager::evalDerivedToBase(SVal derived, QualType baseType) {
872 const CXXRecordDecl *baseDecl;
873 if (baseType->isPointerType())
874 baseDecl = baseType->getCXXRecordDeclForPointerType();
876 baseDecl = baseType->getAsCXXRecordDecl();
878 assert(baseDecl && "not a CXXRecordDecl?");
880 loc::MemRegionVal *derivedRegVal = dyn_cast<loc::MemRegionVal>(&derived);
884 const MemRegion *baseReg =
885 MRMgr.getCXXBaseObjectRegion(baseDecl, derivedRegVal->getRegion());
887 return loc::MemRegionVal(baseReg);
890 SVal RegionStoreManager::evalDynamicCast(SVal base, QualType derivedType,
894 loc::MemRegionVal *baseRegVal = dyn_cast<loc::MemRegionVal>(&base);
897 const MemRegion *BaseRegion = baseRegVal->stripCasts();
899 // Assume the derived class is a pointer or a reference to a CXX record.
900 derivedType = derivedType->getPointeeType();
901 assert(!derivedType.isNull());
902 const CXXRecordDecl *DerivedDecl = derivedType->getAsCXXRecordDecl();
903 if (!DerivedDecl && !derivedType->isVoidType())
906 // Drill down the CXXBaseObject chains, which represent upcasts (casts from
908 const MemRegion *SR = BaseRegion;
909 while (const TypedRegion *TSR = dyn_cast_or_null<TypedRegion>(SR)) {
910 QualType BaseType = TSR->getLocationType()->getPointeeType();
911 assert(!BaseType.isNull());
912 const CXXRecordDecl *SRDecl = BaseType->getAsCXXRecordDecl();
916 // If found the derived class, the cast succeeds.
917 if (SRDecl == DerivedDecl)
918 return loc::MemRegionVal(TSR);
920 // If the region type is a subclass of the derived type.
921 if (!derivedType->isVoidType() && SRDecl->isDerivedFrom(DerivedDecl)) {
922 // This occurs in two cases.
923 // 1) We are processing an upcast.
924 // 2) We are processing a downcast but we jumped directly from the
925 // ancestor to a child of the cast value, so conjure the
926 // appropriate region to represent value (the intermediate node).
927 return loc::MemRegionVal(MRMgr.getCXXBaseObjectRegion(DerivedDecl,
931 // If super region is not a parent of derived class, the cast definitely
933 if (!derivedType->isVoidType() &&
934 DerivedDecl->isProvablyNotDerivedFrom(SRDecl)) {
939 if (const CXXBaseObjectRegion *R = dyn_cast<CXXBaseObjectRegion>(TSR))
940 // Drill down the chain to get the derived classes.
941 SR = R->getSuperRegion();
943 // We reached the bottom of the hierarchy.
945 // If this is a cast to void*, return the region.
946 if (derivedType->isVoidType())
947 return loc::MemRegionVal(TSR);
949 // We did not find the derived class. We we must be casting the base to
950 // derived, so the cast should fail.
959 //===----------------------------------------------------------------------===//
960 // Loading values from regions.
961 //===----------------------------------------------------------------------===//
963 Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B,
964 const MemRegion *R) {
966 if (const SVal *V = lookup(B, R, BindingKey::Direct))
969 return Optional<SVal>();
972 Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B,
973 const MemRegion *R) {
974 if (R->isBoundable())
975 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
976 if (TR->getValueType()->isUnionType())
979 if (const SVal *V = lookup(B, R, BindingKey::Default))
982 return Optional<SVal>();
985 SVal RegionStoreManager::getBinding(Store store, Loc L, QualType T) {
986 assert(!isa<UnknownVal>(L) && "location unknown");
987 assert(!isa<UndefinedVal>(L) && "location undefined");
989 // For access to concrete addresses, return UnknownVal. Checks
990 // for null dereferences (and similar errors) are done by checkers, not
992 // FIXME: We can consider lazily symbolicating such memory, but we really
993 // should defer this when we can reason easily about symbolicating arrays
995 if (isa<loc::ConcreteInt>(L)) {
998 if (!isa<loc::MemRegionVal>(L)) {
1002 const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion();
1004 if (isa<AllocaRegion>(MR) ||
1005 isa<SymbolicRegion>(MR) ||
1006 isa<CodeTextRegion>(MR)) {
1008 if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
1009 T = TR->getLocationType();
1011 const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
1012 T = SR->getSymbol()->getType(Ctx);
1015 MR = GetElementZeroRegion(MR, T);
1018 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1019 // instead of 'Loc', and have the other Loc cases handled at a higher level.
1020 const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1021 QualType RTy = R->getValueType();
1023 // FIXME: We should eventually handle funny addressing. e.g.:
1027 // char *q = (char*) p;
1028 // char c = *q; // returns the first byte of 'x'.
1030 // Such funny addressing will occur due to layering of regions.
1032 if (RTy->isStructureOrClassType())
1033 return getBindingForStruct(store, R);
1035 // FIXME: Handle unions.
1036 if (RTy->isUnionType())
1037 return UnknownVal();
1039 if (RTy->isArrayType())
1040 return getBindingForArray(store, R);
1042 // FIXME: handle Vector types.
1043 if (RTy->isVectorType())
1044 return UnknownVal();
1046 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1047 return CastRetrievedVal(getBindingForField(store, FR), FR, T, false);
1049 if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1050 // FIXME: Here we actually perform an implicit conversion from the loaded
1051 // value to the element type. Eventually we want to compose these values
1052 // more intelligently. For example, an 'element' can encompass multiple
1053 // bound regions (e.g., several bound bytes), or could be a subset of
1055 return CastRetrievedVal(getBindingForElement(store, ER), ER, T, false);
1058 if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1059 // FIXME: Here we actually perform an implicit conversion from the loaded
1060 // value to the ivar type. What we should model is stores to ivars
1061 // that blow past the extent of the ivar. If the address of the ivar is
1062 // reinterpretted, it is possible we stored a different value that could
1063 // fit within the ivar. Either we need to cast these when storing them
1064 // or reinterpret them lazily (as we do here).
1065 return CastRetrievedVal(getBindingForObjCIvar(store, IVR), IVR, T, false);
1068 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1069 // FIXME: Here we actually perform an implicit conversion from the loaded
1070 // value to the variable type. What we should model is stores to variables
1071 // that blow past the extent of the variable. If the address of the
1072 // variable is reinterpretted, it is possible we stored a different value
1073 // that could fit within the variable. Either we need to cast these when
1074 // storing them or reinterpret them lazily (as we do here).
1075 return CastRetrievedVal(getBindingForVar(store, VR), VR, T, false);
1078 RegionBindings B = GetRegionBindings(store);
1079 const SVal *V = lookup(B, R, BindingKey::Direct);
1081 // Check if the region has a binding.
1085 // The location does not have a bound value. This means that it has
1086 // the value it had upon its creation and/or entry to the analyzed
1087 // function/method. These are either symbolic values or 'undefined'.
1088 if (R->hasStackNonParametersStorage()) {
1089 // All stack variables are considered to have undefined values
1090 // upon creation. All heap allocated blocks are considered to
1091 // have undefined values as well unless they are explicitly bound
1092 // to specific values.
1093 return UndefinedVal();
1096 // All other values are symbolic.
1097 return svalBuilder.getRegionValueSymbolVal(R);
1100 std::pair<Store, const MemRegion *>
1101 RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R,
1102 const MemRegion *originalRegion) {
1104 if (originalRegion != R) {
1105 if (Optional<SVal> OV = getDefaultBinding(B, R)) {
1106 if (const nonloc::LazyCompoundVal *V =
1107 dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer()))
1108 return std::make_pair(V->getStore(), V->getRegion());
1112 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1113 const std::pair<Store, const MemRegion *> &X =
1114 GetLazyBinding(B, ER->getSuperRegion(), originalRegion);
1117 return std::make_pair(X.first,
1118 MRMgr.getElementRegionWithSuper(ER, X.second));
1120 else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1121 const std::pair<Store, const MemRegion *> &X =
1122 GetLazyBinding(B, FR->getSuperRegion(), originalRegion);
1125 return std::make_pair(X.first,
1126 MRMgr.getFieldRegionWithSuper(FR, X.second));
1128 // C++ base object region is another kind of region that we should blast
1129 // through to look for lazy compound value. It is like a field region.
1130 else if (const CXXBaseObjectRegion *baseReg =
1131 dyn_cast<CXXBaseObjectRegion>(R)) {
1132 const std::pair<Store, const MemRegion *> &X =
1133 GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion);
1136 return std::make_pair(X.first,
1137 MRMgr.getCXXBaseObjectRegionWithSuper(baseReg, X.second));
1140 // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is
1141 // possible for a valid lazy binding.
1142 return std::make_pair((Store) 0, (const MemRegion *) 0);
1145 SVal RegionStoreManager::getBindingForElement(Store store,
1146 const ElementRegion* R) {
1147 // Check if the region has a binding.
1148 RegionBindings B = GetRegionBindings(store);
1149 if (const Optional<SVal> &V = getDirectBinding(B, R))
1152 const MemRegion* superR = R->getSuperRegion();
1154 // Check if the region is an element region of a string literal.
1155 if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
1156 // FIXME: Handle loads from strings where the literal is treated as
1157 // an integer, e.g., *((unsigned int*)"hello")
1158 QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1159 if (T != Ctx.getCanonicalType(R->getElementType()))
1160 return UnknownVal();
1162 const StringLiteral *Str = StrR->getStringLiteral();
1163 SVal Idx = R->getIndex();
1164 if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) {
1165 int64_t i = CI->getValue().getSExtValue();
1166 // Abort on string underrun. This can be possible by arbitrary
1167 // clients of getBindingForElement().
1169 return UndefinedVal();
1170 int64_t length = Str->getLength();
1171 // Technically, only i == length is guaranteed to be null.
1172 // However, such overflows should be caught before reaching this point;
1173 // the only time such an access would be made is if a string literal was
1174 // used to initialize a larger array.
1175 char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
1176 return svalBuilder.makeIntVal(c, T);
1180 // Check for loads from a code text region. For such loads, just give up.
1181 if (isa<CodeTextRegion>(superR))
1182 return UnknownVal();
1184 // Handle the case where we are indexing into a larger scalar object.
1185 // For example, this handles:
1189 // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1190 const RegionRawOffset &O = R->getAsArrayOffset();
1192 // If we cannot reason about the offset, return an unknown value.
1194 return UnknownVal();
1196 if (const TypedValueRegion *baseR =
1197 dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1198 QualType baseT = baseR->getValueType();
1199 if (baseT->isScalarType()) {
1200 QualType elemT = R->getElementType();
1201 if (elemT->isScalarType()) {
1202 if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1203 if (const Optional<SVal> &V = getDirectBinding(B, superR)) {
1204 if (SymbolRef parentSym = V->getAsSymbol())
1205 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1207 if (V->isUnknownOrUndef())
1209 // Other cases: give up. We are indexing into a larger object
1210 // that has some value, but we don't know how to handle that yet.
1211 return UnknownVal();
1217 return getBindingForFieldOrElementCommon(store, R, R->getElementType(),
1221 SVal RegionStoreManager::getBindingForField(Store store,
1222 const FieldRegion* R) {
1224 // Check if the region has a binding.
1225 RegionBindings B = GetRegionBindings(store);
1226 if (const Optional<SVal> &V = getDirectBinding(B, R))
1229 QualType Ty = R->getValueType();
1230 return getBindingForFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
1234 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindings B,
1235 const MemRegion *superR,
1236 const TypedValueRegion *R,
1239 if (const Optional<SVal> &D = getDefaultBinding(B, superR)) {
1240 const SVal &val = D.getValue();
1241 if (SymbolRef parentSym = val.getAsSymbol())
1242 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1244 if (val.isZeroConstant())
1245 return svalBuilder.makeZeroVal(Ty);
1247 if (val.isUnknownOrUndef())
1250 // Lazy bindings are handled later.
1251 if (isa<nonloc::LazyCompoundVal>(val))
1252 return Optional<SVal>();
1254 llvm_unreachable("Unknown default value");
1257 return Optional<SVal>();
1260 SVal RegionStoreManager::getLazyBinding(const MemRegion *lazyBindingRegion,
1261 Store lazyBindingStore) {
1262 if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion))
1263 return getBindingForElement(lazyBindingStore, ER);
1265 return getBindingForField(lazyBindingStore,
1266 cast<FieldRegion>(lazyBindingRegion));
1269 SVal RegionStoreManager::getBindingForFieldOrElementCommon(Store store,
1270 const TypedValueRegion *R,
1272 const MemRegion *superR) {
1274 // At this point we have already checked in either getBindingForElement or
1275 // getBindingForField if 'R' has a direct binding.
1276 RegionBindings B = GetRegionBindings(store);
1278 // Record whether or not we see a symbolic index. That can completely
1279 // be out of scope of our lookup.
1280 bool hasSymbolicIndex = false;
1283 if (const Optional<SVal> &D =
1284 getBindingForDerivedDefaultValue(B, superR, R, Ty))
1287 if (const ElementRegion *ER = dyn_cast<ElementRegion>(superR)) {
1288 NonLoc index = ER->getIndex();
1289 if (!index.isConstant())
1290 hasSymbolicIndex = true;
1293 // If our super region is a field or element itself, walk up the region
1294 // hierarchy to see if there is a default value installed in an ancestor.
1295 if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) {
1296 superR = SR->getSuperRegion();
1303 Store lazyBindingStore = NULL;
1304 const MemRegion *lazyBindingRegion = NULL;
1305 llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R);
1307 if (lazyBindingRegion)
1308 return getLazyBinding(lazyBindingRegion, lazyBindingStore);
1310 if (R->hasStackNonParametersStorage()) {
1311 if (isa<ElementRegion>(R)) {
1312 // Currently we don't reason specially about Clang-style vectors. Check
1313 // if superR is a vector and if so return Unknown.
1314 if (const TypedValueRegion *typedSuperR =
1315 dyn_cast<TypedValueRegion>(superR)) {
1316 if (typedSuperR->getValueType()->isVectorType())
1317 return UnknownVal();
1321 // FIXME: We also need to take ElementRegions with symbolic indexes into
1322 // account. This case handles both directly accessing an ElementRegion
1323 // with a symbolic offset, but also fields within an element with
1324 // a symbolic offset.
1325 if (hasSymbolicIndex)
1326 return UnknownVal();
1328 return UndefinedVal();
1331 // All other values are symbolic.
1332 return svalBuilder.getRegionValueSymbolVal(R);
1335 SVal RegionStoreManager::getBindingForObjCIvar(Store store,
1336 const ObjCIvarRegion* R) {
1338 // Check if the region has a binding.
1339 RegionBindings B = GetRegionBindings(store);
1341 if (const Optional<SVal> &V = getDirectBinding(B, R))
1344 const MemRegion *superR = R->getSuperRegion();
1346 // Check if the super region has a default binding.
1347 if (const Optional<SVal> &V = getDefaultBinding(B, superR)) {
1348 if (SymbolRef parentSym = V->getAsSymbol())
1349 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1351 // Other cases: give up.
1352 return UnknownVal();
1355 return getBindingForLazySymbol(R);
1358 SVal RegionStoreManager::getBindingForVar(Store store, const VarRegion *R) {
1360 // Check if the region has a binding.
1361 RegionBindings B = GetRegionBindings(store);
1363 if (const Optional<SVal> &V = getDirectBinding(B, R))
1366 // Lazily derive a value for the VarRegion.
1367 const VarDecl *VD = R->getDecl();
1368 QualType T = VD->getType();
1369 const MemSpaceRegion *MS = R->getMemorySpace();
1371 if (isa<UnknownSpaceRegion>(MS) ||
1372 isa<StackArgumentsSpaceRegion>(MS))
1373 return svalBuilder.getRegionValueSymbolVal(R);
1375 if (isa<GlobalsSpaceRegion>(MS)) {
1376 if (isa<NonStaticGlobalSpaceRegion>(MS)) {
1377 // Is 'VD' declared constant? If so, retrieve the constant value.
1378 QualType CT = Ctx.getCanonicalType(T);
1379 if (CT.isConstQualified()) {
1380 const Expr *Init = VD->getInit();
1381 // Do the null check first, as we want to call 'IgnoreParenCasts'.
1383 if (const IntegerLiteral *IL =
1384 dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) {
1385 const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL);
1386 return svalBuilder.evalCast(V, Init->getType(), IL->getType());
1390 if (const Optional<SVal> &V
1391 = getBindingForDerivedDefaultValue(B, MS, R, CT))
1392 return V.getValue();
1394 return svalBuilder.getRegionValueSymbolVal(R);
1397 if (T->isIntegerType())
1398 return svalBuilder.makeIntVal(0, T);
1399 if (T->isPointerType())
1400 return svalBuilder.makeNull();
1402 return UnknownVal();
1405 return UndefinedVal();
1408 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
1409 // All other values are symbolic.
1410 return svalBuilder.getRegionValueSymbolVal(R);
1413 SVal RegionStoreManager::getBindingForStruct(Store store,
1414 const TypedValueRegion* R) {
1415 assert(R->getValueType()->isStructureOrClassType());
1416 return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
1419 SVal RegionStoreManager::getBindingForArray(Store store,
1420 const TypedValueRegion * R) {
1421 assert(Ctx.getAsConstantArrayType(R->getValueType()));
1422 return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
1425 bool RegionStoreManager::includedInBindings(Store store,
1426 const MemRegion *region) const {
1427 RegionBindings B = GetRegionBindings(store);
1428 region = region->getBaseRegion();
1430 for (RegionBindings::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
1431 const BindingKey &K = it.getKey();
1432 if (region == K.getRegion())
1434 const SVal &D = it.getData();
1435 if (const MemRegion *r = D.getAsRegion())
1442 //===----------------------------------------------------------------------===//
1443 // Binding values to regions.
1444 //===----------------------------------------------------------------------===//
1446 StoreRef RegionStoreManager::Remove(Store store, Loc L) {
1447 if (isa<loc::MemRegionVal>(L))
1448 if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion())
1449 return StoreRef(removeBinding(GetRegionBindings(store),
1450 R).getRootWithoutRetain(),
1453 return StoreRef(store, *this);
1456 StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) {
1457 if (isa<loc::ConcreteInt>(L))
1458 return StoreRef(store, *this);
1460 // If we get here, the location should be a region.
1461 const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion();
1463 // Check if the region is a struct region.
1464 if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R))
1465 if (TR->getValueType()->isStructureOrClassType())
1466 return BindStruct(store, TR, V);
1468 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1469 if (ER->getIndex().isZeroConstant()) {
1470 if (const TypedValueRegion *superR =
1471 dyn_cast<TypedValueRegion>(ER->getSuperRegion())) {
1472 QualType superTy = superR->getValueType();
1473 // For now, just invalidate the fields of the struct/union/class.
1474 // This is for test rdar_test_7185607 in misc-ps-region-store.m.
1475 // FIXME: Precisely handle the fields of the record.
1476 if (superTy->isStructureOrClassType())
1477 return KillStruct(store, superR, UnknownVal());
1481 else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1482 // Binding directly to a symbolic region should be treated as binding
1484 QualType T = SR->getSymbol()->getType(Ctx);
1486 // FIXME: Is this the right way to handle symbols that are references?
1487 if (const PointerType *PT = T->getAs<PointerType>())
1488 T = PT->getPointeeType();
1490 T = T->getAs<ReferenceType>()->getPointeeType();
1492 R = GetElementZeroRegion(SR, T);
1495 // Perform the binding.
1496 RegionBindings B = GetRegionBindings(store);
1497 return StoreRef(addBinding(B, R, BindingKey::Direct,
1498 V).getRootWithoutRetain(), *this);
1501 StoreRef RegionStoreManager::BindDecl(Store store, const VarRegion *VR,
1504 QualType T = VR->getDecl()->getType();
1506 if (T->isArrayType())
1507 return BindArray(store, VR, InitVal);
1508 if (T->isStructureOrClassType())
1509 return BindStruct(store, VR, InitVal);
1511 return Bind(store, svalBuilder.makeLoc(VR), InitVal);
1514 // FIXME: this method should be merged into Bind().
1515 StoreRef RegionStoreManager::BindCompoundLiteral(Store store,
1516 const CompoundLiteralExpr *CL,
1517 const LocationContext *LC,
1519 return Bind(store, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)),
1523 StoreRef RegionStoreManager::setImplicitDefaultValue(Store store,
1526 RegionBindings B = GetRegionBindings(store);
1529 if (Loc::isLocType(T))
1530 V = svalBuilder.makeNull();
1531 else if (T->isIntegerType())
1532 V = svalBuilder.makeZeroVal(T);
1533 else if (T->isStructureOrClassType() || T->isArrayType()) {
1534 // Set the default value to a zero constant when it is a structure
1535 // or array. The type doesn't really matter.
1536 V = svalBuilder.makeZeroVal(Ctx.IntTy);
1539 // We can't represent values of this type, but we still need to set a value
1540 // to record that the region has been initialized.
1541 // If this assertion ever fires, a new case should be added above -- we
1542 // should know how to default-initialize any value we can symbolicate.
1543 assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
1547 return StoreRef(addBinding(B, R, BindingKey::Default,
1548 V).getRootWithoutRetain(), *this);
1551 StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R,
1554 const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
1555 QualType ElementTy = AT->getElementType();
1556 Optional<uint64_t> Size;
1558 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
1559 Size = CAT->getSize().getZExtValue();
1561 // Check if the init expr is a string literal.
1562 if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) {
1563 const StringRegion *S = cast<StringRegion>(MRV->getRegion());
1565 // Treat the string as a lazy compound value.
1566 nonloc::LazyCompoundVal LCV =
1567 cast<nonloc::LazyCompoundVal>(svalBuilder.
1568 makeLazyCompoundVal(StoreRef(store, *this), S));
1569 return CopyLazyBindings(LCV, store, R);
1572 // Handle lazy compound values.
1573 if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&Init))
1574 return CopyLazyBindings(*LCV, store, R);
1576 // Remaining case: explicit compound values.
1578 if (Init.isUnknown())
1579 return setImplicitDefaultValue(store, R, ElementTy);
1581 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
1582 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1585 StoreRef newStore(store, *this);
1586 for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
1587 // The init list might be shorter than the array length.
1591 const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
1592 const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
1594 if (ElementTy->isStructureOrClassType())
1595 newStore = BindStruct(newStore.getStore(), ER, *VI);
1596 else if (ElementTy->isArrayType())
1597 newStore = BindArray(newStore.getStore(), ER, *VI);
1599 newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
1602 // If the init list is shorter than the array length, set the
1603 // array default value.
1604 if (Size.hasValue() && i < Size.getValue())
1605 newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy);
1610 StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R,
1613 if (!Features.supportsFields())
1614 return StoreRef(store, *this);
1616 QualType T = R->getValueType();
1617 assert(T->isStructureOrClassType());
1619 const RecordType* RT = T->getAs<RecordType>();
1620 RecordDecl *RD = RT->getDecl();
1622 if (!RD->isCompleteDefinition())
1623 return StoreRef(store, *this);
1625 // Handle lazy compound values.
1626 if (const nonloc::LazyCompoundVal *LCV=dyn_cast<nonloc::LazyCompoundVal>(&V))
1627 return CopyLazyBindings(*LCV, store, R);
1629 // We may get non-CompoundVal accidentally due to imprecise cast logic or
1630 // that we are binding symbolic struct value. Kill the field values, and if
1631 // the value is symbolic go and bind it as a "default" binding.
1632 if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) {
1633 SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal();
1634 return KillStruct(store, R, SV);
1637 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
1638 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1640 RecordDecl::field_iterator FI, FE;
1641 StoreRef newStore(store, *this);
1643 for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
1648 // Skip any unnamed bitfields to stay in sync with the initializers.
1649 if ((*FI)->isUnnamedBitfield())
1652 QualType FTy = (*FI)->getType();
1653 const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
1655 if (FTy->isArrayType())
1656 newStore = BindArray(newStore.getStore(), FR, *VI);
1657 else if (FTy->isStructureOrClassType())
1658 newStore = BindStruct(newStore.getStore(), FR, *VI);
1660 newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
1664 // There may be fewer values in the initialize list than the fields of struct.
1666 RegionBindings B = GetRegionBindings(newStore.getStore());
1667 B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false));
1668 newStore = StoreRef(B.getRootWithoutRetain(), *this);
1674 StoreRef RegionStoreManager::KillStruct(Store store, const TypedRegion* R,
1676 BindingKey key = BindingKey::Make(R, BindingKey::Default);
1678 // The BindingKey may be "invalid" if we cannot handle the region binding
1679 // explicitly. One example is something like array[index], where index
1680 // is a symbolic value. In such cases, we want to invalidate the entire
1681 // array, as the index assignment could have been to any element. In
1682 // the case of nested symbolic indices, we need to march up the region
1683 // hierarchy untile we reach a region whose binding we can reason about.
1684 const SubRegion *subReg = R;
1686 while (!key.isValid()) {
1687 if (const SubRegion *tmp = dyn_cast<SubRegion>(subReg->getSuperRegion())) {
1689 key = BindingKey::Make(tmp, BindingKey::Default);
1695 // Remove the old bindings, using 'subReg' as the root of all regions
1696 // we will invalidate.
1697 RegionBindings B = GetRegionBindings(store);
1698 OwningPtr<RegionStoreSubRegionMap>
1699 SubRegions(getRegionStoreSubRegionMap(store));
1700 RemoveSubRegionBindings(B, subReg, *SubRegions);
1702 // Set the default value of the struct region to "unknown".
1704 return StoreRef(B.getRootWithoutRetain(), *this);
1706 return StoreRef(addBinding(B, key, DefaultVal).getRootWithoutRetain(), *this);
1709 StoreRef RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V,
1711 const TypedRegion *R) {
1713 // Nuke the old bindings stemming from R.
1714 RegionBindings B = GetRegionBindings(store);
1716 OwningPtr<RegionStoreSubRegionMap>
1717 SubRegions(getRegionStoreSubRegionMap(store));
1719 // B and DVM are updated after the call to RemoveSubRegionBindings.
1720 RemoveSubRegionBindings(B, R, *SubRegions.get());
1722 // Now copy the bindings. This amounts to just binding 'V' to 'R'. This
1723 // results in a zero-copy algorithm.
1724 return StoreRef(addBinding(B, R, BindingKey::Default,
1725 V).getRootWithoutRetain(), *this);
1728 //===----------------------------------------------------------------------===//
1729 // "Raw" retrievals and bindings.
1730 //===----------------------------------------------------------------------===//
1733 RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K,
1737 return RBFactory.add(B, K, V);
1740 RegionBindings RegionStoreManager::addBinding(RegionBindings B,
1742 BindingKey::Kind k, SVal V) {
1743 return addBinding(B, BindingKey::Make(R, k), V);
1746 const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) {
1752 const SVal *RegionStoreManager::lookup(RegionBindings B,
1754 BindingKey::Kind k) {
1755 return lookup(B, BindingKey::Make(R, k));
1758 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
1762 return RBFactory.remove(B, K);
1765 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
1767 BindingKey::Kind k){
1768 return removeBinding(B, BindingKey::Make(R, k));
1771 //===----------------------------------------------------------------------===//
1773 //===----------------------------------------------------------------------===//
1776 class removeDeadBindingsWorker :
1777 public ClusterAnalysis<removeDeadBindingsWorker> {
1778 SmallVector<const SymbolicRegion*, 12> Postponed;
1779 SymbolReaper &SymReaper;
1780 const StackFrameContext *CurrentLCtx;
1783 removeDeadBindingsWorker(RegionStoreManager &rm,
1784 ProgramStateManager &stateMgr,
1785 RegionBindings b, SymbolReaper &symReaper,
1786 const StackFrameContext *LCtx)
1787 : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
1788 /* includeGlobals = */ false),
1789 SymReaper(symReaper), CurrentLCtx(LCtx) {}
1791 // Called by ClusterAnalysis.
1792 void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C);
1793 void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
1795 void VisitBindingKey(BindingKey K);
1796 bool UpdatePostponed();
1797 void VisitBinding(SVal V);
1801 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
1804 if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
1805 if (SymReaper.isLive(VR))
1806 AddToWorkList(baseR, C);
1811 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
1812 if (SymReaper.isLive(SR->getSymbol()))
1813 AddToWorkList(SR, C);
1815 Postponed.push_back(SR);
1820 if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
1821 AddToWorkList(baseR, C);
1825 // CXXThisRegion in the current or parent location context is live.
1826 if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
1827 const StackArgumentsSpaceRegion *StackReg =
1828 cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
1829 const StackFrameContext *RegCtx = StackReg->getStackFrame();
1830 if (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))
1831 AddToWorkList(TR, C);
1835 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
1836 BindingKey *I, BindingKey *E) {
1837 for ( ; I != E; ++I)
1838 VisitBindingKey(*I);
1841 void removeDeadBindingsWorker::VisitBinding(SVal V) {
1842 // Is it a LazyCompoundVal? All referenced regions are live as well.
1843 if (const nonloc::LazyCompoundVal *LCS =
1844 dyn_cast<nonloc::LazyCompoundVal>(&V)) {
1846 const MemRegion *LazyR = LCS->getRegion();
1847 RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
1848 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
1849 const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
1850 if (baseR && baseR->isSubRegionOf(LazyR))
1851 VisitBinding(RI.getData());
1856 // If V is a region, then add it to the worklist.
1857 if (const MemRegion *R = V.getAsRegion())
1860 // Update the set of live symbols.
1861 for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
1863 SymReaper.markLive(*SI);
1866 void removeDeadBindingsWorker::VisitBindingKey(BindingKey K) {
1867 const MemRegion *R = K.getRegion();
1869 // Mark this region "live" by adding it to the worklist. This will cause
1870 // use to visit all regions in the cluster (if we haven't visited them
1872 if (AddToWorkList(R)) {
1873 // Mark the symbol for any live SymbolicRegion as "live". This means we
1874 // should continue to track that symbol.
1875 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(R))
1876 SymReaper.markLive(SymR->getSymbol());
1878 // For BlockDataRegions, enqueue the VarRegions for variables marked
1879 // with __block (passed-by-reference).
1880 // via BlockDeclRefExprs.
1881 if (const BlockDataRegion *BD = dyn_cast<BlockDataRegion>(R)) {
1882 for (BlockDataRegion::referenced_vars_iterator
1883 RI = BD->referenced_vars_begin(), RE = BD->referenced_vars_end();
1885 if ((*RI)->getDecl()->getAttr<BlocksAttr>())
1889 // No possible data bindings on a BlockDataRegion.
1894 // Visit the data binding for K.
1895 if (const SVal *V = RM.lookup(B, K))
1899 bool removeDeadBindingsWorker::UpdatePostponed() {
1900 // See if any postponed SymbolicRegions are actually live now, after
1901 // having done a scan.
1902 bool changed = false;
1904 for (SmallVectorImpl<const SymbolicRegion*>::iterator
1905 I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
1906 if (const SymbolicRegion *SR = cast_or_null<SymbolicRegion>(*I)) {
1907 if (SymReaper.isLive(SR->getSymbol())) {
1908 changed |= AddToWorkList(SR);
1917 StoreRef RegionStoreManager::removeDeadBindings(Store store,
1918 const StackFrameContext *LCtx,
1919 SymbolReaper& SymReaper) {
1920 RegionBindings B = GetRegionBindings(store);
1921 removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
1922 W.GenerateClusters();
1924 // Enqueue the region roots onto the worklist.
1925 for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
1926 E = SymReaper.region_end(); I != E; ++I) {
1927 W.AddToWorkList(*I);
1930 do W.RunWorkList(); while (W.UpdatePostponed());
1932 // We have now scanned the store, marking reachable regions and symbols
1933 // as live. We now remove all the regions that are dead from the store
1934 // as well as update DSymbols with the set symbols that are now dead.
1935 for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1936 const BindingKey &K = I.getKey();
1938 // If the cluster has been visited, we know the region has been marked.
1939 if (W.isVisited(K.getRegion()))
1942 // Remove the dead entry.
1943 B = removeBinding(B, K);
1945 // Mark all non-live symbols that this binding references as dead.
1946 if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(K.getRegion()))
1947 SymReaper.maybeDead(SymR->getSymbol());
1949 SVal X = I.getData();
1950 SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
1951 for (; SI != SE; ++SI)
1952 SymReaper.maybeDead(*SI);
1955 return StoreRef(B.getRootWithoutRetain(), *this);
1959 StoreRef RegionStoreManager::enterStackFrame(ProgramStateRef state,
1960 const LocationContext *callerCtx,
1961 const StackFrameContext *calleeCtx)
1963 FunctionDecl const *FD = cast<FunctionDecl>(calleeCtx->getDecl());
1964 FunctionDecl::param_const_iterator PI = FD->param_begin(),
1965 PE = FD->param_end();
1966 StoreRef store = StoreRef(state->getStore(), *this);
1968 if (CallExpr const *CE = dyn_cast<CallExpr>(calleeCtx->getCallSite())) {
1969 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1971 // Copy the arg expression value to the arg variables. We check that
1972 // PI != PE because the actual number of arguments may be different than
1973 // the function declaration.
1974 for (; AI != AE && PI != PE; ++AI, ++PI) {
1975 SVal ArgVal = state->getSVal(*AI, callerCtx);
1976 store = Bind(store.getStore(),
1977 svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, calleeCtx)),
1980 } else if (const CXXConstructExpr *CE =
1981 dyn_cast<CXXConstructExpr>(calleeCtx->getCallSite())) {
1982 CXXConstructExpr::const_arg_iterator AI = CE->arg_begin(),
1985 // Copy the arg expression value to the arg variables.
1986 for (; AI != AE; ++AI, ++PI) {
1987 SVal ArgVal = state->getSVal(*AI, callerCtx);
1988 store = Bind(store.getStore(),
1989 svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, calleeCtx)),
1993 assert(isa<CXXDestructorDecl>(calleeCtx->getDecl()));
1998 //===----------------------------------------------------------------------===//
2000 //===----------------------------------------------------------------------===//
2002 void RegionStoreManager::print(Store store, raw_ostream &OS,
2003 const char* nl, const char *sep) {
2004 RegionBindings B = GetRegionBindings(store);
2005 OS << "Store (direct and default bindings):" << nl;
2007 for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
2008 OS << ' ' << I.getKey() << " : " << I.getData() << nl;