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