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