clang 23.0.0git
Store.h
Go to the documentation of this file.
1//===- Store.h - Interface for maps from Locations to Values ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defined the types Store and StoreManager.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
14#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
15
16#include "clang/AST/Type.h"
17#include "clang/Basic/LLVM.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include <cassert>
28#include <cstdint>
29#include <memory>
30#include <optional>
31
32namespace clang {
33
34class ASTContext;
35class CastExpr;
37class CXXBasePath;
38class Decl;
39class Expr;
40class ObjCIvarDecl;
41class StackFrame;
42
43namespace ento {
44
45class CallEvent;
48class SymbolReaper;
49
50using InvalidatedSymbols = llvm::DenseSet<SymbolRef>;
51
52struct BindResult {
54
55 // If during the bind operation we exhaust the allowed binding budget, we set
56 // this to the beginning of the escaped part of the region.
58};
59
61protected:
64
65 /// MRMgr - Manages region objects associated with this StoreManager.
68
70
71public:
72 virtual ~StoreManager() = default;
73
74 /// Return the value bound to specified location in a given state.
75 /// \param[in] store The store in which to make the lookup.
76 /// \param[in] loc The symbolic memory location.
77 /// \param[in] T An optional type that provides a hint indicating the
78 /// expected type of the returned value. This is used if the value is
79 /// lazily computed.
80 /// \return The value bound to the location \c loc.
81 virtual SVal getBinding(Store store, Loc loc, QualType T = QualType()) = 0;
82
83 /// Return the default value bound to a region in a given store. The default
84 /// binding is the value of sub-regions that were not initialized separately
85 /// from their base region. For example, if the structure is zero-initialized
86 /// upon construction, this method retrieves the concrete zero value, even if
87 /// some or all fields were later overwritten manually. Default binding may be
88 /// an unknown, undefined, concrete, or symbolic value.
89 /// \param[in] store The store in which to make the lookup.
90 /// \param[in] R The region to find the default binding for.
91 /// \return The default value bound to the region in the store, if a default
92 /// binding exists.
93 virtual std::optional<SVal> getDefaultBinding(Store store,
94 const MemRegion *R) = 0;
95
96 /// Return the default value bound to a LazyCompoundVal. The default binding
97 /// is used to represent the value of any fields or elements within the
98 /// structure represented by the LazyCompoundVal which were not initialized
99 /// explicitly separately from the whole structure. Default binding may be an
100 /// unknown, undefined, concrete, or symbolic value.
101 /// \param[in] lcv The lazy compound value.
102 /// \return The default value bound to the LazyCompoundVal \c lcv, if a
103 /// default binding exists.
105 return getDefaultBinding(lcv.getStore(), lcv.getRegion());
106 }
107
108 /// Return a store with the specified value bound to the given location.
109 /// \param[in] store The store in which to make the binding.
110 /// \param[in] loc The symbolic memory location.
111 /// \param[in] val The value to bind to location \c loc.
112 /// \return A StoreRef object that contains the same
113 /// bindings as \c store with the addition of having the value specified
114 /// by \c val bound to the location given for \c loc.
115 virtual BindResult Bind(Store store, Loc loc, SVal val) = 0;
116
117 /// Return a store with the specified value bound to all sub-regions of the
118 /// region. The region must not have previous bindings. If you need to
119 /// invalidate existing bindings, consider invalidateRegions().
121 SVal V) = 0;
122
123 /// Return a store with in which all values within the given region are
124 /// reset to zero. This method is allowed to overwrite previous bindings.
125 virtual BindResult BindDefaultZero(Store store, const MemRegion *R) = 0;
126
127 /// Create a new store with the specified binding removed.
128 /// \param ST the original store, that is the basis for the new store.
129 /// \param L the location whose binding should be removed.
130 virtual StoreRef killBinding(Store ST, Loc L) = 0;
131
132 /// getInitialStore - Returns the initial "empty" store representing the
133 /// value bindings upon entry to an analyzed function.
134 virtual StoreRef getInitialStore(const StackFrame *InitSF) = 0;
135
136 /// getRegionManager - Returns the internal RegionManager object that is
137 /// used to query and manipulate MemRegion objects.
139
141
142 virtual Loc getLValueVar(const VarDecl *VD, const StackFrame *SF) {
143 return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, SF));
144 }
145
147 const StackFrame *SF) {
148 return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, SF));
149 }
150
151 virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base);
152
153 virtual SVal getLValueField(const FieldDecl *D, SVal Base) {
154 return getLValueFieldOrIvar(D, Base);
155 }
156
157 virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base);
158
159 /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit
160 /// conversions between arrays and pointers.
161 virtual SVal ArrayToPointer(Loc Array, QualType ElementTy) = 0;
162
163 /// Evaluates a chain of derived-to-base casts through the path specified in
164 /// \p Cast.
165 SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast);
166
167 /// Evaluates a chain of derived-to-base casts through the specified path.
168 SVal evalDerivedToBase(SVal Derived, const CXXBasePath &CastPath);
169
170 /// Evaluates a derived-to-base cast through a single level of derivation.
171 SVal evalDerivedToBase(SVal Derived, QualType DerivedPtrType,
172 bool IsVirtual);
173
174 /// Attempts to do a down cast. Used to model BaseToDerived and C++
175 /// dynamic_cast.
176 /// The callback may result in the following 3 scenarios:
177 /// - Successful cast (ex: derived is subclass of base).
178 /// - Failed cast (ex: derived is definitely not a subclass of base).
179 /// The distinction of this case from the next one is necessary to model
180 /// dynamic_cast.
181 /// - We don't know (base is a symbolic region and we don't have
182 /// enough info to determine if the cast will succeed at run time).
183 /// The function returns an optional with SVal representing the derived class
184 /// in case of a successful cast and `std::nullopt` otherwise.
185 std::optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType);
186
188
189 /// castRegion - Used by ExprEngine::VisitCast to handle casts from
190 /// a MemRegion* to a specific location type. 'R' is the region being
191 /// casted and 'CastToTy' the result type of the cast.
192 std::optional<const MemRegion *> castRegion(const MemRegion *region,
193 QualType CastToTy);
194
195 virtual StoreRef removeDeadBindings(Store store, const StackFrame *SF,
196 SymbolReaper &SymReaper) = 0;
197
198 virtual bool includedInBindings(Store store,
199 const MemRegion *region) const = 0;
200
201 /// If the StoreManager supports it, increment the reference count of
202 /// the specified Store object.
203 virtual void incrementReferenceCount(Store store) {}
204
205 /// If the StoreManager supports it, decrement the reference count of
206 /// the specified Store object. If the reference count hits 0, the memory
207 /// associated with the object is recycled.
208 virtual void decrementReferenceCount(Store store) {}
209
211
212 /// invalidateRegions - Clears out the specified regions from the store,
213 /// marking their values as unknown. Depending on the store, this may also
214 /// invalidate additional regions that may have changed based on accessing
215 /// the given regions. If \p Call is non-null, then this also invalidates
216 /// non-static globals (but if \p Call is from a system header, then this is
217 /// limited to globals declared in system headers).
218 ///
219 /// Instead of calling this method directly, you should probably use
220 /// \c ProgramState::invalidateRegions, which calls this and then ensures that
221 /// the relevant checker callbacks are triggered.
222 ///
223 /// \param[in] store The initial store.
224 /// \param[in] Values The values to invalidate.
225 /// \param[in] Elem The current CFG Element being evaluated. Used to conjure
226 /// symbols to mark the values of invalidated regions.
227 /// \param[in] Count The current block count. Used to conjure
228 /// symbols to mark the values of invalidated regions.
229 /// \param[in] Call The call expression which will be used to determine which
230 /// globals should get invalidated.
231 /// \param[in,out] IS A set to fill with any symbols that are no longer
232 /// accessible. Pass \c NULL if this information will not be used.
233 /// \param[in] ITraits Information about invalidation for a particular
234 /// region/symbol.
235 /// \param[in,out] InvalidatedTopLevel A vector to fill with regions
236 //// explicitly being invalidated. Pass \c NULL if this
237 /// information will not be used.
238 /// \param[in,out] Invalidated A vector to fill with any regions being
239 /// invalidated. This should include any regions explicitly invalidated
240 /// even if they do not currently have bindings. Pass \c NULL if this
241 /// information will not be used.
243 Store store, ArrayRef<SVal> Values, ConstCFGElementRef Elem,
244 unsigned Count, const StackFrame *SF, const CallEvent *Call,
246 InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0;
247
248 /// enterStackFrame - Let the StoreManager to do something when execution
249 /// engine is about to execute into a callee.
251 const StackFrame *CalleeSF);
252
253 /// Finds the transitive closure of symbols within the given region.
254 ///
255 /// Returns false if the visitor aborted the scan.
256 virtual bool scanReachableSymbols(Store S, const MemRegion *R,
257 ScanReachableSymbols &Visitor) = 0;
258
259 virtual void printJson(raw_ostream &Out, Store S, const char *NL,
260 unsigned int Space, bool IsDot) const = 0;
261
263 public:
265
266 /// \return whether the iteration should continue.
267 virtual bool HandleBinding(StoreManager& SMgr, Store store,
268 const MemRegion *region, SVal val) = 0;
269 };
270
272 SymbolRef Sym;
273 const MemRegion* Binding = nullptr;
274 bool First = true;
275
276 public:
277 FindUniqueBinding(SymbolRef sym) : Sym(sym) {}
278
279 explicit operator bool() { return First && Binding; }
280
281 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
282 SVal val) override;
283 const MemRegion *getRegion() { return Binding; }
284 };
285
286 /// iterBindings - Iterate over the bindings in the Store.
287 virtual void iterBindings(Store store, BindingsHandler& f) = 0;
288
289protected:
290 const ElementRegion *MakeElementRegion(const SubRegion *baseRegion,
291 QualType pointeeTy,
292 uint64_t index = 0);
293
294private:
295 SVal getLValueFieldOrIvar(const Decl *decl, SVal base);
296};
297
299 : store(store), mgr(smgr) {
300 if (store)
301 mgr.incrementReferenceCount(store);
302}
303
305 : store(sr.store), mgr(sr.mgr)
306{
307 if (store)
308 mgr.incrementReferenceCount(store);
309}
310
312 if (store)
313 mgr.decrementReferenceCount(store);
314}
315
316inline StoreRef &StoreRef::operator=(StoreRef const &newStore) {
317 assert(&newStore.mgr == &mgr);
318 if (store != newStore.store) {
319 mgr.incrementReferenceCount(newStore.store);
320 mgr.decrementReferenceCount(store);
321 store = newStore.getStore();
322 }
323 return *this;
324}
325
326// FIXME: Do we need to pass ProgramStateManager anymore?
327std::unique_ptr<StoreManager>
329
330} // namespace ento
331
332} // namespace clang
333
334#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
#define V(N, I)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::json::Array Array
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3182
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
A (possibly-)qualified type.
Definition TypeBase.h:937
It represents a stack frame of the call stack.
Represents a variable declaration or definition.
Definition Decl.h:924
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
ElementRegion is used to represent both array elements and casts.
Definition MemRegion.h:1230
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1656
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:56
A utility class that visits the reachable symbols using a custom SymbolVisitor.
virtual bool HandleBinding(StoreManager &SMgr, Store store, const MemRegion *region, SVal val)=0
bool HandleBinding(StoreManager &SMgr, Store store, const MemRegion *R, SVal val) override
Definition Store.cpp:531
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition Store.cpp:254
ProgramStateManager & StateMgr
Definition Store.h:63
SValBuilder & getSValBuilder()
Definition Store.h:140
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition Store.h:153
virtual bool scanReachableSymbols(Store S, const MemRegion *R, ScanReachableSymbols &Visitor)=0
Finds the transitive closure of symbols within the given region.
MemRegionManager & getRegionManager()
getRegionManager - Returns the internal RegionManager object that is used to query and manipulate Mem...
Definition Store.h:138
std::optional< SVal > evalBaseToDerived(SVal Base, QualType DerivedPtrType)
Attempts to do a down cast.
Definition Store.cpp:318
const ElementRegion * MakeElementRegion(const SubRegion *baseRegion, QualType pointeeTy, uint64_t index=0)
Definition Store.cpp:62
SmallVector< const MemRegion *, 8 > InvalidatedRegions
Definition Store.h:210
virtual BindResult Bind(Store store, Loc loc, SVal val)=0
Return a store with the specified value bound to the given location.
virtual void iterBindings(Store store, BindingsHandler &f)=0
iterBindings - Iterate over the bindings in the Store.
MemRegionManager & MRMgr
MRMgr - Manages region objects associated with this StoreManager.
Definition Store.h:66
SValBuilder & svalBuilder
Definition Store.h:62
virtual BindResult BindDefaultZero(Store store, const MemRegion *R)=0
Return a store with in which all values within the given region are reset to zero.
virtual StoreRef getInitialStore(const StackFrame *InitSF)=0
getInitialStore - Returns the initial "empty" store representing the value bindings upon entry to an ...
virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base)
Definition Store.cpp:441
virtual std::optional< SVal > getDefaultBinding(Store store, const MemRegion *R)=0
Return the default value bound to a region in a given store.
virtual StoreRef killBinding(Store ST, Loc L)=0
Create a new store with the specified binding removed.
virtual void decrementReferenceCount(Store store)
If the StoreManager supports it, decrement the reference count of the specified Store object.
Definition Store.h:208
virtual StoreRef invalidateRegions(Store store, ArrayRef< SVal > Values, ConstCFGElementRef Elem, unsigned Count, const StackFrame *SF, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated)=0
invalidateRegions - Clears out the specified regions from the store, marking their values as unknown.
virtual ~StoreManager()=default
virtual void incrementReferenceCount(Store store)
If the StoreManager supports it, increment the reference count of the specified Store object.
Definition Store.h:203
Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL, const StackFrame *SF)
Definition Store.h:146
virtual SVal ArrayToPointer(Loc Array, QualType ElementTy)=0
ArrayToPointer - Used by ExprEngine::VistCast to handle implicit conversions between arrays and point...
virtual bool includedInBindings(Store store, const MemRegion *region) const =0
virtual SVal getBinding(Store store, Loc loc, QualType T=QualType())=0
Return the value bound to specified location in a given state.
StoreManager(ProgramStateManager &stateMgr)
Definition Store.cpp:41
std::optional< SVal > getDefaultBinding(nonloc::LazyCompoundVal lcv)
Return the default value bound to a LazyCompoundVal.
Definition Store.h:104
virtual StoreRef removeDeadBindings(Store store, const StackFrame *SF, SymbolReaper &SymReaper)=0
const ElementRegion * GetElementZeroRegion(const SubRegion *R, QualType T)
Definition Store.cpp:69
BindResult enterStackFrame(Store store, const CallEvent &Call, const StackFrame *CalleeSF)
enterStackFrame - Let the StoreManager to do something when execution engine is about to execute into...
Definition Store.cpp:45
virtual BindResult BindDefaultInitial(Store store, const MemRegion *R, SVal V)=0
Return a store with the specified value bound to all sub-regions of the region.
virtual Loc getLValueVar(const VarDecl *VD, const StackFrame *SF)
Definition Store.h:142
virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base)
Definition Store.cpp:445
virtual void printJson(raw_ostream &Out, Store S, const char *NL, unsigned int Space, bool IsDot) const =0
std::optional< const MemRegion * > castRegion(const MemRegion *region, QualType CastToTy)
castRegion - Used by ExprEngine::VisitCast to handle casts from a MemRegion* to a specific location t...
Definition Store.cpp:76
ASTContext & Ctx
Definition Store.h:67
Store getStore() const
Definition StoreRef.h:46
StoreRef & operator=(StoreRef const &newStore)
Definition Store.h:316
StoreRef(Store store, StoreManager &smgr)
Definition Store.h:298
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:473
A class responsible for cleaning up unused symbols.
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition SVals.h:389
LLVM_ATTRIBUTE_RETURNS_NONNULL const TypedValueRegion * getRegion() const
This function itself is immaterial.
Definition SVals.cpp:193
const void * getStore() const
It might return null.
Definition SVals.cpp:189
Definition SPIR.cpp:35
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
const SymExpr * SymbolRef
Definition SymExpr.h:133
std::unique_ptr< StoreManager > CreateRegionStoreManager(ProgramStateManager &StMgr)
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition StoreRef.h:27
The JSON file list parser is used to communicate input to InstallAPI.
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition CFG.h:1248
llvm::SmallVector< SVal, 0 > FailedToBindValues
Definition Store.h:57
StoreRef ResultingStore
Definition Store.h:53