clang 20.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"
23#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;
36class CompoundLiteralExpr;
37class CXXBasePath;
38class Decl;
39class Expr;
40class LocationContext;
41class ObjCIvarDecl;
42class StackFrameContext;
43
44namespace ento {
45
46class CallEvent;
47class ProgramStateManager;
48class ScanReachableSymbols;
49class SymbolReaper;
50
51using InvalidatedSymbols = llvm::DenseSet<SymbolRef>;
52
54protected:
57
58 /// MRMgr - Manages region objects associated with this StoreManager.
61
63
64public:
65 virtual ~StoreManager() = default;
66
67 /// Return the value bound to specified location in a given state.
68 /// \param[in] store The store in which to make the lookup.
69 /// \param[in] loc The symbolic memory location.
70 /// \param[in] T An optional type that provides a hint indicating the
71 /// expected type of the returned value. This is used if the value is
72 /// lazily computed.
73 /// \return The value bound to the location \c loc.
74 virtual SVal getBinding(Store store, Loc loc, QualType T = QualType()) = 0;
75
76 /// Return the default value bound to a region in a given store. The default
77 /// binding is the value of sub-regions that were not initialized separately
78 /// from their base region. For example, if the structure is zero-initialized
79 /// upon construction, this method retrieves the concrete zero value, even if
80 /// some or all fields were later overwritten manually. Default binding may be
81 /// an unknown, undefined, concrete, or symbolic value.
82 /// \param[in] store The store in which to make the lookup.
83 /// \param[in] R The region to find the default binding for.
84 /// \return The default value bound to the region in the store, if a default
85 /// binding exists.
86 virtual std::optional<SVal> getDefaultBinding(Store store,
87 const MemRegion *R) = 0;
88
89 /// Return the default value bound to a LazyCompoundVal. The default binding
90 /// is used to represent the value of any fields or elements within the
91 /// structure represented by the LazyCompoundVal which were not initialized
92 /// explicitly separately from the whole structure. Default binding may be an
93 /// unknown, undefined, concrete, or symbolic value.
94 /// \param[in] lcv The lazy compound value.
95 /// \return The default value bound to the LazyCompoundVal \c lcv, if a
96 /// default binding exists.
97 std::optional<SVal> getDefaultBinding(nonloc::LazyCompoundVal lcv) {
98 return getDefaultBinding(lcv.getStore(), lcv.getRegion());
99 }
100
101 /// Return a store with the specified value bound to the given location.
102 /// \param[in] store The store in which to make the binding.
103 /// \param[in] loc The symbolic memory location.
104 /// \param[in] val The value to bind to location \c loc.
105 /// \return A StoreRef object that contains the same
106 /// bindings as \c store with the addition of having the value specified
107 /// by \c val bound to the location given for \c loc.
108 virtual StoreRef Bind(Store store, Loc loc, SVal val) = 0;
109
110 /// Return a store with the specified value bound to all sub-regions of the
111 /// region. The region must not have previous bindings. If you need to
112 /// invalidate existing bindings, consider invalidateRegions().
114 SVal V) = 0;
115
116 /// Return a store with in which all values within the given region are
117 /// reset to zero. This method is allowed to overwrite previous bindings.
118 virtual StoreRef BindDefaultZero(Store store, const MemRegion *R) = 0;
119
120 /// Create a new store with the specified binding removed.
121 /// \param ST the original store, that is the basis for the new store.
122 /// \param L the location whose binding should be removed.
123 virtual StoreRef killBinding(Store ST, Loc L) = 0;
124
125 /// getInitialStore - Returns the initial "empty" store representing the
126 /// value bindings upon entry to an analyzed function.
127 virtual StoreRef getInitialStore(const LocationContext *InitLoc) = 0;
128
129 /// getRegionManager - Returns the internal RegionManager object that is
130 /// used to query and manipulate MemRegion objects.
132
134
135 virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC) {
136 return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC));
137 }
138
140 const LocationContext *LC) {
142 }
143
144 virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base);
145
147 return getLValueFieldOrIvar(D, Base);
148 }
149
150 virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base);
151
152 /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit
153 /// conversions between arrays and pointers.
154 virtual SVal ArrayToPointer(Loc Array, QualType ElementTy) = 0;
155
156 /// Evaluates a chain of derived-to-base casts through the path specified in
157 /// \p Cast.
158 SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast);
159
160 /// Evaluates a chain of derived-to-base casts through the specified path.
161 SVal evalDerivedToBase(SVal Derived, const CXXBasePath &CastPath);
162
163 /// Evaluates a derived-to-base cast through a single level of derivation.
164 SVal evalDerivedToBase(SVal Derived, QualType DerivedPtrType,
165 bool IsVirtual);
166
167 /// Attempts to do a down cast. Used to model BaseToDerived and C++
168 /// dynamic_cast.
169 /// The callback may result in the following 3 scenarios:
170 /// - Successful cast (ex: derived is subclass of base).
171 /// - Failed cast (ex: derived is definitely not a subclass of base).
172 /// The distinction of this case from the next one is necessary to model
173 /// dynamic_cast.
174 /// - We don't know (base is a symbolic region and we don't have
175 /// enough info to determine if the cast will succeed at run time).
176 /// The function returns an optional with SVal representing the derived class
177 /// in case of a successful cast and `std::nullopt` otherwise.
178 std::optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType);
179
181
182 /// castRegion - Used by ExprEngine::VisitCast to handle casts from
183 /// a MemRegion* to a specific location type. 'R' is the region being
184 /// casted and 'CastToTy' the result type of the cast.
185 std::optional<const MemRegion *> castRegion(const MemRegion *region,
186 QualType CastToTy);
187
189 SymbolReaper &SymReaper) = 0;
190
191 virtual bool includedInBindings(Store store,
192 const MemRegion *region) const = 0;
193
194 /// If the StoreManager supports it, increment the reference count of
195 /// the specified Store object.
196 virtual void incrementReferenceCount(Store store) {}
197
198 /// If the StoreManager supports it, decrement the reference count of
199 /// the specified Store object. If the reference count hits 0, the memory
200 /// associated with the object is recycled.
201 virtual void decrementReferenceCount(Store store) {}
202
204
205 /// invalidateRegions - Clears out the specified regions from the store,
206 /// marking their values as unknown. Depending on the store, this may also
207 /// invalidate additional regions that may have changed based on accessing
208 /// the given regions. If \p Call is non-null, then this also invalidates
209 /// non-static globals (but if \p Call is from a system header, then this is
210 /// limited to globals declared in system headers).
211 ///
212 /// Instead of calling this method directly, you should probably use
213 /// \c ProgramState::invalidateRegions, which calls this and then ensures that
214 /// the relevant checker callbacks are triggered.
215 ///
216 /// \param[in] store The initial store.
217 /// \param[in] Values The values to invalidate.
218 /// \param[in] E The current statement being evaluated. Used to conjure
219 /// symbols to mark the values of invalidated regions.
220 /// \param[in] Count The current block count. Used to conjure
221 /// symbols to mark the values of invalidated regions.
222 /// \param[in] Call The call expression which will be used to determine which
223 /// globals should get invalidated.
224 /// \param[in,out] IS A set to fill with any symbols that are no longer
225 /// accessible. Pass \c NULL if this information will not be used.
226 /// \param[in] ITraits Information about invalidation for a particular
227 /// region/symbol.
228 /// \param[in,out] InvalidatedTopLevel A vector to fill with regions
229 //// explicitly being invalidated. Pass \c NULL if this
230 /// information will not be used.
231 /// \param[in,out] Invalidated A vector to fill with any regions being
232 /// invalidated. This should include any regions explicitly invalidated
233 /// even if they do not currently have bindings. Pass \c NULL if this
234 /// information will not be used.
236 Store store, ArrayRef<SVal> Values, const Expr *Ex, unsigned Count,
237 const LocationContext *LCtx, const CallEvent *Call,
239 InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0;
240
241 /// enterStackFrame - Let the StoreManager to do something when execution
242 /// engine is about to execute into a callee.
244 const CallEvent &Call,
245 const StackFrameContext *CalleeCtx);
246
247 /// Finds the transitive closure of symbols within the given region.
248 ///
249 /// Returns false if the visitor aborted the scan.
250 virtual bool scanReachableSymbols(Store S, const MemRegion *R,
251 ScanReachableSymbols &Visitor) = 0;
252
253 virtual void printJson(raw_ostream &Out, Store S, const char *NL,
254 unsigned int Space, bool IsDot) const = 0;
255
257 public:
259
260 /// \return whether the iteration should continue.
261 virtual bool HandleBinding(StoreManager& SMgr, Store store,
262 const MemRegion *region, SVal val) = 0;
263 };
264
266 SymbolRef Sym;
267 const MemRegion* Binding = nullptr;
268 bool First = true;
269
270 public:
271 FindUniqueBinding(SymbolRef sym) : Sym(sym) {}
272
273 explicit operator bool() { return First && Binding; }
274
275 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
276 SVal val) override;
277 const MemRegion *getRegion() { return Binding; }
278 };
279
280 /// iterBindings - Iterate over the bindings in the Store.
281 virtual void iterBindings(Store store, BindingsHandler& f) = 0;
282
283protected:
284 const ElementRegion *MakeElementRegion(const SubRegion *baseRegion,
285 QualType pointeeTy,
286 uint64_t index = 0);
287
288private:
289 SVal getLValueFieldOrIvar(const Decl *decl, SVal base);
290};
291
293 : store(store), mgr(smgr) {
294 if (store)
295 mgr.incrementReferenceCount(store);
296}
297
299 : store(sr.store), mgr(sr.mgr)
300{
301 if (store)
302 mgr.incrementReferenceCount(store);
303}
304
306 if (store)
307 mgr.decrementReferenceCount(store);
308}
309
310inline StoreRef &StoreRef::operator=(StoreRef const &newStore) {
311 assert(&newStore.mgr == &mgr);
312 if (store != newStore.store) {
313 mgr.incrementReferenceCount(newStore.store);
314 mgr.decrementReferenceCount(store);
315 store = newStore.getStore();
316 }
317 return *this;
318}
319
320// FIXME: Do we need to pass ProgramStateManager anymore?
321std::unique_ptr<StoreManager>
323
324} // namespace ento
325
326} // namespace clang
327
328#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
#define V(N, I)
Definition: ASTContext.h:3341
const Decl * D
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
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:187
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:3498
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:3030
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
A (possibly-)qualified type.
Definition: Type.h:941
It represents a stack frame of the call stack (based on CallEvent).
Represents a variable declaration or definition.
Definition: Decl.h:879
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
ElementRegion is used to represent both array elements and casts.
Definition: MemRegion.h:1199
const CompoundLiteralRegion * getCompoundLiteralRegion(const CompoundLiteralExpr *CL, const LocationContext *LC)
getCompoundLiteralRegion - Retrieve the region associated with a given CompoundLiteral.
Definition: MemRegion.cpp:1154
const VarRegion * getVarRegion(const VarDecl *VD, const LocationContext *LC)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and LocationC...
Definition: MemRegion.cpp:1002
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:97
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1629
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:377
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
A utility class that visits the reachable symbols using a custom SymbolVisitor.
Definition: ProgramState.h:885
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:533
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:252
ProgramStateManager & StateMgr
Definition: Store.h:56
SValBuilder & getSValBuilder()
Definition: Store.h:133
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition: Store.h:146
virtual bool scanReachableSymbols(Store S, const MemRegion *R, ScanReachableSymbols &Visitor)=0
Finds the transitive closure of symbols within the given region.
virtual StoreRef Bind(Store store, Loc loc, SVal val)=0
Return a store with the specified value bound to the given location.
MemRegionManager & getRegionManager()
getRegionManager - Returns the internal RegionManager object that is used to query and manipulate Mem...
Definition: Store.h:131
std::optional< SVal > evalBaseToDerived(SVal Base, QualType DerivedPtrType)
Attempts to do a down cast.
Definition: Store.cpp:316
const ElementRegion * MakeElementRegion(const SubRegion *baseRegion, QualType pointeeTy, uint64_t index=0)
Definition: Store.cpp:60
StoreRef enterStackFrame(Store store, const CallEvent &Call, const StackFrameContext *CalleeCtx)
enterStackFrame - Let the StoreManager to do something when execution engine is about to execute into...
Definition: Store.cpp:46
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:59
SValBuilder & svalBuilder
Definition: Store.h:55
virtual StoreRef getInitialStore(const LocationContext *InitLoc)=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:439
virtual StoreRef BindDefaultZero(Store store, const MemRegion *R)=0
Return a store with in which all values within the given region are reset to zero.
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:201
virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, SymbolReaper &SymReaper)=0
virtual StoreRef invalidateRegions(Store store, ArrayRef< SVal > Values, const Expr *Ex, unsigned Count, const LocationContext *LCtx, 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:196
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.
virtual StoreRef BindDefaultInitial(Store store, const MemRegion *R, SVal V)=0
Return a store with the specified value bound to all sub-regions of the region.
std::optional< SVal > getDefaultBinding(nonloc::LazyCompoundVal lcv)
Return the default value bound to a LazyCompoundVal.
Definition: Store.h:97
virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC)
Definition: Store.h:135
const ElementRegion * GetElementZeroRegion(const SubRegion *R, QualType T)
Definition: Store.cpp:67
virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base)
Definition: Store.cpp:443
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:74
ASTContext & Ctx
Definition: Store.h:60
Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL, const LocationContext *LC)
Definition: Store.h:139
Store getStore() const
Definition: StoreRef.h:46
StoreRef & operator=(StoreRef const &newStore)
Definition: Store.h:310
StoreRef(Store store, StoreManager &smgr)
Definition: Store.h:292
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:446
Symbolic value.
Definition: SymExpr.h:30
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:383
LLVM_ATTRIBUTE_RETURNS_NONNULL const TypedValueRegion * getRegion() const
This function itself is immaterial.
Definition: SVals.cpp:194
const void * getStore() const
It might return null.
Definition: SVals.cpp:190
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition: Store.h:51
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.
const FunctionProtoType * T
#define bool
Definition: stdbool.h:24