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