1 //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
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
7 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/ASTMatchers/ASTMatchFinder.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/AnalysisDeclContext.h"
22 #include "clang/Basic/JsonSupport.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
30 #include "llvm/ADT/ImmutableMap.h"
31 #include "llvm/Support/raw_ostream.h"
35 using namespace clang
;
38 //===----------------------------------------------------------------------===//
39 // Representation of binding keys.
40 //===----------------------------------------------------------------------===//
45 enum Kind
{ Default
= 0x0, Direct
= 0x1 };
47 enum { Symbolic
= 0x2 };
49 llvm::PointerIntPair
<const MemRegion
*, 2> P
;
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");
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
)) &&
71 bool isDirect() const { return P
.getInt() & Direct
; }
72 bool hasSymbolicOffset() const { return P
.getInt() & Symbolic
; }
74 const MemRegion
*getRegion() const { return P
.getPointer(); }
75 uint64_t getOffset() const {
76 assert(!hasSymbolicOffset());
80 const SubRegion
*getConcreteOffsetRegion() const {
81 assert(hasSymbolicOffset());
82 return reinterpret_cast<const SubRegion
*>(static_cast<uintptr_t>(Data
));
85 const MemRegion
*getBaseRegion() const {
86 if (hasSymbolicOffset())
87 return getConcreteOffsetRegion()->getBaseRegion();
88 return getRegion()->getBaseRegion();
91 void Profile(llvm::FoldingSetNodeID
& ID
) const {
92 ID
.AddPointer(P
.getOpaqueValue());
96 static BindingKey
Make(const MemRegion
*R
, Kind k
);
98 bool operator<(const BindingKey
&X
) const {
99 if (P
.getOpaqueValue() < X
.P
.getOpaqueValue())
101 if (P
.getOpaqueValue() > X
.P
.getOpaqueValue())
103 return Data
< X
.Data
;
106 bool operator==(const BindingKey
&X
) const {
107 return P
.getOpaqueValue() == X
.P
.getOpaqueValue() &&
111 LLVM_DUMP_METHOD
void dump() const;
113 } // end anonymous namespace
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
);
120 return BindingKey(RO
.getRegion(), RO
.getOffset(), k
);
124 static inline raw_ostream
&operator<<(raw_ostream
&Out
, BindingKey K
) {
125 Out
<< "\"kind\": \"" << (K
.isDirect() ? "Direct" : "Default")
126 << "\", \"offset\": ";
128 if (!K
.hasSymbolicOffset())
129 Out
<< K
.getOffset();
138 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
139 void BindingKey::dump() const { llvm::errs() << *this; }
142 //===----------------------------------------------------------------------===//
143 // Actual Store type.
144 //===----------------------------------------------------------------------===//
146 typedef llvm::ImmutableMap
<BindingKey
, SVal
> ClusterBindings
;
147 typedef llvm::ImmutableMapRef
<BindingKey
, SVal
> ClusterBindingsRef
;
148 typedef std::pair
<BindingKey
, SVal
> BindingPair
;
150 typedef llvm::ImmutableMap
<const MemRegion
*, ClusterBindings
>
154 class RegionBindingsRef
: public llvm::ImmutableMapRef
<const MemRegion
*,
156 ClusterBindings::Factory
*CBFactory
;
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.
170 typedef llvm::ImmutableMapRef
<const MemRegion
*, ClusterBindings
>
173 RegionBindingsRef(ClusterBindings::Factory
&CBFactory
,
174 const RegionBindings::TreeTy
*T
,
175 RegionBindings::TreeTy::Factory
*F
,
177 : llvm::ImmutableMapRef
<const MemRegion
*, ClusterBindings
>(T
, F
),
178 CBFactory(&CBFactory
), IsMainAnalysis(IsMainAnalysis
) {}
180 RegionBindingsRef(const ParentTy
&P
,
181 ClusterBindings::Factory
&CBFactory
,
183 : llvm::ImmutableMapRef
<const MemRegion
*, ClusterBindings
>(P
),
184 CBFactory(&CBFactory
), IsMainAnalysis(IsMainAnalysis
) {}
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
);
191 RegionBindingsRef
remove(key_type_ref K
) const {
192 return RegionBindingsRef(static_cast<const ParentTy
*>(this)->remove(K
),
193 *CBFactory
, IsMainAnalysis
);
196 RegionBindingsRef
addBinding(BindingKey K
, SVal V
) const;
198 RegionBindingsRef
addBinding(const MemRegion
*R
,
199 BindingKey::Kind k
, SVal V
) const;
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
;
205 RegionBindingsRef
removeBinding(BindingKey K
);
207 RegionBindingsRef
removeBinding(const MemRegion
*R
,
210 RegionBindingsRef
removeBinding(const MemRegion
*R
) {
211 return removeBinding(R
, BindingKey::Direct
).
212 removeBinding(R
, BindingKey::Default
);
215 std::optional
<SVal
> getDirectBinding(const MemRegion
*R
) const;
217 /// getDefaultBinding - Returns an SVal* representing an optional default
218 /// binding associated with a region and its subregions.
219 std::optional
<SVal
> getDefaultBinding(const MemRegion
*R
) const;
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());
228 bool isMainAnalysis() const {
229 return IsMainAnalysis
;
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
;
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);
246 if (std::next(CI
) != CB
.end())
252 Indent(Out
, Space
, IsDot
) << "]}";
253 if (std::next(I
) != end())
259 LLVM_DUMP_METHOD
void dump() const { printJson(llvm::errs()); }
261 } // end anonymous namespace
263 typedef const RegionBindingsRef
& RegionBindingsConstRef
;
266 RegionBindingsRef::getDirectBinding(const MemRegion
*R
) const {
267 const SVal
*V
= lookup(R
, BindingKey::Direct
);
268 return V
? std::optional
<SVal
>(*V
) : std::nullopt
;
272 RegionBindingsRef::getDefaultBinding(const MemRegion
*R
) const {
273 const SVal
*V
= lookup(R
, BindingKey::Default
);
274 return V
? std::optional
<SVal
>(*V
) : std::nullopt
;
277 RegionBindingsRef
RegionBindingsRef::addBinding(BindingKey K
, SVal V
) const {
278 const MemRegion
*Base
= K
.getBaseRegion();
280 const ClusterBindings
*ExistingCluster
= lookup(Base
);
281 ClusterBindings Cluster
=
282 (ExistingCluster
? *ExistingCluster
: CBFactory
->getEmptyMap());
284 ClusterBindings NewCluster
= CBFactory
->add(Cluster
, K
, V
);
285 return add(Base
, NewCluster
);
289 RegionBindingsRef
RegionBindingsRef::addBinding(const MemRegion
*R
,
292 return addBinding(BindingKey::Make(R
, k
), V
);
295 const SVal
*RegionBindingsRef::lookup(BindingKey K
) const {
296 const ClusterBindings
*Cluster
= lookup(K
.getBaseRegion());
299 return Cluster
->lookup(K
);
302 const SVal
*RegionBindingsRef::lookup(const MemRegion
*R
,
303 BindingKey::Kind k
) const {
304 return lookup(BindingKey::Make(R
, k
));
307 RegionBindingsRef
RegionBindingsRef::removeBinding(BindingKey K
) {
308 const MemRegion
*Base
= K
.getBaseRegion();
309 const ClusterBindings
*Cluster
= lookup(Base
);
313 ClusterBindings NewCluster
= CBFactory
->remove(*Cluster
, K
);
314 if (NewCluster
.isEmpty())
316 return add(Base
, NewCluster
);
319 RegionBindingsRef
RegionBindingsRef::removeBinding(const MemRegion
*R
,
321 return removeBinding(BindingKey::Make(R
, k
));
324 //===----------------------------------------------------------------------===//
325 // Main RegionStore logic.
326 //===----------------------------------------------------------------------===//
329 class InvalidateRegionsWorker
;
331 class RegionStoreManager
: public StoreManager
{
333 RegionBindings::Factory RBFactory
;
334 mutable ClusterBindings::Factory CBFactory
;
336 typedef std::vector
<SVal
> SValListTy
;
338 typedef llvm::DenseMap
<const LazyCompoundValData
*,
339 SValListTy
> LazyBindingsMapTy
;
340 LazyBindingsMapTy LazyBindingsMap
;
342 /// The largest number of fields a struct can have and still be
343 /// considered "small".
345 /// This is currently used to decide whether or not it is worth "forcing" a
346 /// LazyCompoundVal on bind.
348 /// This is controlled by 'region-store-small-struct-limit' option.
349 /// To disable all small-struct-dependent behavior, set the option to "0".
350 unsigned SmallStructLimit
;
352 /// The largest number of element an array can have and still be
353 /// considered "small".
355 /// This is currently used to decide whether or not it is worth "forcing" a
356 /// LazyCompoundVal on bind.
358 /// This is controlled by 'region-store-small-struct-limit' option.
359 /// To disable all small-struct-dependent behavior, set the option to "0".
360 unsigned SmallArrayLimit
;
362 /// A helper used to populate the work list with the given set of
364 void populateWorkList(InvalidateRegionsWorker
&W
,
365 ArrayRef
<SVal
> Values
,
366 InvalidatedRegions
*TopLevelRegions
);
369 RegionStoreManager(ProgramStateManager
&mgr
)
370 : StoreManager(mgr
), RBFactory(mgr
.getAllocator()),
371 CBFactory(mgr
.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) {
372 ExprEngine
&Eng
= StateMgr
.getOwningEngine();
373 AnalyzerOptions
&Options
= Eng
.getAnalysisManager().options
;
374 SmallStructLimit
= Options
.RegionStoreSmallStructLimit
;
375 SmallArrayLimit
= Options
.RegionStoreSmallArrayLimit
;
378 /// setImplicitDefaultValue - Set the default binding for the provided
379 /// MemRegion to the value implicitly defined for compound literals when
380 /// the value is not specified.
381 RegionBindingsRef
setImplicitDefaultValue(RegionBindingsConstRef B
,
382 const MemRegion
*R
, QualType T
);
384 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
385 /// type. 'Array' represents the lvalue of the array being decayed
386 /// to a pointer, and the returned SVal represents the decayed
387 /// version of that lvalue (i.e., a pointer to the first element of
388 /// the array). This is called by ExprEngine when evaluating
389 /// casts from arrays to pointers.
390 SVal
ArrayToPointer(Loc Array
, QualType ElementTy
) override
;
392 /// Creates the Store that correctly represents memory contents before
393 /// the beginning of the analysis of the given top-level stack frame.
394 StoreRef
getInitialStore(const LocationContext
*InitLoc
) override
{
395 bool IsMainAnalysis
= false;
396 if (const auto *FD
= dyn_cast
<FunctionDecl
>(InitLoc
->getDecl()))
397 IsMainAnalysis
= FD
->isMain() && !Ctx
.getLangOpts().CPlusPlus
;
398 return StoreRef(RegionBindingsRef(
399 RegionBindingsRef::ParentTy(RBFactory
.getEmptyMap(), RBFactory
),
400 CBFactory
, IsMainAnalysis
).asStore(), *this);
403 //===-------------------------------------------------------------------===//
404 // Binding values to regions.
405 //===-------------------------------------------------------------------===//
406 RegionBindingsRef
invalidateGlobalRegion(MemRegion::Kind K
,
409 const LocationContext
*LCtx
,
411 InvalidatedRegions
*Invalidated
);
413 StoreRef
invalidateRegions(Store store
,
414 ArrayRef
<SVal
> Values
,
415 const Expr
*E
, unsigned Count
,
416 const LocationContext
*LCtx
,
417 const CallEvent
*Call
,
418 InvalidatedSymbols
&IS
,
419 RegionAndSymbolInvalidationTraits
&ITraits
,
420 InvalidatedRegions
*Invalidated
,
421 InvalidatedRegions
*InvalidatedTopLevel
) override
;
423 bool scanReachableSymbols(Store S
, const MemRegion
*R
,
424 ScanReachableSymbols
&Callbacks
) override
;
426 RegionBindingsRef
removeSubRegionBindings(RegionBindingsConstRef B
,
429 getConstantValFromConstArrayInitializer(RegionBindingsConstRef B
,
430 const ElementRegion
*R
);
432 getSValFromInitListExpr(const InitListExpr
*ILE
,
433 const SmallVector
<uint64_t, 2> &ConcreteOffsets
,
435 SVal
getSValFromStringLiteral(const StringLiteral
*SL
, uint64_t Offset
,
438 public: // Part of public interface to class.
440 StoreRef
Bind(Store store
, Loc LV
, SVal V
) override
{
441 return StoreRef(bind(getRegionBindings(store
), LV
, V
).asStore(), *this);
444 RegionBindingsRef
bind(RegionBindingsConstRef B
, Loc LV
, SVal V
);
446 // BindDefaultInitial is only used to initialize a region with
448 StoreRef
BindDefaultInitial(Store store
, const MemRegion
*R
,
450 RegionBindingsRef B
= getRegionBindings(store
);
451 // Use other APIs when you have to wipe the region that was initialized
453 assert(!(B
.getDefaultBinding(R
) || B
.getDirectBinding(R
)) &&
454 "Double initialization!");
455 B
= B
.addBinding(BindingKey::Make(R
, BindingKey::Default
), V
);
456 return StoreRef(B
.asImmutableMap().getRootWithoutRetain(), *this);
459 // BindDefaultZero is used for zeroing constructors that may accidentally
460 // overwrite existing bindings.
461 StoreRef
BindDefaultZero(Store store
, const MemRegion
*R
) override
{
462 // FIXME: The offsets of empty bases can be tricky because of
463 // of the so called "empty base class optimization".
464 // If a base class has been optimized out
465 // we should not try to create a binding, otherwise we should.
466 // Unfortunately, at the moment ASTRecordLayout doesn't expose
467 // the actual sizes of the empty bases
468 // and trying to infer them from offsets/alignments
469 // seems to be error-prone and non-trivial because of the trailing padding.
470 // As a temporary mitigation we don't create bindings for empty bases.
471 if (const auto *BR
= dyn_cast
<CXXBaseObjectRegion
>(R
))
472 if (BR
->getDecl()->isEmpty())
473 return StoreRef(store
, *this);
475 RegionBindingsRef B
= getRegionBindings(store
);
476 SVal V
= svalBuilder
.makeZeroVal(Ctx
.CharTy
);
477 B
= removeSubRegionBindings(B
, cast
<SubRegion
>(R
));
478 B
= B
.addBinding(BindingKey::Make(R
, BindingKey::Default
), V
);
479 return StoreRef(B
.asImmutableMap().getRootWithoutRetain(), *this);
482 /// Attempt to extract the fields of \p LCV and bind them to the struct region
485 /// This path is used when it seems advantageous to "force" loading the values
486 /// within a LazyCompoundVal to bind memberwise to the struct region, rather
487 /// than using a Default binding at the base of the entire region. This is a
488 /// heuristic attempting to avoid building long chains of LazyCompoundVals.
490 /// \returns The updated store bindings, or \c std::nullopt if binding
491 /// non-lazily would be too expensive.
492 std::optional
<RegionBindingsRef
>
493 tryBindSmallStruct(RegionBindingsConstRef B
, const TypedValueRegion
*R
,
494 const RecordDecl
*RD
, nonloc::LazyCompoundVal LCV
);
496 /// BindStruct - Bind a compound value to a structure.
497 RegionBindingsRef
bindStruct(RegionBindingsConstRef B
,
498 const TypedValueRegion
* R
, SVal V
);
500 /// BindVector - Bind a compound value to a vector.
501 RegionBindingsRef
bindVector(RegionBindingsConstRef B
,
502 const TypedValueRegion
* R
, SVal V
);
504 std::optional
<RegionBindingsRef
>
505 tryBindSmallArray(RegionBindingsConstRef B
, const TypedValueRegion
*R
,
506 const ArrayType
*AT
, nonloc::LazyCompoundVal LCV
);
508 RegionBindingsRef
bindArray(RegionBindingsConstRef B
,
509 const TypedValueRegion
* R
,
512 /// Clears out all bindings in the given region and assigns a new value
513 /// as a Default binding.
514 RegionBindingsRef
bindAggregate(RegionBindingsConstRef B
,
515 const TypedRegion
*R
,
518 /// Create a new store with the specified binding removed.
519 /// \param ST the original store, that is the basis for the new store.
520 /// \param L the location whose binding should be removed.
521 StoreRef
killBinding(Store ST
, Loc L
) override
;
523 void incrementReferenceCount(Store store
) override
{
524 getRegionBindings(store
).manualRetain();
527 /// If the StoreManager supports it, decrement the reference count of
528 /// the specified Store object. If the reference count hits 0, the memory
529 /// associated with the object is recycled.
530 void decrementReferenceCount(Store store
) override
{
531 getRegionBindings(store
).manualRelease();
534 bool includedInBindings(Store store
, const MemRegion
*region
) const override
;
536 /// Return the value bound to specified location in a given state.
538 /// The high level logic for this method is this:
541 /// return L's binding
542 /// else if L is in killset
545 /// if L is on stack or heap
549 SVal
getBinding(Store S
, Loc L
, QualType T
) override
{
550 return getBinding(getRegionBindings(S
), L
, T
);
553 std::optional
<SVal
> getDefaultBinding(Store S
, const MemRegion
*R
) override
{
554 RegionBindingsRef B
= getRegionBindings(S
);
555 // Default bindings are always applied over a base region so look up the
556 // base region's default binding, otherwise the lookup will fail when R
557 // is at an offset from R->getBaseRegion().
558 return B
.getDefaultBinding(R
->getBaseRegion());
561 SVal
getBinding(RegionBindingsConstRef B
, Loc L
, QualType T
= QualType());
563 SVal
getBindingForElement(RegionBindingsConstRef B
, const ElementRegion
*R
);
565 SVal
getBindingForField(RegionBindingsConstRef B
, const FieldRegion
*R
);
567 SVal
getBindingForObjCIvar(RegionBindingsConstRef B
, const ObjCIvarRegion
*R
);
569 SVal
getBindingForVar(RegionBindingsConstRef B
, const VarRegion
*R
);
571 SVal
getBindingForLazySymbol(const TypedValueRegion
*R
);
573 SVal
getBindingForFieldOrElementCommon(RegionBindingsConstRef B
,
574 const TypedValueRegion
*R
,
577 SVal
getLazyBinding(const SubRegion
*LazyBindingRegion
,
578 RegionBindingsRef LazyBinding
);
580 /// Get bindings for the values in a struct and return a CompoundVal, used
581 /// when doing struct copy:
584 /// y's value is retrieved by this method.
585 SVal
getBindingForStruct(RegionBindingsConstRef B
, const TypedValueRegion
*R
);
586 SVal
getBindingForArray(RegionBindingsConstRef B
, const TypedValueRegion
*R
);
587 NonLoc
createLazyBinding(RegionBindingsConstRef B
, const TypedValueRegion
*R
);
589 /// Used to lazily generate derived symbols for bindings that are defined
590 /// implicitly by default bindings in a super region.
592 /// Note that callers may need to specially handle LazyCompoundVals, which
593 /// are returned as is in case the caller needs to treat them differently.
595 getBindingForDerivedDefaultValue(RegionBindingsConstRef B
,
596 const MemRegion
*superR
,
597 const TypedValueRegion
*R
, QualType Ty
);
599 /// Get the state and region whose binding this region \p R corresponds to.
601 /// If there is no lazy binding for \p R, the returned value will have a null
602 /// \c second. Note that a null pointer can represents a valid Store.
603 std::pair
<Store
, const SubRegion
*>
604 findLazyBinding(RegionBindingsConstRef B
, const SubRegion
*R
,
605 const SubRegion
*originalRegion
);
607 /// Returns the cached set of interesting SVals contained within a lazy
610 /// The precise value of "interesting" is determined for the purposes of
611 /// RegionStore's internal analysis. It must always contain all regions and
612 /// symbols, but may omit constants and other kinds of SVal.
614 /// In contrast to compound values, LazyCompoundVals are also added
615 /// to the 'interesting values' list in addition to the child interesting
617 const SValListTy
&getInterestingValues(nonloc::LazyCompoundVal LCV
);
619 //===------------------------------------------------------------------===//
621 //===------------------------------------------------------------------===//
623 /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
624 /// It returns a new Store with these values removed.
625 StoreRef
removeDeadBindings(Store store
, const StackFrameContext
*LCtx
,
626 SymbolReaper
& SymReaper
) override
;
628 //===------------------------------------------------------------------===//
630 //===------------------------------------------------------------------===//
632 RegionBindingsRef
getRegionBindings(Store store
) const {
633 llvm::PointerIntPair
<Store
, 1, bool> Ptr
;
634 Ptr
.setFromOpaqueValue(const_cast<void *>(store
));
635 return RegionBindingsRef(
637 static_cast<const RegionBindings::TreeTy
*>(Ptr
.getPointer()),
638 RBFactory
.getTreeFactory(),
642 void printJson(raw_ostream
&Out
, Store S
, const char *NL
= "\n",
643 unsigned int Space
= 0, bool IsDot
= false) const override
;
645 void iterBindings(Store store
, BindingsHandler
& f
) override
{
646 RegionBindingsRef B
= getRegionBindings(store
);
647 for (RegionBindingsRef::iterator I
= B
.begin(), E
= B
.end(); I
!= E
; ++I
) {
648 const ClusterBindings
&Cluster
= I
.getData();
649 for (ClusterBindings::iterator CI
= Cluster
.begin(), CE
= Cluster
.end();
651 const BindingKey
&K
= CI
.getKey();
654 if (const SubRegion
*R
= dyn_cast
<SubRegion
>(K
.getRegion())) {
655 // FIXME: Possibly incorporate the offset?
656 if (!f
.HandleBinding(*this, store
, R
, CI
.getData()))
664 } // end anonymous namespace
666 //===----------------------------------------------------------------------===//
667 // RegionStore creation.
668 //===----------------------------------------------------------------------===//
670 std::unique_ptr
<StoreManager
>
671 ento::CreateRegionStoreManager(ProgramStateManager
&StMgr
) {
672 return std::make_unique
<RegionStoreManager
>(StMgr
);
675 //===----------------------------------------------------------------------===//
676 // Region Cluster analysis.
677 //===----------------------------------------------------------------------===//
680 /// Used to determine which global regions are automatically included in the
681 /// initial worklist of a ClusterAnalysis.
682 enum GlobalsFilterKind
{
683 /// Don't include any global regions.
685 /// Only include system globals.
687 /// Include all global regions.
691 template <typename DERIVED
>
692 class ClusterAnalysis
{
694 typedef llvm::DenseMap
<const MemRegion
*, const ClusterBindings
*> ClusterMap
;
695 typedef const MemRegion
* WorkListElement
;
696 typedef SmallVector
<WorkListElement
, 10> WorkList
;
698 llvm::SmallPtrSet
<const ClusterBindings
*, 16> Visited
;
702 RegionStoreManager
&RM
;
704 SValBuilder
&svalBuilder
;
710 const ClusterBindings
*getCluster(const MemRegion
*R
) {
714 /// Returns true if all clusters in the given memspace should be initially
715 /// included in the cluster analysis. Subclasses may provide their
716 /// own implementation.
717 bool includeEntireMemorySpace(const MemRegion
*Base
) {
722 ClusterAnalysis(RegionStoreManager
&rm
, ProgramStateManager
&StateMgr
,
724 : RM(rm
), Ctx(StateMgr
.getContext()),
725 svalBuilder(StateMgr
.getSValBuilder()), B(std::move(b
)) {}
727 RegionBindingsRef
getRegionBindings() const { return B
; }
729 bool isVisited(const MemRegion
*R
) {
730 return Visited
.count(getCluster(R
));
733 void GenerateClusters() {
734 // Scan the entire set of bindings and record the region clusters.
735 for (RegionBindingsRef::iterator RI
= B
.begin(), RE
= B
.end();
737 const MemRegion
*Base
= RI
.getKey();
739 const ClusterBindings
&Cluster
= RI
.getData();
740 assert(!Cluster
.isEmpty() && "Empty clusters should be removed");
741 static_cast<DERIVED
*>(this)->VisitAddedToCluster(Base
, Cluster
);
743 // If the base's memspace should be entirely invalidated, add the cluster
744 // to the workspace up front.
745 if (static_cast<DERIVED
*>(this)->includeEntireMemorySpace(Base
))
746 AddToWorkList(WorkListElement(Base
), &Cluster
);
750 bool AddToWorkList(WorkListElement E
, const ClusterBindings
*C
) {
751 if (C
&& !Visited
.insert(C
).second
)
757 bool AddToWorkList(const MemRegion
*R
) {
758 return static_cast<DERIVED
*>(this)->AddToWorkList(R
);
762 while (!WL
.empty()) {
763 WorkListElement E
= WL
.pop_back_val();
764 const MemRegion
*BaseR
= E
;
766 static_cast<DERIVED
*>(this)->VisitCluster(BaseR
, getCluster(BaseR
));
770 void VisitAddedToCluster(const MemRegion
*baseR
, const ClusterBindings
&C
) {}
771 void VisitCluster(const MemRegion
*baseR
, const ClusterBindings
*C
) {}
773 void VisitCluster(const MemRegion
*BaseR
, const ClusterBindings
*C
,
775 static_cast<DERIVED
*>(this)->VisitCluster(BaseR
, C
);
780 //===----------------------------------------------------------------------===//
781 // Binding invalidation.
782 //===----------------------------------------------------------------------===//
784 bool RegionStoreManager::scanReachableSymbols(Store S
, const MemRegion
*R
,
785 ScanReachableSymbols
&Callbacks
) {
786 assert(R
== R
->getBaseRegion() && "Should only be called for base regions");
787 RegionBindingsRef B
= getRegionBindings(S
);
788 const ClusterBindings
*Cluster
= B
.lookup(R
);
793 for (ClusterBindings::iterator RI
= Cluster
->begin(), RE
= Cluster
->end();
795 if (!Callbacks
.scan(RI
.getData()))
802 static inline bool isUnionField(const FieldRegion
*FR
) {
803 return FR
->getDecl()->getParent()->isUnion();
806 typedef SmallVector
<const FieldDecl
*, 8> FieldVector
;
808 static void getSymbolicOffsetFields(BindingKey K
, FieldVector
&Fields
) {
809 assert(K
.hasSymbolicOffset() && "Not implemented for concrete offset keys");
811 const MemRegion
*Base
= K
.getConcreteOffsetRegion();
812 const MemRegion
*R
= K
.getRegion();
815 if (const FieldRegion
*FR
= dyn_cast
<FieldRegion
>(R
))
816 if (!isUnionField(FR
))
817 Fields
.push_back(FR
->getDecl());
819 R
= cast
<SubRegion
>(R
)->getSuperRegion();
823 static bool isCompatibleWithFields(BindingKey K
, const FieldVector
&Fields
) {
824 assert(K
.hasSymbolicOffset() && "Not implemented for concrete offset keys");
829 FieldVector FieldsInBindingKey
;
830 getSymbolicOffsetFields(K
, FieldsInBindingKey
);
832 ptrdiff_t Delta
= FieldsInBindingKey
.size() - Fields
.size();
834 return std::equal(FieldsInBindingKey
.begin() + Delta
,
835 FieldsInBindingKey
.end(),
838 return std::equal(FieldsInBindingKey
.begin(), FieldsInBindingKey
.end(),
839 Fields
.begin() - Delta
);
842 /// Collects all bindings in \p Cluster that may refer to bindings within
845 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose
846 /// \c second is the value (an SVal).
848 /// The \p IncludeAllDefaultBindings parameter specifies whether to include
849 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
850 /// an aggregate within a larger aggregate with a default binding.
852 collectSubRegionBindings(SmallVectorImpl
<BindingPair
> &Bindings
,
853 SValBuilder
&SVB
, const ClusterBindings
&Cluster
,
854 const SubRegion
*Top
, BindingKey TopKey
,
855 bool IncludeAllDefaultBindings
) {
856 FieldVector FieldsInSymbolicSubregions
;
857 if (TopKey
.hasSymbolicOffset()) {
858 getSymbolicOffsetFields(TopKey
, FieldsInSymbolicSubregions
);
859 Top
= TopKey
.getConcreteOffsetRegion();
860 TopKey
= BindingKey::Make(Top
, BindingKey::Default
);
863 // Find the length (in bits) of the region being invalidated.
864 uint64_t Length
= UINT64_MAX
;
865 SVal Extent
= Top
->getMemRegionManager().getStaticSize(Top
, SVB
);
866 if (std::optional
<nonloc::ConcreteInt
> ExtentCI
=
867 Extent
.getAs
<nonloc::ConcreteInt
>()) {
868 const llvm::APSInt
&ExtentInt
= ExtentCI
->getValue();
869 assert(ExtentInt
.isNonNegative() || ExtentInt
.isUnsigned());
870 // Extents are in bytes but region offsets are in bits. Be careful!
871 Length
= ExtentInt
.getLimitedValue() * SVB
.getContext().getCharWidth();
872 } else if (const FieldRegion
*FR
= dyn_cast
<FieldRegion
>(Top
)) {
873 if (FR
->getDecl()->isBitField())
874 Length
= FR
->getDecl()->getBitWidthValue(SVB
.getContext());
877 for (ClusterBindings::iterator I
= Cluster
.begin(), E
= Cluster
.end();
879 BindingKey NextKey
= I
.getKey();
880 if (NextKey
.getRegion() == TopKey
.getRegion()) {
881 // FIXME: This doesn't catch the case where we're really invalidating a
882 // region with a symbolic offset. Example:
886 if (NextKey
.getOffset() > TopKey
.getOffset() &&
887 NextKey
.getOffset() - TopKey
.getOffset() < Length
) {
888 // Case 1: The next binding is inside the region we're invalidating.
890 Bindings
.push_back(*I
);
892 } else if (NextKey
.getOffset() == TopKey
.getOffset()) {
893 // Case 2: The next binding is at the same offset as the region we're
894 // invalidating. In this case, we need to leave default bindings alone,
895 // since they may be providing a default value for a regions beyond what
896 // we're invalidating.
897 // FIXME: This is probably incorrect; consider invalidating an outer
898 // struct whose first field is bound to a LazyCompoundVal.
899 if (IncludeAllDefaultBindings
|| NextKey
.isDirect())
900 Bindings
.push_back(*I
);
903 } else if (NextKey
.hasSymbolicOffset()) {
904 const MemRegion
*Base
= NextKey
.getConcreteOffsetRegion();
905 if (Top
->isSubRegionOf(Base
) && Top
!= Base
) {
906 // Case 3: The next key is symbolic and we just changed something within
907 // its concrete region. We don't know if the binding is still valid, so
908 // we'll be conservative and include it.
909 if (IncludeAllDefaultBindings
|| NextKey
.isDirect())
910 if (isCompatibleWithFields(NextKey
, FieldsInSymbolicSubregions
))
911 Bindings
.push_back(*I
);
912 } else if (const SubRegion
*BaseSR
= dyn_cast
<SubRegion
>(Base
)) {
913 // Case 4: The next key is symbolic, but we changed a known
914 // super-region. In this case the binding is certainly included.
915 if (BaseSR
->isSubRegionOf(Top
))
916 if (isCompatibleWithFields(NextKey
, FieldsInSymbolicSubregions
))
917 Bindings
.push_back(*I
);
924 collectSubRegionBindings(SmallVectorImpl
<BindingPair
> &Bindings
,
925 SValBuilder
&SVB
, const ClusterBindings
&Cluster
,
926 const SubRegion
*Top
, bool IncludeAllDefaultBindings
) {
927 collectSubRegionBindings(Bindings
, SVB
, Cluster
, Top
,
928 BindingKey::Make(Top
, BindingKey::Default
),
929 IncludeAllDefaultBindings
);
933 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B
,
934 const SubRegion
*Top
) {
935 BindingKey TopKey
= BindingKey::Make(Top
, BindingKey::Default
);
936 const MemRegion
*ClusterHead
= TopKey
.getBaseRegion();
938 if (Top
== ClusterHead
) {
939 // We can remove an entire cluster's bindings all in one go.
940 return B
.remove(Top
);
943 const ClusterBindings
*Cluster
= B
.lookup(ClusterHead
);
945 // If we're invalidating a region with a symbolic offset, we need to make
946 // sure we don't treat the base region as uninitialized anymore.
947 if (TopKey
.hasSymbolicOffset()) {
948 const SubRegion
*Concrete
= TopKey
.getConcreteOffsetRegion();
949 return B
.addBinding(Concrete
, BindingKey::Default
, UnknownVal());
954 SmallVector
<BindingPair
, 32> Bindings
;
955 collectSubRegionBindings(Bindings
, svalBuilder
, *Cluster
, Top
, TopKey
,
956 /*IncludeAllDefaultBindings=*/false);
958 ClusterBindingsRef
Result(*Cluster
, CBFactory
);
959 for (SmallVectorImpl
<BindingPair
>::const_iterator I
= Bindings
.begin(),
962 Result
= Result
.remove(I
->first
);
964 // If we're invalidating a region with a symbolic offset, we need to make sure
965 // we don't treat the base region as uninitialized anymore.
966 // FIXME: This isn't very precise; see the example in
967 // collectSubRegionBindings.
968 if (TopKey
.hasSymbolicOffset()) {
969 const SubRegion
*Concrete
= TopKey
.getConcreteOffsetRegion();
970 Result
= Result
.add(BindingKey::Make(Concrete
, BindingKey::Default
),
974 if (Result
.isEmpty())
975 return B
.remove(ClusterHead
);
976 return B
.add(ClusterHead
, Result
.asImmutableMap());
980 class InvalidateRegionsWorker
: public ClusterAnalysis
<InvalidateRegionsWorker
>
984 const LocationContext
*LCtx
;
985 InvalidatedSymbols
&IS
;
986 RegionAndSymbolInvalidationTraits
&ITraits
;
987 StoreManager::InvalidatedRegions
*Regions
;
988 GlobalsFilterKind GlobalsFilter
;
990 InvalidateRegionsWorker(RegionStoreManager
&rm
,
991 ProgramStateManager
&stateMgr
,
993 const Expr
*ex
, unsigned count
,
994 const LocationContext
*lctx
,
995 InvalidatedSymbols
&is
,
996 RegionAndSymbolInvalidationTraits
&ITraitsIn
,
997 StoreManager::InvalidatedRegions
*r
,
998 GlobalsFilterKind GFK
)
999 : ClusterAnalysis
<InvalidateRegionsWorker
>(rm
, stateMgr
, b
),
1000 Ex(ex
), Count(count
), LCtx(lctx
), IS(is
), ITraits(ITraitsIn
), Regions(r
),
1001 GlobalsFilter(GFK
) {}
1003 void VisitCluster(const MemRegion
*baseR
, const ClusterBindings
*C
);
1004 void VisitBinding(SVal V
);
1006 using ClusterAnalysis::AddToWorkList
;
1008 bool AddToWorkList(const MemRegion
*R
);
1010 /// Returns true if all clusters in the memory space for \p Base should be
1012 bool includeEntireMemorySpace(const MemRegion
*Base
);
1014 /// Returns true if the memory space of the given region is one of the global
1015 /// regions specially included at the start of invalidation.
1016 bool isInitiallyIncludedGlobalRegion(const MemRegion
*R
);
1020 bool InvalidateRegionsWorker::AddToWorkList(const MemRegion
*R
) {
1021 bool doNotInvalidateSuperRegion
= ITraits
.hasTrait(
1022 R
, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion
);
1023 const MemRegion
*BaseR
= doNotInvalidateSuperRegion
? R
: R
->getBaseRegion();
1024 return AddToWorkList(WorkListElement(BaseR
), getCluster(BaseR
));
1027 void InvalidateRegionsWorker::VisitBinding(SVal V
) {
1028 // A symbol? Mark it touched by the invalidation.
1029 if (SymbolRef Sym
= V
.getAsSymbol())
1032 if (const MemRegion
*R
= V
.getAsRegion()) {
1037 // Is it a LazyCompoundVal? All references get invalidated as well.
1038 if (std::optional
<nonloc::LazyCompoundVal
> LCS
=
1039 V
.getAs
<nonloc::LazyCompoundVal
>()) {
1041 // `getInterestingValues()` returns SVals contained within LazyCompoundVals,
1042 // so there is no need to visit them.
1043 for (SVal V
: RM
.getInterestingValues(*LCS
))
1044 if (!isa
<nonloc::LazyCompoundVal
>(V
))
1051 void InvalidateRegionsWorker::VisitCluster(const MemRegion
*baseR
,
1052 const ClusterBindings
*C
) {
1054 bool PreserveRegionsContents
=
1055 ITraits
.hasTrait(baseR
,
1056 RegionAndSymbolInvalidationTraits::TK_PreserveContents
);
1059 for (ClusterBindings::iterator I
= C
->begin(), E
= C
->end(); I
!= E
; ++I
)
1060 VisitBinding(I
.getData());
1062 // Invalidate regions contents.
1063 if (!PreserveRegionsContents
)
1064 B
= B
.remove(baseR
);
1067 if (const auto *TO
= dyn_cast
<TypedValueRegion
>(baseR
)) {
1068 if (const auto *RD
= TO
->getValueType()->getAsCXXRecordDecl()) {
1070 // Lambdas can affect all static local variables without explicitly
1072 // We invalidate all static locals referenced inside the lambda body.
1073 if (RD
->isLambda() && RD
->getLambdaCallOperator()->getBody()) {
1074 using namespace ast_matchers
;
1076 const char *DeclBind
= "DeclBind";
1077 StatementMatcher RefToStatic
= stmt(hasDescendant(declRefExpr(
1078 to(varDecl(hasStaticStorageDuration()).bind(DeclBind
)))));
1080 match(RefToStatic
, *RD
->getLambdaCallOperator()->getBody(),
1081 RD
->getASTContext());
1083 for (BoundNodes
&Match
: Matches
) {
1084 auto *VD
= Match
.getNodeAs
<VarDecl
>(DeclBind
);
1085 const VarRegion
*ToInvalidate
=
1086 RM
.getRegionManager().getVarRegion(VD
, LCtx
);
1087 AddToWorkList(ToInvalidate
);
1093 // BlockDataRegion? If so, invalidate captured variables that are passed
1095 if (const BlockDataRegion
*BR
= dyn_cast
<BlockDataRegion
>(baseR
)) {
1096 for (BlockDataRegion::referenced_vars_iterator
1097 BI
= BR
->referenced_vars_begin(), BE
= BR
->referenced_vars_end() ;
1099 const VarRegion
*VR
= BI
.getCapturedRegion();
1100 const VarDecl
*VD
= VR
->getDecl();
1101 if (VD
->hasAttr
<BlocksAttr
>() || !VD
->hasLocalStorage()) {
1104 else if (Loc::isLocType(VR
->getValueType())) {
1105 // Map the current bindings to a Store to retrieve the value
1106 // of the binding. If that binding itself is a region, we should
1107 // invalidate that region. This is because a block may capture
1108 // a pointer value, but the thing pointed by that pointer may
1110 SVal V
= RM
.getBinding(B
, loc::MemRegionVal(VR
));
1111 if (std::optional
<Loc
> L
= V
.getAs
<Loc
>()) {
1112 if (const MemRegion
*LR
= L
->getAsRegion())
1121 if (const SymbolicRegion
*SR
= dyn_cast
<SymbolicRegion
>(baseR
))
1122 IS
.insert(SR
->getSymbol());
1124 // Nothing else should be done in the case when we preserve regions context.
1125 if (PreserveRegionsContents
)
1128 // Otherwise, we have a normal data region. Record that we touched the region.
1130 Regions
->push_back(baseR
);
1132 if (isa
<AllocaRegion
, SymbolicRegion
>(baseR
)) {
1133 // Invalidate the region by setting its default value to
1134 // conjured symbol. The type of the symbol is irrelevant.
1135 DefinedOrUnknownSVal V
=
1136 svalBuilder
.conjureSymbolVal(baseR
, Ex
, LCtx
, Ctx
.IntTy
, Count
);
1137 B
= B
.addBinding(baseR
, BindingKey::Default
, V
);
1141 if (!baseR
->isBoundable())
1144 const TypedValueRegion
*TR
= cast
<TypedValueRegion
>(baseR
);
1145 QualType T
= TR
->getValueType();
1147 if (isInitiallyIncludedGlobalRegion(baseR
)) {
1148 // If the region is a global and we are invalidating all globals,
1149 // erasing the entry is good enough. This causes all globals to be lazily
1150 // symbolicated from the same base symbol.
1154 if (T
->isRecordType()) {
1155 // Invalidate the region by setting its default value to
1156 // conjured symbol. The type of the symbol is irrelevant.
1157 DefinedOrUnknownSVal V
= svalBuilder
.conjureSymbolVal(baseR
, Ex
, LCtx
,
1159 B
= B
.addBinding(baseR
, BindingKey::Default
, V
);
1163 if (const ArrayType
*AT
= Ctx
.getAsArrayType(T
)) {
1164 bool doNotInvalidateSuperRegion
= ITraits
.hasTrait(
1166 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion
);
1168 if (doNotInvalidateSuperRegion
) {
1169 // We are not doing blank invalidation of the whole array region so we
1170 // have to manually invalidate each elements.
1171 std::optional
<uint64_t> NumElements
;
1173 // Compute lower and upper offsets for region within array.
1174 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(AT
))
1175 NumElements
= CAT
->getSize().getZExtValue();
1176 if (!NumElements
) // We are not dealing with a constant size array
1177 goto conjure_default
;
1178 QualType ElementTy
= AT
->getElementType();
1179 uint64_t ElemSize
= Ctx
.getTypeSize(ElementTy
);
1180 const RegionOffset
&RO
= baseR
->getAsOffset();
1181 const MemRegion
*SuperR
= baseR
->getBaseRegion();
1182 if (RO
.hasSymbolicOffset()) {
1183 // If base region has a symbolic offset,
1184 // we revert to invalidating the super region.
1186 AddToWorkList(SuperR
);
1187 goto conjure_default
;
1190 uint64_t LowerOffset
= RO
.getOffset();
1191 uint64_t UpperOffset
= LowerOffset
+ *NumElements
* ElemSize
;
1192 bool UpperOverflow
= UpperOffset
< LowerOffset
;
1194 // Invalidate regions which are within array boundaries,
1195 // or have a symbolic offset.
1197 goto conjure_default
;
1199 const ClusterBindings
*C
= B
.lookup(SuperR
);
1201 goto conjure_default
;
1203 for (ClusterBindings::iterator I
= C
->begin(), E
= C
->end(); I
!= E
;
1205 const BindingKey
&BK
= I
.getKey();
1206 std::optional
<uint64_t> ROffset
=
1207 BK
.hasSymbolicOffset() ? std::optional
<uint64_t>() : BK
.getOffset();
1209 // Check offset is not symbolic and within array's boundaries.
1210 // Handles arrays of 0 elements and of 0-sized elements as well.
1212 ((*ROffset
>= LowerOffset
&& *ROffset
< UpperOffset
) ||
1214 (*ROffset
>= LowerOffset
|| *ROffset
< UpperOffset
)) ||
1215 (LowerOffset
== UpperOffset
&& *ROffset
== LowerOffset
))) {
1216 B
= B
.removeBinding(I
.getKey());
1217 // Bound symbolic regions need to be invalidated for dead symbol
1219 SVal V
= I
.getData();
1220 const MemRegion
*R
= V
.getAsRegion();
1221 if (isa_and_nonnull
<SymbolicRegion
>(R
))
1227 // Set the default value of the array to conjured symbol.
1228 DefinedOrUnknownSVal V
=
1229 svalBuilder
.conjureSymbolVal(baseR
, Ex
, LCtx
,
1230 AT
->getElementType(), Count
);
1231 B
= B
.addBinding(baseR
, BindingKey::Default
, V
);
1235 DefinedOrUnknownSVal V
= svalBuilder
.conjureSymbolVal(baseR
, Ex
, LCtx
,
1237 assert(SymbolManager::canSymbolicate(T
) || V
.isUnknown());
1238 B
= B
.addBinding(baseR
, BindingKey::Direct
, V
);
1241 bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
1242 const MemRegion
*R
) {
1243 switch (GlobalsFilter
) {
1246 case GFK_SystemOnly
:
1247 return isa
<GlobalSystemSpaceRegion
>(R
->getMemorySpace());
1249 return isa
<NonStaticGlobalSpaceRegion
>(R
->getMemorySpace());
1252 llvm_unreachable("unknown globals filter");
1255 bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion
*Base
) {
1256 if (isInitiallyIncludedGlobalRegion(Base
))
1259 const MemSpaceRegion
*MemSpace
= Base
->getMemorySpace();
1260 return ITraits
.hasTrait(MemSpace
,
1261 RegionAndSymbolInvalidationTraits::TK_EntireMemSpace
);
1265 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K
,
1268 const LocationContext
*LCtx
,
1269 RegionBindingsRef B
,
1270 InvalidatedRegions
*Invalidated
) {
1271 // Bind the globals memory space to a new symbol that we will use to derive
1272 // the bindings for all globals.
1273 const GlobalsSpaceRegion
*GS
= MRMgr
.getGlobalsRegion(K
);
1274 SVal V
= svalBuilder
.conjureSymbolVal(/* symbolTag = */ (const void*) GS
, Ex
, LCtx
,
1275 /* type does not matter */ Ctx
.IntTy
,
1278 B
= B
.removeBinding(GS
)
1279 .addBinding(BindingKey::Make(GS
, BindingKey::Default
), V
);
1281 // Even if there are no bindings in the global scope, we still need to
1282 // record that we touched it.
1284 Invalidated
->push_back(GS
);
1289 void RegionStoreManager::populateWorkList(InvalidateRegionsWorker
&W
,
1290 ArrayRef
<SVal
> Values
,
1291 InvalidatedRegions
*TopLevelRegions
) {
1292 for (ArrayRef
<SVal
>::iterator I
= Values
.begin(),
1293 E
= Values
.end(); I
!= E
; ++I
) {
1295 if (std::optional
<nonloc::LazyCompoundVal
> LCS
=
1296 V
.getAs
<nonloc::LazyCompoundVal
>()) {
1298 for (SVal S
: getInterestingValues(*LCS
))
1299 if (const MemRegion
*R
= S
.getAsRegion())
1305 if (const MemRegion
*R
= V
.getAsRegion()) {
1306 if (TopLevelRegions
)
1307 TopLevelRegions
->push_back(R
);
1315 RegionStoreManager::invalidateRegions(Store store
,
1316 ArrayRef
<SVal
> Values
,
1317 const Expr
*Ex
, unsigned Count
,
1318 const LocationContext
*LCtx
,
1319 const CallEvent
*Call
,
1320 InvalidatedSymbols
&IS
,
1321 RegionAndSymbolInvalidationTraits
&ITraits
,
1322 InvalidatedRegions
*TopLevelRegions
,
1323 InvalidatedRegions
*Invalidated
) {
1324 GlobalsFilterKind GlobalsFilter
;
1326 if (Call
->isInSystemHeader())
1327 GlobalsFilter
= GFK_SystemOnly
;
1329 GlobalsFilter
= GFK_All
;
1331 GlobalsFilter
= GFK_None
;
1334 RegionBindingsRef B
= getRegionBindings(store
);
1335 InvalidateRegionsWorker
W(*this, StateMgr
, B
, Ex
, Count
, LCtx
, IS
, ITraits
,
1336 Invalidated
, GlobalsFilter
);
1338 // Scan the bindings and generate the clusters.
1339 W
.GenerateClusters();
1341 // Add the regions to the worklist.
1342 populateWorkList(W
, Values
, TopLevelRegions
);
1346 // Return the new bindings.
1347 B
= W
.getRegionBindings();
1349 // For calls, determine which global regions should be invalidated and
1350 // invalidate them. (Note that function-static and immutable globals are never
1351 // invalidated by this.)
1352 // TODO: This could possibly be more precise with modules.
1353 switch (GlobalsFilter
) {
1355 B
= invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind
,
1356 Ex
, Count
, LCtx
, B
, Invalidated
);
1358 case GFK_SystemOnly
:
1359 B
= invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind
,
1360 Ex
, Count
, LCtx
, B
, Invalidated
);
1366 return StoreRef(B
.asStore(), *this);
1369 //===----------------------------------------------------------------------===//
1370 // Location and region casting.
1371 //===----------------------------------------------------------------------===//
1373 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
1374 /// type. 'Array' represents the lvalue of the array being decayed
1375 /// to a pointer, and the returned SVal represents the decayed
1376 /// version of that lvalue (i.e., a pointer to the first element of
1377 /// the array). This is called by ExprEngine when evaluating casts
1378 /// from arrays to pointers.
1379 SVal
RegionStoreManager::ArrayToPointer(Loc Array
, QualType T
) {
1380 if (isa
<loc::ConcreteInt
>(Array
))
1383 if (!isa
<loc::MemRegionVal
>(Array
))
1384 return UnknownVal();
1386 const SubRegion
*R
=
1387 cast
<SubRegion
>(Array
.castAs
<loc::MemRegionVal
>().getRegion());
1388 NonLoc ZeroIdx
= svalBuilder
.makeZeroArrayIndex();
1389 return loc::MemRegionVal(MRMgr
.getElementRegion(T
, ZeroIdx
, R
, Ctx
));
1392 //===----------------------------------------------------------------------===//
1393 // Loading values from regions.
1394 //===----------------------------------------------------------------------===//
1396 SVal
RegionStoreManager::getBinding(RegionBindingsConstRef B
, Loc L
, QualType T
) {
1397 assert(!isa
<UnknownVal
>(L
) && "location unknown");
1398 assert(!isa
<UndefinedVal
>(L
) && "location undefined");
1400 // For access to concrete addresses, return UnknownVal. Checks
1401 // for null dereferences (and similar errors) are done by checkers, not
1403 // FIXME: We can consider lazily symbolicating such memory, but we really
1404 // should defer this when we can reason easily about symbolicating arrays
1406 if (L
.getAs
<loc::ConcreteInt
>()) {
1407 return UnknownVal();
1409 if (!L
.getAs
<loc::MemRegionVal
>()) {
1410 return UnknownVal();
1413 const MemRegion
*MR
= L
.castAs
<loc::MemRegionVal
>().getRegion();
1415 if (isa
<BlockDataRegion
>(MR
)) {
1416 return UnknownVal();
1419 // Auto-detect the binding type.
1421 if (const auto *TVR
= dyn_cast
<TypedValueRegion
>(MR
))
1422 T
= TVR
->getValueType();
1423 else if (const auto *TR
= dyn_cast
<TypedRegion
>(MR
))
1424 T
= TR
->getLocationType()->getPointeeType();
1425 else if (const auto *SR
= dyn_cast
<SymbolicRegion
>(MR
))
1426 T
= SR
->getPointeeStaticType();
1428 assert(!T
.isNull() && "Unable to auto-detect binding type!");
1429 assert(!T
->isVoidType() && "Attempting to dereference a void pointer!");
1431 if (!isa
<TypedValueRegion
>(MR
))
1432 MR
= GetElementZeroRegion(cast
<SubRegion
>(MR
), T
);
1434 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1435 // instead of 'Loc', and have the other Loc cases handled at a higher level.
1436 const TypedValueRegion
*R
= cast
<TypedValueRegion
>(MR
);
1437 QualType RTy
= R
->getValueType();
1439 // FIXME: we do not yet model the parts of a complex type, so treat the
1440 // whole thing as "unknown".
1441 if (RTy
->isAnyComplexType())
1442 return UnknownVal();
1444 // FIXME: We should eventually handle funny addressing. e.g.:
1448 // char *q = (char*) p;
1449 // char c = *q; // returns the first byte of 'x'.
1451 // Such funny addressing will occur due to layering of regions.
1452 if (RTy
->isStructureOrClassType())
1453 return getBindingForStruct(B
, R
);
1455 // FIXME: Handle unions.
1456 if (RTy
->isUnionType())
1457 return createLazyBinding(B
, R
);
1459 if (RTy
->isArrayType()) {
1460 if (RTy
->isConstantArrayType())
1461 return getBindingForArray(B
, R
);
1463 return UnknownVal();
1466 // FIXME: handle Vector types.
1467 if (RTy
->isVectorType())
1468 return UnknownVal();
1470 if (const FieldRegion
* FR
= dyn_cast
<FieldRegion
>(R
))
1471 return svalBuilder
.evalCast(getBindingForField(B
, FR
), T
, QualType
{});
1473 if (const ElementRegion
* ER
= dyn_cast
<ElementRegion
>(R
)) {
1474 // FIXME: Here we actually perform an implicit conversion from the loaded
1475 // value to the element type. Eventually we want to compose these values
1476 // more intelligently. For example, an 'element' can encompass multiple
1477 // bound regions (e.g., several bound bytes), or could be a subset of
1479 return svalBuilder
.evalCast(getBindingForElement(B
, ER
), T
, QualType
{});
1482 if (const ObjCIvarRegion
*IVR
= dyn_cast
<ObjCIvarRegion
>(R
)) {
1483 // FIXME: Here we actually perform an implicit conversion from the loaded
1484 // value to the ivar type. What we should model is stores to ivars
1485 // that blow past the extent of the ivar. If the address of the ivar is
1486 // reinterpretted, it is possible we stored a different value that could
1487 // fit within the ivar. Either we need to cast these when storing them
1488 // or reinterpret them lazily (as we do here).
1489 return svalBuilder
.evalCast(getBindingForObjCIvar(B
, IVR
), T
, QualType
{});
1492 if (const VarRegion
*VR
= dyn_cast
<VarRegion
>(R
)) {
1493 // FIXME: Here we actually perform an implicit conversion from the loaded
1494 // value to the variable type. What we should model is stores to variables
1495 // that blow past the extent of the variable. If the address of the
1496 // variable is reinterpretted, it is possible we stored a different value
1497 // that could fit within the variable. Either we need to cast these when
1498 // storing them or reinterpret them lazily (as we do here).
1499 return svalBuilder
.evalCast(getBindingForVar(B
, VR
), T
, QualType
{});
1502 const SVal
*V
= B
.lookup(R
, BindingKey::Direct
);
1504 // Check if the region has a binding.
1508 // The location does not have a bound value. This means that it has
1509 // the value it had upon its creation and/or entry to the analyzed
1510 // function/method. These are either symbolic values or 'undefined'.
1511 if (R
->hasStackNonParametersStorage()) {
1512 // All stack variables are considered to have undefined values
1513 // upon creation. All heap allocated blocks are considered to
1514 // have undefined values as well unless they are explicitly bound
1515 // to specific values.
1516 return UndefinedVal();
1519 // All other values are symbolic.
1520 return svalBuilder
.getRegionValueSymbolVal(R
);
1523 static QualType
getUnderlyingType(const SubRegion
*R
) {
1525 if (const TypedValueRegion
*TVR
= dyn_cast
<TypedValueRegion
>(R
))
1526 RegionTy
= TVR
->getValueType();
1528 if (const SymbolicRegion
*SR
= dyn_cast
<SymbolicRegion
>(R
))
1529 RegionTy
= SR
->getSymbol()->getType();
1534 /// Checks to see if store \p B has a lazy binding for region \p R.
1536 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1537 /// if there are additional bindings within \p R.
1539 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1540 /// for lazy bindings for super-regions of \p R.
1541 static std::optional
<nonloc::LazyCompoundVal
>
1542 getExistingLazyBinding(SValBuilder
&SVB
, RegionBindingsConstRef B
,
1543 const SubRegion
*R
, bool AllowSubregionBindings
) {
1544 std::optional
<SVal
> V
= B
.getDefaultBinding(R
);
1546 return std::nullopt
;
1548 std::optional
<nonloc::LazyCompoundVal
> LCV
=
1549 V
->getAs
<nonloc::LazyCompoundVal
>();
1551 return std::nullopt
;
1553 // If the LCV is for a subregion, the types might not match, and we shouldn't
1554 // reuse the binding.
1555 QualType RegionTy
= getUnderlyingType(R
);
1556 if (!RegionTy
.isNull() &&
1557 !RegionTy
->isVoidPointerType()) {
1558 QualType SourceRegionTy
= LCV
->getRegion()->getValueType();
1559 if (!SVB
.getContext().hasSameUnqualifiedType(RegionTy
, SourceRegionTy
))
1560 return std::nullopt
;
1563 if (!AllowSubregionBindings
) {
1564 // If there are any other bindings within this region, we shouldn't reuse
1565 // the top-level binding.
1566 SmallVector
<BindingPair
, 16> Bindings
;
1567 collectSubRegionBindings(Bindings
, SVB
, *B
.lookup(R
->getBaseRegion()), R
,
1568 /*IncludeAllDefaultBindings=*/true);
1569 if (Bindings
.size() > 1)
1570 return std::nullopt
;
1576 std::pair
<Store
, const SubRegion
*>
1577 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B
,
1579 const SubRegion
*originalRegion
) {
1580 if (originalRegion
!= R
) {
1581 if (std::optional
<nonloc::LazyCompoundVal
> V
=
1582 getExistingLazyBinding(svalBuilder
, B
, R
, true))
1583 return std::make_pair(V
->getStore(), V
->getRegion());
1586 typedef std::pair
<Store
, const SubRegion
*> StoreRegionPair
;
1587 StoreRegionPair Result
= StoreRegionPair();
1589 if (const ElementRegion
*ER
= dyn_cast
<ElementRegion
>(R
)) {
1590 Result
= findLazyBinding(B
, cast
<SubRegion
>(ER
->getSuperRegion()),
1594 Result
.second
= MRMgr
.getElementRegionWithSuper(ER
, Result
.second
);
1596 } else if (const FieldRegion
*FR
= dyn_cast
<FieldRegion
>(R
)) {
1597 Result
= findLazyBinding(B
, cast
<SubRegion
>(FR
->getSuperRegion()),
1601 Result
.second
= MRMgr
.getFieldRegionWithSuper(FR
, Result
.second
);
1603 } else if (const CXXBaseObjectRegion
*BaseReg
=
1604 dyn_cast
<CXXBaseObjectRegion
>(R
)) {
1605 // C++ base object region is another kind of region that we should blast
1606 // through to look for lazy compound value. It is like a field region.
1607 Result
= findLazyBinding(B
, cast
<SubRegion
>(BaseReg
->getSuperRegion()),
1611 Result
.second
= MRMgr
.getCXXBaseObjectRegionWithSuper(BaseReg
,
1618 /// This is a helper function for `getConstantValFromConstArrayInitializer`.
1620 /// Return an array of extents of the declared array type.
1622 /// E.g. for `int x[1][2][3];` returns { 1, 2, 3 }.
1623 static SmallVector
<uint64_t, 2>
1624 getConstantArrayExtents(const ConstantArrayType
*CAT
) {
1625 assert(CAT
&& "ConstantArrayType should not be null");
1626 CAT
= cast
<ConstantArrayType
>(CAT
->getCanonicalTypeInternal());
1627 SmallVector
<uint64_t, 2> Extents
;
1629 Extents
.push_back(CAT
->getSize().getZExtValue());
1630 } while ((CAT
= dyn_cast
<ConstantArrayType
>(CAT
->getElementType())));
1634 /// This is a helper function for `getConstantValFromConstArrayInitializer`.
1636 /// Return an array of offsets from nested ElementRegions and a root base
1637 /// region. The array is never empty and a base region is never null.
1639 /// E.g. for `Element{Element{Element{VarRegion},1},2},3}` returns { 3, 2, 1 }.
1640 /// This represents an access through indirection: `arr[1][2][3];`
1642 /// \param ER The given (possibly nested) ElementRegion.
1644 /// \note The result array is in the reverse order of indirection expression:
1645 /// arr[1][2][3] -> { 3, 2, 1 }. This helps to provide complexity O(n), where n
1646 /// is a number of indirections. It may not affect performance in real-life
1648 static std::pair
<SmallVector
<SVal
, 2>, const MemRegion
*>
1649 getElementRegionOffsetsWithBase(const ElementRegion
*ER
) {
1650 assert(ER
&& "ConstantArrayType should not be null");
1651 const MemRegion
*Base
;
1652 SmallVector
<SVal
, 2> SValOffsets
;
1654 SValOffsets
.push_back(ER
->getIndex());
1655 Base
= ER
->getSuperRegion();
1656 ER
= dyn_cast
<ElementRegion
>(Base
);
1658 return {SValOffsets
, Base
};
1661 /// This is a helper function for `getConstantValFromConstArrayInitializer`.
1663 /// Convert array of offsets from `SVal` to `uint64_t` in consideration of
1664 /// respective array extents.
1665 /// \param SrcOffsets [in] The array of offsets of type `SVal` in reversed
1666 /// order (expectedly received from `getElementRegionOffsetsWithBase`).
1667 /// \param ArrayExtents [in] The array of extents.
1668 /// \param DstOffsets [out] The array of offsets of type `uint64_t`.
1670 /// - `std::nullopt` for successful convertion.
1671 /// - `UndefinedVal` or `UnknownVal` otherwise. It's expected that this SVal
1672 /// will be returned as a suitable value of the access operation.
1673 /// which should be returned as a correct
1676 /// const int arr[10][20][30] = {}; // ArrayExtents { 10, 20, 30 }
1677 /// int x1 = arr[4][5][6]; // SrcOffsets { NonLoc(6), NonLoc(5), NonLoc(4) }
1678 /// // DstOffsets { 4, 5, 6 }
1679 /// // returns std::nullopt
1680 /// int x2 = arr[42][5][-6]; // returns UndefinedVal
1681 /// int x3 = arr[4][5][x2]; // returns UnknownVal
1682 static std::optional
<SVal
>
1683 convertOffsetsFromSvalToUnsigneds(const SmallVector
<SVal
, 2> &SrcOffsets
,
1684 const SmallVector
<uint64_t, 2> ArrayExtents
,
1685 SmallVector
<uint64_t, 2> &DstOffsets
) {
1686 // Check offsets for being out of bounds.
1687 // C++20 [expr.add] 7.6.6.4 (excerpt):
1688 // If P points to an array element i of an array object x with n
1689 // elements, where i < 0 or i > n, the behavior is undefined.
1690 // Dereferencing is not allowed on the "one past the last
1691 // element", when i == n.
1693 // const int arr[3][2] = {{1, 2}, {3, 4}};
1699 // arr[1][-1]; // UB
1702 // arr[-2][0]; // UB
1703 DstOffsets
.resize(SrcOffsets
.size());
1704 auto ExtentIt
= ArrayExtents
.begin();
1705 auto OffsetIt
= DstOffsets
.begin();
1706 // Reverse `SValOffsets` to make it consistent with `ArrayExtents`.
1707 for (SVal V
: llvm::reverse(SrcOffsets
)) {
1708 if (auto CI
= V
.getAs
<nonloc::ConcreteInt
>()) {
1709 // When offset is out of array's bounds, result is UB.
1710 const llvm::APSInt
&Offset
= CI
->getValue();
1711 if (Offset
.isNegative() || Offset
.uge(*(ExtentIt
++)))
1712 return UndefinedVal();
1713 // Store index in a reversive order.
1714 *(OffsetIt
++) = Offset
.getZExtValue();
1717 // Symbolic index presented. Return Unknown value.
1718 // FIXME: We also need to take ElementRegions with symbolic indexes into
1720 return UnknownVal();
1722 return std::nullopt
;
1725 std::optional
<SVal
> RegionStoreManager::getConstantValFromConstArrayInitializer(
1726 RegionBindingsConstRef B
, const ElementRegion
*R
) {
1727 assert(R
&& "ElementRegion should not be null");
1729 // Treat an n-dimensional array.
1730 SmallVector
<SVal
, 2> SValOffsets
;
1731 const MemRegion
*Base
;
1732 std::tie(SValOffsets
, Base
) = getElementRegionOffsetsWithBase(R
);
1733 const VarRegion
*VR
= dyn_cast
<VarRegion
>(Base
);
1735 return std::nullopt
;
1737 assert(!SValOffsets
.empty() && "getElementRegionOffsets guarantees the "
1738 "offsets vector is not empty.");
1740 // Check if the containing array has an initialized value that we can trust.
1741 // We can trust a const value or a value of a global initializer in main().
1742 const VarDecl
*VD
= VR
->getDecl();
1743 if (!VD
->getType().isConstQualified() &&
1744 !R
->getElementType().isConstQualified() &&
1745 (!B
.isMainAnalysis() || !VD
->hasGlobalStorage()))
1746 return std::nullopt
;
1748 // Array's declaration should have `ConstantArrayType` type, because only this
1749 // type contains an array extent. It may happen that array type can be of
1750 // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType`
1751 // type, we should find the declaration in the redeclarations chain that has
1752 // the initialization expression.
1753 // NOTE: `getAnyInitializer` has an out-parameter, which returns a new `VD`
1754 // from which an initializer is obtained. We replace current `VD` with the new
1755 // `VD`. If the return value of the function is null than `VD` won't be
1757 const Expr
*Init
= VD
->getAnyInitializer(VD
);
1758 // NOTE: If `Init` is non-null, then a new `VD` is non-null for sure. So check
1759 // `Init` for null only and don't worry about the replaced `VD`.
1761 return std::nullopt
;
1763 // Array's declaration should have ConstantArrayType type, because only this
1764 // type contains an array extent.
1765 const ConstantArrayType
*CAT
= Ctx
.getAsConstantArrayType(VD
->getType());
1767 return std::nullopt
;
1769 // Get array extents.
1770 SmallVector
<uint64_t, 2> Extents
= getConstantArrayExtents(CAT
);
1772 // The number of offsets should equal to the numbers of extents,
1773 // otherwise wrong type punning occurred. For instance:
1774 // int arr[1][2][3];
1775 // auto ptr = (int(*)[42])arr;
1776 // auto x = ptr[4][2]; // UB
1777 // FIXME: Should return UndefinedVal.
1778 if (SValOffsets
.size() != Extents
.size())
1779 return std::nullopt
;
1781 SmallVector
<uint64_t, 2> ConcreteOffsets
;
1782 if (std::optional
<SVal
> V
= convertOffsetsFromSvalToUnsigneds(
1783 SValOffsets
, Extents
, ConcreteOffsets
))
1786 // Handle InitListExpr.
1788 // const char arr[4][2] = { { 1, 2 }, { 3 }, 4, 5 };
1789 if (const auto *ILE
= dyn_cast
<InitListExpr
>(Init
))
1790 return getSValFromInitListExpr(ILE
, ConcreteOffsets
, R
->getElementType());
1792 // Handle StringLiteral.
1794 // const char arr[] = "abc";
1795 if (const auto *SL
= dyn_cast
<StringLiteral
>(Init
))
1796 return getSValFromStringLiteral(SL
, ConcreteOffsets
.front(),
1797 R
->getElementType());
1799 // FIXME: Handle CompoundLiteralExpr.
1801 return std::nullopt
;
1804 /// Returns an SVal, if possible, for the specified position of an
1805 /// initialization list.
1807 /// \param ILE The given initialization list.
1808 /// \param Offsets The array of unsigned offsets. E.g. for the expression
1809 /// `int x = arr[1][2][3];` an array should be { 1, 2, 3 }.
1810 /// \param ElemT The type of the result SVal expression.
1811 /// \return Optional SVal for the particular position in the initialization
1812 /// list. E.g. for the list `{{1, 2},[3, 4],{5, 6}, {}}` offsets:
1813 /// - {1, 1} returns SVal{4}, because it's the second position in the second
1815 /// - {3, 0} returns SVal{0}, because there's no explicit value at this
1816 /// position in the sublist.
1818 /// NOTE: Inorder to get a valid SVal, a caller shall guarantee valid offsets
1819 /// for the given initialization list. Otherwise SVal can be an equivalent to 0
1820 /// or lead to assertion.
1821 std::optional
<SVal
> RegionStoreManager::getSValFromInitListExpr(
1822 const InitListExpr
*ILE
, const SmallVector
<uint64_t, 2> &Offsets
,
1824 assert(ILE
&& "InitListExpr should not be null");
1826 for (uint64_t Offset
: Offsets
) {
1827 // C++20 [dcl.init.string] 9.4.2.1:
1828 // An array of ordinary character type [...] can be initialized by [...]
1829 // an appropriately-typed string-literal enclosed in braces.
1831 // const char arr[] = { "abc" };
1832 if (ILE
->isStringLiteralInit())
1833 if (const auto *SL
= dyn_cast
<StringLiteral
>(ILE
->getInit(0)))
1834 return getSValFromStringLiteral(SL
, Offset
, ElemT
);
1836 // C++20 [expr.add] 9.4.17.5 (excerpt):
1837 // i-th array element is value-initialized for each k < i ≤ n,
1838 // where k is an expression-list size and n is an array extent.
1839 if (Offset
>= ILE
->getNumInits())
1840 return svalBuilder
.makeZeroVal(ElemT
);
1842 const Expr
*E
= ILE
->getInit(Offset
);
1843 const auto *IL
= dyn_cast
<InitListExpr
>(E
);
1845 // Return a constant value, if it is presented.
1846 // FIXME: Support other SVals.
1847 return svalBuilder
.getConstantVal(E
);
1849 // Go to the nested initializer list.
1853 "Unhandled InitListExpr sub-expressions or invalid offsets.");
1856 /// Returns an SVal, if possible, for the specified position in a string
1859 /// \param SL The given string literal.
1860 /// \param Offset The unsigned offset. E.g. for the expression
1861 /// `char x = str[42];` an offset should be 42.
1862 /// E.g. for the string "abc" offset:
1863 /// - 1 returns SVal{b}, because it's the second position in the string.
1864 /// - 42 returns SVal{0}, because there's no explicit value at this
1865 /// position in the string.
1866 /// \param ElemT The type of the result SVal expression.
1868 /// NOTE: We return `0` for every offset >= the literal length for array
1869 /// declarations, like:
1870 /// const char str[42] = "123"; // Literal length is 4.
1871 /// char c = str[41]; // Offset is 41.
1872 /// FIXME: Nevertheless, we can't do the same for pointer declaraions, like:
1873 /// const char * const str = "123"; // Literal length is 4.
1874 /// char c = str[41]; // Offset is 41. Returns `0`, but Undef
1876 /// It should be properly handled before reaching this point.
1877 /// The main problem is that we can't distinguish between these declarations,
1878 /// because in case of array we can get the Decl from VarRegion, but in case
1879 /// of pointer the region is a StringRegion, which doesn't contain a Decl.
1880 /// Possible solution could be passing an array extent along with the offset.
1881 SVal
RegionStoreManager::getSValFromStringLiteral(const StringLiteral
*SL
,
1884 assert(SL
&& "StringLiteral should not be null");
1885 // C++20 [dcl.init.string] 9.4.2.3:
1886 // If there are fewer initializers than there are array elements, each
1887 // element not explicitly initialized shall be zero-initialized [dcl.init].
1888 uint32_t Code
= (Offset
>= SL
->getLength()) ? 0 : SL
->getCodeUnit(Offset
);
1889 return svalBuilder
.makeIntVal(Code
, ElemT
);
1892 static std::optional
<SVal
> getDerivedSymbolForBinding(
1893 RegionBindingsConstRef B
, const TypedValueRegion
*BaseRegion
,
1894 const TypedValueRegion
*SubReg
, const ASTContext
&Ctx
, SValBuilder
&SVB
) {
1896 QualType BaseTy
= BaseRegion
->getValueType();
1897 QualType Ty
= SubReg
->getValueType();
1898 if (BaseTy
->isScalarType() && Ty
->isScalarType()) {
1899 if (Ctx
.getTypeSizeInChars(BaseTy
) >= Ctx
.getTypeSizeInChars(Ty
)) {
1900 if (const std::optional
<SVal
> &ParentValue
=
1901 B
.getDirectBinding(BaseRegion
)) {
1902 if (SymbolRef ParentValueAsSym
= ParentValue
->getAsSymbol())
1903 return SVB
.getDerivedRegionValueSymbolVal(ParentValueAsSym
, SubReg
);
1905 if (ParentValue
->isUndef())
1906 return UndefinedVal();
1908 // Other cases: give up. We are indexing into a larger object
1909 // that has some value, but we don't know how to handle that yet.
1910 return UnknownVal();
1914 return std::nullopt
;
1917 SVal
RegionStoreManager::getBindingForElement(RegionBindingsConstRef B
,
1918 const ElementRegion
* R
) {
1919 // Check if the region has a binding.
1920 if (const std::optional
<SVal
> &V
= B
.getDirectBinding(R
))
1923 const MemRegion
* superR
= R
->getSuperRegion();
1925 // Check if the region is an element region of a string literal.
1926 if (const StringRegion
*StrR
= dyn_cast
<StringRegion
>(superR
)) {
1927 // FIXME: Handle loads from strings where the literal is treated as
1928 // an integer, e.g., *((unsigned int*)"hello"). Such loads are UB according
1929 // to C++20 7.2.1.11 [basic.lval].
1930 QualType T
= Ctx
.getAsArrayType(StrR
->getValueType())->getElementType();
1931 if (!Ctx
.hasSameUnqualifiedType(T
, R
->getElementType()))
1932 return UnknownVal();
1933 if (const auto CI
= R
->getIndex().getAs
<nonloc::ConcreteInt
>()) {
1934 const llvm::APSInt
&Idx
= CI
->getValue();
1936 return UndefinedVal();
1937 const StringLiteral
*SL
= StrR
->getStringLiteral();
1938 return getSValFromStringLiteral(SL
, Idx
.getZExtValue(), T
);
1940 } else if (isa
<ElementRegion
, VarRegion
>(superR
)) {
1941 if (std::optional
<SVal
> V
= getConstantValFromConstArrayInitializer(B
, R
))
1945 // Check for loads from a code text region. For such loads, just give up.
1946 if (isa
<CodeTextRegion
>(superR
))
1947 return UnknownVal();
1949 // Handle the case where we are indexing into a larger scalar object.
1950 // For example, this handles:
1954 // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1955 const RegionRawOffset
&O
= R
->getAsArrayOffset();
1957 // If we cannot reason about the offset, return an unknown value.
1959 return UnknownVal();
1961 if (const TypedValueRegion
*baseR
= dyn_cast
<TypedValueRegion
>(O
.getRegion()))
1962 if (auto V
= getDerivedSymbolForBinding(B
, baseR
, R
, Ctx
, svalBuilder
))
1965 return getBindingForFieldOrElementCommon(B
, R
, R
->getElementType());
1968 SVal
RegionStoreManager::getBindingForField(RegionBindingsConstRef B
,
1969 const FieldRegion
* R
) {
1971 // Check if the region has a binding.
1972 if (const std::optional
<SVal
> &V
= B
.getDirectBinding(R
))
1975 // If the containing record was initialized, try to get its constant value.
1976 const FieldDecl
*FD
= R
->getDecl();
1977 QualType Ty
= FD
->getType();
1978 const MemRegion
* superR
= R
->getSuperRegion();
1979 if (const auto *VR
= dyn_cast
<VarRegion
>(superR
)) {
1980 const VarDecl
*VD
= VR
->getDecl();
1981 QualType RecordVarTy
= VD
->getType();
1982 unsigned Index
= FD
->getFieldIndex();
1983 // Either the record variable or the field has an initializer that we can
1984 // trust. We trust initializers of constants and, additionally, respect
1985 // initializers of globals when analyzing main().
1986 if (RecordVarTy
.isConstQualified() || Ty
.isConstQualified() ||
1987 (B
.isMainAnalysis() && VD
->hasGlobalStorage()))
1988 if (const Expr
*Init
= VD
->getAnyInitializer())
1989 if (const auto *InitList
= dyn_cast
<InitListExpr
>(Init
)) {
1990 if (Index
< InitList
->getNumInits()) {
1991 if (const Expr
*FieldInit
= InitList
->getInit(Index
))
1992 if (std::optional
<SVal
> V
= svalBuilder
.getConstantVal(FieldInit
))
1995 return svalBuilder
.makeZeroVal(Ty
);
2000 // Handle the case where we are accessing into a larger scalar object.
2001 // For example, this handles:
2007 // unsigned bits0 : 1;
2008 // unsigned bits2 : 2; // <-- header
2009 // unsigned bits4 : 4;
2011 // int parse(parse_t *p) {
2012 // unsigned copy = p->bits2;
2013 // header *bits = (header *)©
2014 // return bits->b; <-- here
2016 if (const auto *Base
= dyn_cast
<TypedValueRegion
>(R
->getBaseRegion()))
2017 if (auto V
= getDerivedSymbolForBinding(B
, Base
, R
, Ctx
, svalBuilder
))
2020 return getBindingForFieldOrElementCommon(B
, R
, Ty
);
2023 std::optional
<SVal
> RegionStoreManager::getBindingForDerivedDefaultValue(
2024 RegionBindingsConstRef B
, const MemRegion
*superR
,
2025 const TypedValueRegion
*R
, QualType Ty
) {
2027 if (const std::optional
<SVal
> &D
= B
.getDefaultBinding(superR
)) {
2028 const SVal
&val
= *D
;
2029 if (SymbolRef parentSym
= val
.getAsSymbol())
2030 return svalBuilder
.getDerivedRegionValueSymbolVal(parentSym
, R
);
2032 if (val
.isZeroConstant())
2033 return svalBuilder
.makeZeroVal(Ty
);
2035 if (val
.isUnknownOrUndef())
2038 // Lazy bindings are usually handled through getExistingLazyBinding().
2039 // We should unify these two code paths at some point.
2040 if (isa
<nonloc::LazyCompoundVal
, nonloc::CompoundVal
>(val
))
2043 llvm_unreachable("Unknown default value");
2046 return std::nullopt
;
2049 SVal
RegionStoreManager::getLazyBinding(const SubRegion
*LazyBindingRegion
,
2050 RegionBindingsRef LazyBinding
) {
2052 if (const ElementRegion
*ER
= dyn_cast
<ElementRegion
>(LazyBindingRegion
))
2053 Result
= getBindingForElement(LazyBinding
, ER
);
2055 Result
= getBindingForField(LazyBinding
,
2056 cast
<FieldRegion
>(LazyBindingRegion
));
2058 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
2059 // default value for /part/ of an aggregate from a default value for the
2060 // /entire/ aggregate. The most common case of this is when struct Outer
2061 // has as its first member a struct Inner, which is copied in from a stack
2062 // variable. In this case, even if the Outer's default value is symbolic, 0,
2063 // or unknown, it gets overridden by the Inner's default value of undefined.
2065 // This is a general problem -- if the Inner is zero-initialized, the Outer
2066 // will now look zero-initialized. The proper way to solve this is with a
2067 // new version of RegionStore that tracks the extent of a binding as well
2070 // This hack only takes care of the undefined case because that can very
2071 // quickly result in a warning.
2072 if (Result
.isUndef())
2073 Result
= UnknownVal();
2079 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B
,
2080 const TypedValueRegion
*R
,
2083 // At this point we have already checked in either getBindingForElement or
2084 // getBindingForField if 'R' has a direct binding.
2087 Store lazyBindingStore
= nullptr;
2088 const SubRegion
*lazyBindingRegion
= nullptr;
2089 std::tie(lazyBindingStore
, lazyBindingRegion
) = findLazyBinding(B
, R
, R
);
2090 if (lazyBindingRegion
)
2091 return getLazyBinding(lazyBindingRegion
,
2092 getRegionBindings(lazyBindingStore
));
2094 // Record whether or not we see a symbolic index. That can completely
2095 // be out of scope of our lookup.
2096 bool hasSymbolicIndex
= false;
2098 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
2099 // default value for /part/ of an aggregate from a default value for the
2100 // /entire/ aggregate. The most common case of this is when struct Outer
2101 // has as its first member a struct Inner, which is copied in from a stack
2102 // variable. In this case, even if the Outer's default value is symbolic, 0,
2103 // or unknown, it gets overridden by the Inner's default value of undefined.
2105 // This is a general problem -- if the Inner is zero-initialized, the Outer
2106 // will now look zero-initialized. The proper way to solve this is with a
2107 // new version of RegionStore that tracks the extent of a binding as well
2110 // This hack only takes care of the undefined case because that can very
2111 // quickly result in a warning.
2112 bool hasPartialLazyBinding
= false;
2114 const SubRegion
*SR
= R
;
2116 const MemRegion
*Base
= SR
->getSuperRegion();
2117 if (std::optional
<SVal
> D
=
2118 getBindingForDerivedDefaultValue(B
, Base
, R
, Ty
)) {
2119 if (D
->getAs
<nonloc::LazyCompoundVal
>()) {
2120 hasPartialLazyBinding
= true;
2127 if (const ElementRegion
*ER
= dyn_cast
<ElementRegion
>(Base
)) {
2128 NonLoc index
= ER
->getIndex();
2129 if (!index
.isConstant())
2130 hasSymbolicIndex
= true;
2133 // If our super region is a field or element itself, walk up the region
2134 // hierarchy to see if there is a default value installed in an ancestor.
2135 SR
= dyn_cast
<SubRegion
>(Base
);
2138 if (R
->hasStackNonParametersStorage()) {
2139 if (isa
<ElementRegion
>(R
)) {
2140 // Currently we don't reason specially about Clang-style vectors. Check
2141 // if superR is a vector and if so return Unknown.
2142 if (const TypedValueRegion
*typedSuperR
=
2143 dyn_cast
<TypedValueRegion
>(R
->getSuperRegion())) {
2144 if (typedSuperR
->getValueType()->isVectorType())
2145 return UnknownVal();
2149 // FIXME: We also need to take ElementRegions with symbolic indexes into
2150 // account. This case handles both directly accessing an ElementRegion
2151 // with a symbolic offset, but also fields within an element with
2152 // a symbolic offset.
2153 if (hasSymbolicIndex
)
2154 return UnknownVal();
2156 // Additionally allow introspection of a block's internal layout.
2157 // Try to get direct binding if all other attempts failed thus far.
2158 // Else, return UndefinedVal()
2159 if (!hasPartialLazyBinding
&& !isa
<BlockDataRegion
>(R
->getBaseRegion())) {
2160 if (const std::optional
<SVal
> &V
= B
.getDefaultBinding(R
))
2162 return UndefinedVal();
2166 // All other values are symbolic.
2167 return svalBuilder
.getRegionValueSymbolVal(R
);
2170 SVal
RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B
,
2171 const ObjCIvarRegion
* R
) {
2172 // Check if the region has a binding.
2173 if (const std::optional
<SVal
> &V
= B
.getDirectBinding(R
))
2176 const MemRegion
*superR
= R
->getSuperRegion();
2178 // Check if the super region has a default binding.
2179 if (const std::optional
<SVal
> &V
= B
.getDefaultBinding(superR
)) {
2180 if (SymbolRef parentSym
= V
->getAsSymbol())
2181 return svalBuilder
.getDerivedRegionValueSymbolVal(parentSym
, R
);
2183 // Other cases: give up.
2184 return UnknownVal();
2187 return getBindingForLazySymbol(R
);
2190 SVal
RegionStoreManager::getBindingForVar(RegionBindingsConstRef B
,
2191 const VarRegion
*R
) {
2193 // Check if the region has a binding.
2194 if (std::optional
<SVal
> V
= B
.getDirectBinding(R
))
2197 if (std::optional
<SVal
> V
= B
.getDefaultBinding(R
))
2200 // Lazily derive a value for the VarRegion.
2201 const VarDecl
*VD
= R
->getDecl();
2202 const MemSpaceRegion
*MS
= R
->getMemorySpace();
2204 // Arguments are always symbolic.
2205 if (isa
<StackArgumentsSpaceRegion
>(MS
))
2206 return svalBuilder
.getRegionValueSymbolVal(R
);
2208 // Is 'VD' declared constant? If so, retrieve the constant value.
2209 if (VD
->getType().isConstQualified()) {
2210 if (const Expr
*Init
= VD
->getAnyInitializer()) {
2211 if (std::optional
<SVal
> V
= svalBuilder
.getConstantVal(Init
))
2214 // If the variable is const qualified and has an initializer but
2215 // we couldn't evaluate initializer to a value, treat the value as
2217 return UnknownVal();
2221 // This must come after the check for constants because closure-captured
2222 // constant variables may appear in UnknownSpaceRegion.
2223 if (isa
<UnknownSpaceRegion
>(MS
))
2224 return svalBuilder
.getRegionValueSymbolVal(R
);
2226 if (isa
<GlobalsSpaceRegion
>(MS
)) {
2227 QualType T
= VD
->getType();
2229 // If we're in main(), then global initializers have not become stale yet.
2230 if (B
.isMainAnalysis())
2231 if (const Expr
*Init
= VD
->getAnyInitializer())
2232 if (std::optional
<SVal
> V
= svalBuilder
.getConstantVal(Init
))
2235 // Function-scoped static variables are default-initialized to 0; if they
2236 // have an initializer, it would have been processed by now.
2237 // FIXME: This is only true when we're starting analysis from main().
2238 // We're losing a lot of coverage here.
2239 if (isa
<StaticGlobalSpaceRegion
>(MS
))
2240 return svalBuilder
.makeZeroVal(T
);
2242 if (std::optional
<SVal
> V
= getBindingForDerivedDefaultValue(B
, MS
, R
, T
)) {
2243 assert(!V
->getAs
<nonloc::LazyCompoundVal
>());
2247 return svalBuilder
.getRegionValueSymbolVal(R
);
2250 return UndefinedVal();
2253 SVal
RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion
*R
) {
2254 // All other values are symbolic.
2255 return svalBuilder
.getRegionValueSymbolVal(R
);
2258 const RegionStoreManager::SValListTy
&
2259 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV
) {
2260 // First, check the cache.
2261 LazyBindingsMapTy::iterator I
= LazyBindingsMap
.find(LCV
.getCVData());
2262 if (I
!= LazyBindingsMap
.end())
2265 // If we don't have a list of values cached, start constructing it.
2268 const SubRegion
*LazyR
= LCV
.getRegion();
2269 RegionBindingsRef B
= getRegionBindings(LCV
.getStore());
2271 // If this region had /no/ bindings at the time, there are no interesting
2272 // values to return.
2273 const ClusterBindings
*Cluster
= B
.lookup(LazyR
->getBaseRegion());
2275 return (LazyBindingsMap
[LCV
.getCVData()] = std::move(List
));
2277 SmallVector
<BindingPair
, 32> Bindings
;
2278 collectSubRegionBindings(Bindings
, svalBuilder
, *Cluster
, LazyR
,
2279 /*IncludeAllDefaultBindings=*/true);
2280 for (SmallVectorImpl
<BindingPair
>::const_iterator I
= Bindings
.begin(),
2284 if (V
.isUnknownOrUndef() || V
.isConstant())
2287 if (auto InnerLCV
= V
.getAs
<nonloc::LazyCompoundVal
>()) {
2288 const SValListTy
&InnerList
= getInterestingValues(*InnerLCV
);
2289 List
.insert(List
.end(), InnerList
.begin(), InnerList
.end());
2295 return (LazyBindingsMap
[LCV
.getCVData()] = std::move(List
));
2298 NonLoc
RegionStoreManager::createLazyBinding(RegionBindingsConstRef B
,
2299 const TypedValueRegion
*R
) {
2300 if (std::optional
<nonloc::LazyCompoundVal
> V
=
2301 getExistingLazyBinding(svalBuilder
, B
, R
, false))
2304 return svalBuilder
.makeLazyCompoundVal(StoreRef(B
.asStore(), *this), R
);
2307 static bool isRecordEmpty(const RecordDecl
*RD
) {
2308 if (!RD
->field_empty())
2310 if (const CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
))
2311 return CRD
->getNumBases() == 0;
2315 SVal
RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B
,
2316 const TypedValueRegion
*R
) {
2317 const RecordDecl
*RD
= R
->getValueType()->castAs
<RecordType
>()->getDecl();
2318 if (!RD
->getDefinition() || isRecordEmpty(RD
))
2319 return UnknownVal();
2321 return createLazyBinding(B
, R
);
2324 SVal
RegionStoreManager::getBindingForArray(RegionBindingsConstRef B
,
2325 const TypedValueRegion
*R
) {
2326 assert(Ctx
.getAsConstantArrayType(R
->getValueType()) &&
2327 "Only constant array types can have compound bindings.");
2329 return createLazyBinding(B
, R
);
2332 bool RegionStoreManager::includedInBindings(Store store
,
2333 const MemRegion
*region
) const {
2334 RegionBindingsRef B
= getRegionBindings(store
);
2335 region
= region
->getBaseRegion();
2337 // Quick path: if the base is the head of a cluster, the region is live.
2338 if (B
.lookup(region
))
2341 // Slow path: if the region is the VALUE of any binding, it is live.
2342 for (RegionBindingsRef::iterator RI
= B
.begin(), RE
= B
.end(); RI
!= RE
; ++RI
) {
2343 const ClusterBindings
&Cluster
= RI
.getData();
2344 for (ClusterBindings::iterator CI
= Cluster
.begin(), CE
= Cluster
.end();
2346 const SVal
&D
= CI
.getData();
2347 if (const MemRegion
*R
= D
.getAsRegion())
2348 if (R
->getBaseRegion() == region
)
2356 //===----------------------------------------------------------------------===//
2357 // Binding values to regions.
2358 //===----------------------------------------------------------------------===//
2360 StoreRef
RegionStoreManager::killBinding(Store ST
, Loc L
) {
2361 if (std::optional
<loc::MemRegionVal
> LV
= L
.getAs
<loc::MemRegionVal
>())
2362 if (const MemRegion
* R
= LV
->getRegion())
2363 return StoreRef(getRegionBindings(ST
).removeBinding(R
)
2365 .getRootWithoutRetain(),
2368 return StoreRef(ST
, *this);
2372 RegionStoreManager::bind(RegionBindingsConstRef B
, Loc L
, SVal V
) {
2373 if (L
.getAs
<loc::ConcreteInt
>())
2376 // If we get here, the location should be a region.
2377 const MemRegion
*R
= L
.castAs
<loc::MemRegionVal
>().getRegion();
2379 // Check if the region is a struct region.
2380 if (const TypedValueRegion
* TR
= dyn_cast
<TypedValueRegion
>(R
)) {
2381 QualType Ty
= TR
->getValueType();
2382 if (Ty
->isArrayType())
2383 return bindArray(B
, TR
, V
);
2384 if (Ty
->isStructureOrClassType())
2385 return bindStruct(B
, TR
, V
);
2386 if (Ty
->isVectorType())
2387 return bindVector(B
, TR
, V
);
2388 if (Ty
->isUnionType())
2389 return bindAggregate(B
, TR
, V
);
2392 // Binding directly to a symbolic region should be treated as binding
2394 if (const SymbolicRegion
*SR
= dyn_cast
<SymbolicRegion
>(R
))
2395 R
= GetElementZeroRegion(SR
, SR
->getPointeeStaticType());
2397 assert((!isa
<CXXThisRegion
>(R
) || !B
.lookup(R
)) &&
2398 "'this' pointer is not an l-value and is not assignable");
2400 // Clear out bindings that may overlap with this binding.
2401 RegionBindingsRef NewB
= removeSubRegionBindings(B
, cast
<SubRegion
>(R
));
2403 // LazyCompoundVals should be always bound as 'default' bindings.
2404 auto KeyKind
= isa
<nonloc::LazyCompoundVal
>(V
) ? BindingKey::Default
2405 : BindingKey::Direct
;
2406 return NewB
.addBinding(BindingKey::Make(R
, KeyKind
), V
);
2410 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B
,
2415 if (Loc::isLocType(T
))
2416 V
= svalBuilder
.makeNullWithType(T
);
2417 else if (T
->isIntegralOrEnumerationType())
2418 V
= svalBuilder
.makeZeroVal(T
);
2419 else if (T
->isStructureOrClassType() || T
->isArrayType()) {
2420 // Set the default value to a zero constant when it is a structure
2421 // or array. The type doesn't really matter.
2422 V
= svalBuilder
.makeZeroVal(Ctx
.IntTy
);
2425 // We can't represent values of this type, but we still need to set a value
2426 // to record that the region has been initialized.
2427 // If this assertion ever fires, a new case should be added above -- we
2428 // should know how to default-initialize any value we can symbolicate.
2429 assert(!SymbolManager::canSymbolicate(T
) && "This type is representable");
2433 return B
.addBinding(R
, BindingKey::Default
, V
);
2436 std::optional
<RegionBindingsRef
> RegionStoreManager::tryBindSmallArray(
2437 RegionBindingsConstRef B
, const TypedValueRegion
*R
, const ArrayType
*AT
,
2438 nonloc::LazyCompoundVal LCV
) {
2440 auto CAT
= dyn_cast
<ConstantArrayType
>(AT
);
2442 // If we don't know the size, create a lazyCompoundVal instead.
2444 return std::nullopt
;
2446 QualType Ty
= CAT
->getElementType();
2447 if (!(Ty
->isScalarType() || Ty
->isReferenceType()))
2448 return std::nullopt
;
2450 // If the array is too big, create a LCV instead.
2451 uint64_t ArrSize
= CAT
->getSize().getLimitedValue();
2452 if (ArrSize
> SmallArrayLimit
)
2453 return std::nullopt
;
2455 RegionBindingsRef NewB
= B
;
2457 for (uint64_t i
= 0; i
< ArrSize
; ++i
) {
2458 auto Idx
= svalBuilder
.makeArrayIndex(i
);
2459 const ElementRegion
*SrcER
=
2460 MRMgr
.getElementRegion(Ty
, Idx
, LCV
.getRegion(), Ctx
);
2461 SVal V
= getBindingForElement(getRegionBindings(LCV
.getStore()), SrcER
);
2463 const ElementRegion
*DstER
= MRMgr
.getElementRegion(Ty
, Idx
, R
, Ctx
);
2464 NewB
= bind(NewB
, loc::MemRegionVal(DstER
), V
);
2471 RegionStoreManager::bindArray(RegionBindingsConstRef B
,
2472 const TypedValueRegion
* R
,
2475 const ArrayType
*AT
=cast
<ArrayType
>(Ctx
.getCanonicalType(R
->getValueType()));
2476 QualType ElementTy
= AT
->getElementType();
2477 std::optional
<uint64_t> Size
;
2479 if (const ConstantArrayType
* CAT
= dyn_cast
<ConstantArrayType
>(AT
))
2480 Size
= CAT
->getSize().getZExtValue();
2482 // Check if the init expr is a literal. If so, bind the rvalue instead.
2483 // FIXME: It's not responsibility of the Store to transform this lvalue
2484 // to rvalue. ExprEngine or maybe even CFG should do this before binding.
2485 if (std::optional
<loc::MemRegionVal
> MRV
= Init
.getAs
<loc::MemRegionVal
>()) {
2486 SVal V
= getBinding(B
.asStore(), *MRV
, R
->getValueType());
2487 return bindAggregate(B
, R
, V
);
2490 // Handle lazy compound values.
2491 if (std::optional
<nonloc::LazyCompoundVal
> LCV
=
2492 Init
.getAs
<nonloc::LazyCompoundVal
>()) {
2493 if (std::optional
<RegionBindingsRef
> NewB
=
2494 tryBindSmallArray(B
, R
, AT
, *LCV
))
2497 return bindAggregate(B
, R
, Init
);
2500 if (Init
.isUnknown())
2501 return bindAggregate(B
, R
, UnknownVal());
2503 // Remaining case: explicit compound values.
2504 const nonloc::CompoundVal
& CV
= Init
.castAs
<nonloc::CompoundVal
>();
2505 nonloc::CompoundVal::iterator VI
= CV
.begin(), VE
= CV
.end();
2508 RegionBindingsRef
NewB(B
);
2510 for (; Size
? i
< *Size
: true; ++i
, ++VI
) {
2511 // The init list might be shorter than the array length.
2515 const NonLoc
&Idx
= svalBuilder
.makeArrayIndex(i
);
2516 const ElementRegion
*ER
= MRMgr
.getElementRegion(ElementTy
, Idx
, R
, Ctx
);
2518 if (ElementTy
->isStructureOrClassType())
2519 NewB
= bindStruct(NewB
, ER
, *VI
);
2520 else if (ElementTy
->isArrayType())
2521 NewB
= bindArray(NewB
, ER
, *VI
);
2523 NewB
= bind(NewB
, loc::MemRegionVal(ER
), *VI
);
2526 // If the init list is shorter than the array length (or the array has
2527 // variable length), set the array default value. Values that are already set
2528 // are not overwritten.
2529 if (!Size
|| i
< *Size
)
2530 NewB
= setImplicitDefaultValue(NewB
, R
, ElementTy
);
2535 RegionBindingsRef
RegionStoreManager::bindVector(RegionBindingsConstRef B
,
2536 const TypedValueRegion
* R
,
2538 QualType T
= R
->getValueType();
2539 const VectorType
*VT
= T
->castAs
<VectorType
>(); // Use castAs for typedefs.
2541 // Handle lazy compound values and symbolic values.
2542 if (isa
<nonloc::LazyCompoundVal
, nonloc::SymbolVal
>(V
))
2543 return bindAggregate(B
, R
, V
);
2545 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2546 // that we are binding symbolic struct value. Kill the field values, and if
2547 // the value is symbolic go and bind it as a "default" binding.
2548 if (!isa
<nonloc::CompoundVal
>(V
)) {
2549 return bindAggregate(B
, R
, UnknownVal());
2552 QualType ElemType
= VT
->getElementType();
2553 nonloc::CompoundVal CV
= V
.castAs
<nonloc::CompoundVal
>();
2554 nonloc::CompoundVal::iterator VI
= CV
.begin(), VE
= CV
.end();
2555 unsigned index
= 0, numElements
= VT
->getNumElements();
2556 RegionBindingsRef
NewB(B
);
2558 for ( ; index
!= numElements
; ++index
) {
2562 NonLoc Idx
= svalBuilder
.makeArrayIndex(index
);
2563 const ElementRegion
*ER
= MRMgr
.getElementRegion(ElemType
, Idx
, R
, Ctx
);
2565 if (ElemType
->isArrayType())
2566 NewB
= bindArray(NewB
, ER
, *VI
);
2567 else if (ElemType
->isStructureOrClassType())
2568 NewB
= bindStruct(NewB
, ER
, *VI
);
2570 NewB
= bind(NewB
, loc::MemRegionVal(ER
), *VI
);
2575 std::optional
<RegionBindingsRef
> RegionStoreManager::tryBindSmallStruct(
2576 RegionBindingsConstRef B
, const TypedValueRegion
*R
, const RecordDecl
*RD
,
2577 nonloc::LazyCompoundVal LCV
) {
2580 if (const CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(RD
))
2581 if (Class
->getNumBases() != 0 || Class
->getNumVBases() != 0)
2582 return std::nullopt
;
2584 for (const auto *FD
: RD
->fields()) {
2585 if (FD
->isUnnamedBitfield())
2588 // If there are too many fields, or if any of the fields are aggregates,
2589 // just use the LCV as a default binding.
2590 if (Fields
.size() == SmallStructLimit
)
2591 return std::nullopt
;
2593 QualType Ty
= FD
->getType();
2595 // Zero length arrays are basically no-ops, so we also ignore them here.
2596 if (Ty
->isConstantArrayType() &&
2597 Ctx
.getConstantArrayElementCount(Ctx
.getAsConstantArrayType(Ty
)) == 0)
2600 if (!(Ty
->isScalarType() || Ty
->isReferenceType()))
2601 return std::nullopt
;
2603 Fields
.push_back(FD
);
2606 RegionBindingsRef NewB
= B
;
2608 for (FieldVector::iterator I
= Fields
.begin(), E
= Fields
.end(); I
!= E
; ++I
){
2609 const FieldRegion
*SourceFR
= MRMgr
.getFieldRegion(*I
, LCV
.getRegion());
2610 SVal V
= getBindingForField(getRegionBindings(LCV
.getStore()), SourceFR
);
2612 const FieldRegion
*DestFR
= MRMgr
.getFieldRegion(*I
, R
);
2613 NewB
= bind(NewB
, loc::MemRegionVal(DestFR
), V
);
2619 RegionBindingsRef
RegionStoreManager::bindStruct(RegionBindingsConstRef B
,
2620 const TypedValueRegion
*R
,
2622 QualType T
= R
->getValueType();
2623 assert(T
->isStructureOrClassType());
2625 const RecordType
* RT
= T
->castAs
<RecordType
>();
2626 const RecordDecl
*RD
= RT
->getDecl();
2628 if (!RD
->isCompleteDefinition())
2631 // Handle lazy compound values and symbolic values.
2632 if (std::optional
<nonloc::LazyCompoundVal
> LCV
=
2633 V
.getAs
<nonloc::LazyCompoundVal
>()) {
2634 if (std::optional
<RegionBindingsRef
> NewB
=
2635 tryBindSmallStruct(B
, R
, RD
, *LCV
))
2637 return bindAggregate(B
, R
, V
);
2639 if (isa
<nonloc::SymbolVal
>(V
))
2640 return bindAggregate(B
, R
, V
);
2642 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2643 // that we are binding symbolic struct value. Kill the field values, and if
2644 // the value is symbolic go and bind it as a "default" binding.
2645 if (V
.isUnknown() || !isa
<nonloc::CompoundVal
>(V
))
2646 return bindAggregate(B
, R
, UnknownVal());
2648 // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable)
2649 // list of other values. It appears pretty much only when there's an actual
2650 // initializer list expression in the program, and the analyzer tries to
2651 // unwrap it as soon as possible.
2652 // This code is where such unwrap happens: when the compound value is put into
2653 // the object that it was supposed to initialize (it's an *initializer* list,
2654 // after all), instead of binding the whole value to the whole object, we bind
2655 // sub-values to sub-objects. Sub-values may themselves be compound values,
2656 // and in this case the procedure becomes recursive.
2657 // FIXME: The annoying part about compound values is that they don't carry
2658 // any sort of information about which value corresponds to which sub-object.
2659 // It's simply a list of values in the middle of nowhere; we expect to match
2660 // them to sub-objects, essentially, "by index": first value binds to
2661 // the first field, second value binds to the second field, etc.
2662 // It would have been much safer to organize non-lazy compound values as
2663 // a mapping from fields/bases to values.
2664 const nonloc::CompoundVal
& CV
= V
.castAs
<nonloc::CompoundVal
>();
2665 nonloc::CompoundVal::iterator VI
= CV
.begin(), VE
= CV
.end();
2667 RegionBindingsRef
NewB(B
);
2669 // In C++17 aggregates may have base classes, handle those as well.
2670 // They appear before fields in the initializer list / compound value.
2671 if (const auto *CRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
2672 // If the object was constructed with a constructor, its value is a
2673 // LazyCompoundVal. If it's a raw CompoundVal, it means that we're
2674 // performing aggregate initialization. The only exception from this
2675 // rule is sending an Objective-C++ message that returns a C++ object
2676 // to a nil receiver; in this case the semantics is to return a
2677 // zero-initialized object even if it's a C++ object that doesn't have
2678 // this sort of constructor; the CompoundVal is empty in this case.
2679 assert((CRD
->isAggregate() || (Ctx
.getLangOpts().ObjC
&& VI
== VE
)) &&
2680 "Non-aggregates are constructed with a constructor!");
2682 for (const auto &B
: CRD
->bases()) {
2683 // (Multiple inheritance is fine though.)
2684 assert(!B
.isVirtual() && "Aggregates cannot have virtual base classes!");
2689 QualType BTy
= B
.getType();
2690 assert(BTy
->isStructureOrClassType() && "Base classes must be classes!");
2692 const CXXRecordDecl
*BRD
= BTy
->getAsCXXRecordDecl();
2693 assert(BRD
&& "Base classes must be C++ classes!");
2695 const CXXBaseObjectRegion
*BR
=
2696 MRMgr
.getCXXBaseObjectRegion(BRD
, R
, /*IsVirtual=*/false);
2698 NewB
= bindStruct(NewB
, BR
, *VI
);
2704 RecordDecl::field_iterator FI
, FE
;
2706 for (FI
= RD
->field_begin(), FE
= RD
->field_end(); FI
!= FE
; ++FI
) {
2711 // Skip any unnamed bitfields to stay in sync with the initializers.
2712 if (FI
->isUnnamedBitfield())
2715 QualType FTy
= FI
->getType();
2716 const FieldRegion
* FR
= MRMgr
.getFieldRegion(*FI
, R
);
2718 if (FTy
->isArrayType())
2719 NewB
= bindArray(NewB
, FR
, *VI
);
2720 else if (FTy
->isStructureOrClassType())
2721 NewB
= bindStruct(NewB
, FR
, *VI
);
2723 NewB
= bind(NewB
, loc::MemRegionVal(FR
), *VI
);
2727 // There may be fewer values in the initialize list than the fields of struct.
2729 NewB
= NewB
.addBinding(R
, BindingKey::Default
,
2730 svalBuilder
.makeIntVal(0, false));
2737 RegionStoreManager::bindAggregate(RegionBindingsConstRef B
,
2738 const TypedRegion
*R
,
2740 // Remove the old bindings, using 'R' as the root of all regions
2741 // we will invalidate. Then add the new binding.
2742 return removeSubRegionBindings(B
, R
).addBinding(R
, BindingKey::Default
, Val
);
2745 //===----------------------------------------------------------------------===//
2747 //===----------------------------------------------------------------------===//
2750 class RemoveDeadBindingsWorker
2751 : public ClusterAnalysis
<RemoveDeadBindingsWorker
> {
2752 SmallVector
<const SymbolicRegion
*, 12> Postponed
;
2753 SymbolReaper
&SymReaper
;
2754 const StackFrameContext
*CurrentLCtx
;
2757 RemoveDeadBindingsWorker(RegionStoreManager
&rm
,
2758 ProgramStateManager
&stateMgr
,
2759 RegionBindingsRef b
, SymbolReaper
&symReaper
,
2760 const StackFrameContext
*LCtx
)
2761 : ClusterAnalysis
<RemoveDeadBindingsWorker
>(rm
, stateMgr
, b
),
2762 SymReaper(symReaper
), CurrentLCtx(LCtx
) {}
2764 // Called by ClusterAnalysis.
2765 void VisitAddedToCluster(const MemRegion
*baseR
, const ClusterBindings
&C
);
2766 void VisitCluster(const MemRegion
*baseR
, const ClusterBindings
*C
);
2767 using ClusterAnalysis
<RemoveDeadBindingsWorker
>::VisitCluster
;
2769 using ClusterAnalysis::AddToWorkList
;
2771 bool AddToWorkList(const MemRegion
*R
);
2773 bool UpdatePostponed();
2774 void VisitBinding(SVal V
);
2778 bool RemoveDeadBindingsWorker::AddToWorkList(const MemRegion
*R
) {
2779 const MemRegion
*BaseR
= R
->getBaseRegion();
2780 return AddToWorkList(WorkListElement(BaseR
), getCluster(BaseR
));
2783 void RemoveDeadBindingsWorker::VisitAddedToCluster(const MemRegion
*baseR
,
2784 const ClusterBindings
&C
) {
2786 if (const VarRegion
*VR
= dyn_cast
<VarRegion
>(baseR
)) {
2787 if (SymReaper
.isLive(VR
))
2788 AddToWorkList(baseR
, &C
);
2793 if (const SymbolicRegion
*SR
= dyn_cast
<SymbolicRegion
>(baseR
)) {
2794 if (SymReaper
.isLive(SR
->getSymbol()))
2795 AddToWorkList(SR
, &C
);
2797 Postponed
.push_back(SR
);
2802 if (isa
<NonStaticGlobalSpaceRegion
>(baseR
)) {
2803 AddToWorkList(baseR
, &C
);
2807 // CXXThisRegion in the current or parent location context is live.
2808 if (const CXXThisRegion
*TR
= dyn_cast
<CXXThisRegion
>(baseR
)) {
2809 const auto *StackReg
=
2810 cast
<StackArgumentsSpaceRegion
>(TR
->getSuperRegion());
2811 const StackFrameContext
*RegCtx
= StackReg
->getStackFrame();
2813 (RegCtx
== CurrentLCtx
|| RegCtx
->isParentOf(CurrentLCtx
)))
2814 AddToWorkList(TR
, &C
);
2818 void RemoveDeadBindingsWorker::VisitCluster(const MemRegion
*baseR
,
2819 const ClusterBindings
*C
) {
2823 // Mark the symbol for any SymbolicRegion with live bindings as live itself.
2824 // This means we should continue to track that symbol.
2825 if (const SymbolicRegion
*SymR
= dyn_cast
<SymbolicRegion
>(baseR
))
2826 SymReaper
.markLive(SymR
->getSymbol());
2828 for (ClusterBindings::iterator I
= C
->begin(), E
= C
->end(); I
!= E
; ++I
) {
2829 // Element index of a binding key is live.
2830 SymReaper
.markElementIndicesLive(I
.getKey().getRegion());
2832 VisitBinding(I
.getData());
2836 void RemoveDeadBindingsWorker::VisitBinding(SVal V
) {
2837 // Is it a LazyCompoundVal? All referenced regions are live as well.
2838 // The LazyCompoundVal itself is not live but should be readable.
2839 if (auto LCS
= V
.getAs
<nonloc::LazyCompoundVal
>()) {
2840 SymReaper
.markLazilyCopied(LCS
->getRegion());
2842 for (SVal V
: RM
.getInterestingValues(*LCS
)) {
2843 if (auto DepLCS
= V
.getAs
<nonloc::LazyCompoundVal
>())
2844 SymReaper
.markLazilyCopied(DepLCS
->getRegion());
2852 // If V is a region, then add it to the worklist.
2853 if (const MemRegion
*R
= V
.getAsRegion()) {
2855 SymReaper
.markLive(R
);
2857 // All regions captured by a block are also live.
2858 if (const BlockDataRegion
*BR
= dyn_cast
<BlockDataRegion
>(R
)) {
2859 BlockDataRegion::referenced_vars_iterator I
= BR
->referenced_vars_begin(),
2860 E
= BR
->referenced_vars_end();
2861 for ( ; I
!= E
; ++I
)
2862 AddToWorkList(I
.getCapturedRegion());
2867 // Update the set of live symbols.
2868 for (auto SI
= V
.symbol_begin(), SE
= V
.symbol_end(); SI
!=SE
; ++SI
)
2869 SymReaper
.markLive(*SI
);
2872 bool RemoveDeadBindingsWorker::UpdatePostponed() {
2873 // See if any postponed SymbolicRegions are actually live now, after
2874 // having done a scan.
2875 bool Changed
= false;
2877 for (auto I
= Postponed
.begin(), E
= Postponed
.end(); I
!= E
; ++I
) {
2878 if (const SymbolicRegion
*SR
= *I
) {
2879 if (SymReaper
.isLive(SR
->getSymbol())) {
2880 Changed
|= AddToWorkList(SR
);
2889 StoreRef
RegionStoreManager::removeDeadBindings(Store store
,
2890 const StackFrameContext
*LCtx
,
2891 SymbolReaper
& SymReaper
) {
2892 RegionBindingsRef B
= getRegionBindings(store
);
2893 RemoveDeadBindingsWorker
W(*this, StateMgr
, B
, SymReaper
, LCtx
);
2894 W
.GenerateClusters();
2896 // Enqueue the region roots onto the worklist.
2897 for (SymbolReaper::region_iterator I
= SymReaper
.region_begin(),
2898 E
= SymReaper
.region_end(); I
!= E
; ++I
) {
2899 W
.AddToWorkList(*I
);
2902 do W
.RunWorkList(); while (W
.UpdatePostponed());
2904 // We have now scanned the store, marking reachable regions and symbols
2905 // as live. We now remove all the regions that are dead from the store
2906 // as well as update DSymbols with the set symbols that are now dead.
2907 for (RegionBindingsRef::iterator I
= B
.begin(), E
= B
.end(); I
!= E
; ++I
) {
2908 const MemRegion
*Base
= I
.getKey();
2910 // If the cluster has been visited, we know the region has been marked.
2911 // Otherwise, remove the dead entry.
2912 if (!W
.isVisited(Base
))
2916 return StoreRef(B
.asStore(), *this);
2919 //===----------------------------------------------------------------------===//
2921 //===----------------------------------------------------------------------===//
2923 void RegionStoreManager::printJson(raw_ostream
&Out
, Store S
, const char *NL
,
2924 unsigned int Space
, bool IsDot
) const {
2925 RegionBindingsRef Bindings
= getRegionBindings(S
);
2927 Indent(Out
, Space
, IsDot
) << "\"store\": ";
2929 if (Bindings
.isEmpty()) {
2930 Out
<< "null," << NL
;
2934 Out
<< "{ \"pointer\": \"" << Bindings
.asStore() << "\", \"items\": [" << NL
;
2935 Bindings
.printJson(Out
, NL
, Space
+ 1, IsDot
);
2936 Indent(Out
, Space
, IsDot
) << "]}," << NL
;