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