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