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