Store.h revision 239462
1//== Store.h - Interface for maps from Locations to Values ------*- C++ -*--==//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defined the types Store and StoreManager.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_GR_STORE_H
15#define LLVM_CLANG_GR_STORE_H
16
17#include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/Optional.h"
22
23namespace clang {
24
25class Stmt;
26class Expr;
27class ObjCIvarDecl;
28class StackFrameContext;
29
30namespace ento {
31
32class CallEvent;
33class ProgramState;
34class ProgramStateManager;
35class ScanReachableSymbols;
36
37class StoreManager {
38protected:
39  SValBuilder &svalBuilder;
40  ProgramStateManager &StateMgr;
41
42  /// MRMgr - Manages region objects associated with this StoreManager.
43  MemRegionManager &MRMgr;
44  ASTContext &Ctx;
45
46  StoreManager(ProgramStateManager &stateMgr);
47
48public:
49  virtual ~StoreManager() {}
50
51  /// Return the value bound to specified location in a given state.
52  /// \param[in] store The analysis state.
53  /// \param[in] loc The symbolic memory location.
54  /// \param[in] T An optional type that provides a hint indicating the
55  ///   expected type of the returned value.  This is used if the value is
56  ///   lazily computed.
57  /// \return The value bound to the location \c loc.
58  virtual SVal getBinding(Store store, Loc loc, QualType T = QualType()) = 0;
59
60  /// Return a state with the specified value bound to the given location.
61  /// \param[in] store The analysis state.
62  /// \param[in] loc The symbolic memory location.
63  /// \param[in] val The value to bind to location \c loc.
64  /// \return A pointer to a ProgramState object that contains the same
65  ///   bindings as \c state with the addition of having the value specified
66  ///   by \c val bound to the location given for \c loc.
67  virtual StoreRef Bind(Store store, Loc loc, SVal val) = 0;
68
69  virtual StoreRef BindDefault(Store store, const MemRegion *R, SVal V);
70  virtual StoreRef Remove(Store St, Loc L) = 0;
71
72  /// BindCompoundLiteral - Return the store that has the bindings currently
73  ///  in 'store' plus the bindings for the CompoundLiteral.  'R' is the region
74  ///  for the compound literal and 'BegInit' and 'EndInit' represent an
75  ///  array of initializer values.
76  virtual StoreRef BindCompoundLiteral(Store store,
77                                       const CompoundLiteralExpr *cl,
78                                       const LocationContext *LC, SVal v) = 0;
79
80  /// getInitialStore - Returns the initial "empty" store representing the
81  ///  value bindings upon entry to an analyzed function.
82  virtual StoreRef getInitialStore(const LocationContext *InitLoc) = 0;
83
84  /// getRegionManager - Returns the internal RegionManager object that is
85  ///  used to query and manipulate MemRegion objects.
86  MemRegionManager& getRegionManager() { return MRMgr; }
87
88  virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC) {
89    return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC));
90  }
91
92  Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL,
93                               const LocationContext *LC) {
94    return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC));
95  }
96
97  virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base);
98
99  virtual SVal getLValueField(const FieldDecl *D, SVal Base) {
100    return getLValueFieldOrIvar(D, Base);
101  }
102
103  virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base);
104
105  // FIXME: This should soon be eliminated altogether; clients should deal with
106  // region extents directly.
107  virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
108                                                 const MemRegion *region,
109                                                 QualType EleTy) {
110    return UnknownVal();
111  }
112
113  /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit
114  ///  conversions between arrays and pointers.
115  virtual SVal ArrayToPointer(Loc Array) = 0;
116
117  /// Evaluates DerivedToBase casts.
118  SVal evalDerivedToBase(SVal derived, const CastExpr *Cast);
119
120  /// Evaluates a derived-to-base cast through a single level of derivation.
121  virtual SVal evalDerivedToBase(SVal derived, QualType derivedPtrType) = 0;
122
123  /// \brief Evaluates C++ dynamic_cast cast.
124  /// The callback may result in the following 3 scenarios:
125  ///  - Successful cast (ex: derived is subclass of base).
126  ///  - Failed cast (ex: derived is definitely not a subclass of base).
127  ///  - We don't know (base is a symbolic region and we don't have
128  ///    enough info to determine if the cast will succeed at run time).
129  /// The function returns an SVal representing the derived class; it's
130  /// valid only if Failed flag is set to false.
131  virtual SVal evalDynamicCast(SVal base, QualType derivedPtrType,
132                                 bool &Failed) = 0;
133
134  const ElementRegion *GetElementZeroRegion(const MemRegion *R, QualType T);
135
136  /// castRegion - Used by ExprEngine::VisitCast to handle casts from
137  ///  a MemRegion* to a specific location type.  'R' is the region being
138  ///  casted and 'CastToTy' the result type of the cast.
139  const MemRegion *castRegion(const MemRegion *region, QualType CastToTy);
140
141  virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
142                                      SymbolReaper& SymReaper) = 0;
143
144  virtual StoreRef BindDecl(Store store, const VarRegion *VR, SVal initVal) = 0;
145
146  virtual StoreRef BindDeclWithNoInit(Store store, const VarRegion *VR) = 0;
147
148  virtual bool includedInBindings(Store store,
149                                  const MemRegion *region) const = 0;
150
151  /// If the StoreManager supports it, increment the reference count of
152  /// the specified Store object.
153  virtual void incrementReferenceCount(Store store) {}
154
155  /// If the StoreManager supports it, decrement the reference count of
156  /// the specified Store object.  If the reference count hits 0, the memory
157  /// associated with the object is recycled.
158  virtual void decrementReferenceCount(Store store) {}
159
160  typedef llvm::DenseSet<SymbolRef> InvalidatedSymbols;
161  typedef SmallVector<const MemRegion *, 8> InvalidatedRegions;
162
163  /// invalidateRegions - Clears out the specified regions from the store,
164  ///  marking their values as unknown. Depending on the store, this may also
165  ///  invalidate additional regions that may have changed based on accessing
166  ///  the given regions. Optionally, invalidates non-static globals as well.
167  /// \param[in] store The initial store
168  /// \param[in] Regions The regions to invalidate.
169  /// \param[in] E The current statement being evaluated. Used to conjure
170  ///   symbols to mark the values of invalidated regions.
171  /// \param[in] Count The current block count. Used to conjure
172  ///   symbols to mark the values of invalidated regions.
173  /// \param[in,out] IS A set to fill with any symbols that are no longer
174  ///   accessible. Pass \c NULL if this information will not be used.
175  /// \param[in] Call The call expression which will be used to determine which
176  ///   globals should get invalidated.
177  /// \param[in,out] Invalidated A vector to fill with any regions being
178  ///   invalidated. This should include any regions explicitly invalidated
179  ///   even if they do not currently have bindings. Pass \c NULL if this
180  ///   information will not be used.
181  virtual StoreRef invalidateRegions(Store store,
182                                     ArrayRef<const MemRegion *> Regions,
183                                     const Expr *E, unsigned Count,
184                                     const LocationContext *LCtx,
185                                     InvalidatedSymbols &IS,
186                                     const CallEvent *Call,
187                                     InvalidatedRegions *Invalidated) = 0;
188
189  /// enterStackFrame - Let the StoreManager to do something when execution
190  /// engine is about to execute into a callee.
191  StoreRef enterStackFrame(Store store,
192                           const CallEvent &Call,
193                           const StackFrameContext *CalleeCtx);
194
195  /// Finds the transitive closure of symbols within the given region.
196  ///
197  /// Returns false if the visitor aborted the scan.
198  virtual bool scanReachableSymbols(Store S, const MemRegion *R,
199                                    ScanReachableSymbols &Visitor) = 0;
200
201  virtual void print(Store store, raw_ostream &Out,
202                     const char* nl, const char *sep) = 0;
203
204  class BindingsHandler {
205  public:
206    virtual ~BindingsHandler();
207    virtual bool HandleBinding(StoreManager& SMgr, Store store,
208                               const MemRegion *region, SVal val) = 0;
209  };
210
211  class FindUniqueBinding :
212  public BindingsHandler {
213    SymbolRef Sym;
214    const MemRegion* Binding;
215    bool First;
216
217  public:
218    FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
219
220    bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
221                       SVal val);
222    operator bool() { return First && Binding; }
223    const MemRegion *getRegion() { return Binding; }
224  };
225
226  /// iterBindings - Iterate over the bindings in the Store.
227  virtual void iterBindings(Store store, BindingsHandler& f) = 0;
228
229protected:
230  const MemRegion *MakeElementRegion(const MemRegion *baseRegion,
231                                     QualType pointeeTy, uint64_t index = 0);
232
233  /// CastRetrievedVal - Used by subclasses of StoreManager to implement
234  ///  implicit casts that arise from loads from regions that are reinterpreted
235  ///  as another region.
236  SVal CastRetrievedVal(SVal val, const TypedValueRegion *region,
237                        QualType castTy, bool performTestOnly = true);
238
239private:
240  SVal getLValueFieldOrIvar(const Decl *decl, SVal base);
241};
242
243
244inline StoreRef::StoreRef(Store store, StoreManager & smgr)
245  : store(store), mgr(smgr) {
246  if (store)
247    mgr.incrementReferenceCount(store);
248}
249
250inline StoreRef::StoreRef(const StoreRef &sr)
251  : store(sr.store), mgr(sr.mgr)
252{
253  if (store)
254    mgr.incrementReferenceCount(store);
255}
256
257inline StoreRef::~StoreRef() {
258  if (store)
259    mgr.decrementReferenceCount(store);
260}
261
262inline StoreRef &StoreRef::operator=(StoreRef const &newStore) {
263  assert(&newStore.mgr == &mgr);
264  if (store != newStore.store) {
265    mgr.incrementReferenceCount(newStore.store);
266    mgr.decrementReferenceCount(store);
267    store = newStore.getStore();
268  }
269  return *this;
270}
271
272// FIXME: Do we need to pass ProgramStateManager anymore?
273StoreManager *CreateRegionStoreManager(ProgramStateManager& StMgr);
274StoreManager *CreateFieldsOnlyRegionStoreManager(ProgramStateManager& StMgr);
275
276} // end GR namespace
277
278} // end clang namespace
279
280#endif
281