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