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