ProgramState.h revision da8d37ce42d2db4e1e76ee6f7f38f10f6b0ef0f8
1//== ProgramState.h - Path-sensitive "State" for tracking 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 defines the state of the program along the analysisa path.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_GR_VALUESTATE_H
15#define LLVM_CLANG_GR_VALUESTATE_H
16
17#include "clang/Basic/LLVM.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
24#include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/ADT/ImmutableMap.h"
27#include "llvm/ADT/PointerIntPair.h"
28
29namespace llvm {
30class APSInt;
31class BumpPtrAllocator;
32}
33
34namespace clang {
35class ASTContext;
36
37namespace ento {
38
39class CallEvent;
40class CallEventManager;
41
42typedef ConstraintManager* (*ConstraintManagerCreator)(ProgramStateManager&,
43                                                       SubEngine*);
44typedef StoreManager* (*StoreManagerCreator)(ProgramStateManager&);
45
46//===----------------------------------------------------------------------===//
47// ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
48//===----------------------------------------------------------------------===//
49
50template <typename T> struct ProgramStatePartialTrait;
51
52template <typename T> struct ProgramStateTrait {
53  typedef typename T::data_type data_type;
54  static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
55  static inline data_type MakeData(void *const* P) {
56    return P ? (data_type) *P : (data_type) 0;
57  }
58};
59
60/// \class ProgramState
61/// ProgramState - This class encapsulates:
62///
63///    1. A mapping from expressions to values (Environment)
64///    2. A mapping from locations to values (Store)
65///    3. Constraints on symbolic values (GenericDataMap)
66///
67///  Together these represent the "abstract state" of a program.
68///
69///  ProgramState is intended to be used as a functional object; that is,
70///  once it is created and made "persistent" in a FoldingSet, its
71///  values will never change.
72class ProgramState : public llvm::FoldingSetNode {
73public:
74  typedef llvm::ImmutableSet<llvm::APSInt*>                IntSetTy;
75  typedef llvm::ImmutableMap<void*, void*>                 GenericDataMap;
76
77private:
78  void operator=(const ProgramState& R) LLVM_DELETED_FUNCTION;
79
80  friend class ProgramStateManager;
81  friend class ExplodedGraph;
82  friend class ExplodedNode;
83
84  ProgramStateManager *stateMgr;
85  Environment Env;           // Maps a Stmt to its current SVal.
86  Store store;               // Maps a location to its current value.
87  GenericDataMap   GDM;      // Custom data stored by a client of this class.
88  unsigned refCount;
89
90  /// makeWithStore - Return a ProgramState with the same values as the current
91  ///  state with the exception of using the specified Store.
92  ProgramStateRef makeWithStore(const StoreRef &store) const;
93
94  void setStore(const StoreRef &storeRef);
95
96public:
97  /// This ctor is used when creating the first ProgramState object.
98  ProgramState(ProgramStateManager *mgr, const Environment& env,
99          StoreRef st, GenericDataMap gdm);
100
101  /// Copy ctor - We must explicitly define this or else the "Next" ptr
102  ///  in FoldingSetNode will also get copied.
103  ProgramState(const ProgramState &RHS);
104
105  ~ProgramState();
106
107  /// Return the ProgramStateManager associated with this state.
108  ProgramStateManager &getStateManager() const {
109    return *stateMgr;
110  }
111
112  /// Return the ConstraintManager.
113  ConstraintManager &getConstraintManager() const;
114
115  /// getEnvironment - Return the environment associated with this state.
116  ///  The environment is the mapping from expressions to values.
117  const Environment& getEnvironment() const { return Env; }
118
119  /// Return the store associated with this state.  The store
120  ///  is a mapping from locations to values.
121  Store getStore() const { return store; }
122
123
124  /// getGDM - Return the generic data map associated with this state.
125  GenericDataMap getGDM() const { return GDM; }
126
127  void setGDM(GenericDataMap gdm) { GDM = gdm; }
128
129  /// Profile - Profile the contents of a ProgramState object for use in a
130  ///  FoldingSet.  Two ProgramState objects are considered equal if they
131  ///  have the same Environment, Store, and GenericDataMap.
132  static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
133    V->Env.Profile(ID);
134    ID.AddPointer(V->store);
135    V->GDM.Profile(ID);
136  }
137
138  /// Profile - Used to profile the contents of this object for inclusion
139  ///  in a FoldingSet.
140  void Profile(llvm::FoldingSetNodeID& ID) const {
141    Profile(ID, this);
142  }
143
144  BasicValueFactory &getBasicVals() const;
145  SymbolManager &getSymbolManager() const;
146
147  //==---------------------------------------------------------------------==//
148  // Constraints on values.
149  //==---------------------------------------------------------------------==//
150  //
151  // Each ProgramState records constraints on symbolic values.  These constraints
152  // are managed using the ConstraintManager associated with a ProgramStateManager.
153  // As constraints gradually accrue on symbolic values, added constraints
154  // may conflict and indicate that a state is infeasible (as no real values
155  // could satisfy all the constraints).  This is the principal mechanism
156  // for modeling path-sensitivity in ExprEngine/ProgramState.
157  //
158  // Various "assume" methods form the interface for adding constraints to
159  // symbolic values.  A call to 'assume' indicates an assumption being placed
160  // on one or symbolic values.  'assume' methods take the following inputs:
161  //
162  //  (1) A ProgramState object representing the current state.
163  //
164  //  (2) The assumed constraint (which is specific to a given "assume" method).
165  //
166  //  (3) A binary value "Assumption" that indicates whether the constraint is
167  //      assumed to be true or false.
168  //
169  // The output of "assume*" is a new ProgramState object with the added constraints.
170  // If no new state is feasible, NULL is returned.
171  //
172
173  /// Assumes that the value of \p cond is zero (if \p assumption is "false")
174  /// or non-zero (if \p assumption is "true").
175  ///
176  /// This returns a new state with the added constraint on \p cond.
177  /// If no new state is feasible, NULL is returned.
178  ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
179
180  /// Assumes both "true" and "false" for \p cond, and returns both
181  /// corresponding states (respectively).
182  ///
183  /// This is more efficient than calling assume() twice. Note that one (but not
184  /// both) of the returned states may be NULL.
185  std::pair<ProgramStateRef, ProgramStateRef>
186  assume(DefinedOrUnknownSVal cond) const;
187
188  ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
189                               DefinedOrUnknownSVal upperBound,
190                               bool assumption,
191                               QualType IndexType = QualType()) const;
192
193  /// \brief Check if the given SVal is constrained to zero or is a zero
194  ///        constant.
195  ConditionTruthVal isNull(SVal V) const;
196
197  /// Utility method for getting regions.
198  const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
199
200  //==---------------------------------------------------------------------==//
201  // Binding and retrieving values to/from the environment and symbolic store.
202  //==---------------------------------------------------------------------==//
203
204  /// Create a new state by binding the value 'V' to the statement 'S' in the
205  /// state's environment.
206  ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
207                               SVal V, bool Invalidate = true) const;
208
209  ProgramStateRef bindLoc(Loc location,
210                          SVal V,
211                          bool notifyChanges = true) const;
212
213  ProgramStateRef bindLoc(SVal location, SVal V) const;
214
215  ProgramStateRef bindDefault(SVal loc, SVal V) const;
216
217  ProgramStateRef killBinding(Loc LV) const;
218
219  /// \brief Returns the state with bindings for the given regions
220  ///  cleared from the store.
221  ///
222  /// Optionally invalidates global regions as well.
223  ///
224  /// \param Regions the set of regions to be invalidated.
225  /// \param E the expression that caused the invalidation.
226  /// \param BlockCount The number of times the current basic block has been
227  //         visited.
228  /// \param CausesPointerEscape the flag is set to true when
229  ///        the invalidation entails escape of a symbol (representing a
230  ///        pointer). For example, due to it being passed as an argument in a
231  ///        call.
232  /// \param IS the set of invalidated symbols.
233  /// \param Call if non-null, the invalidated regions represent parameters to
234  ///        the call and should be considered directly invalidated.
235  /// \param HTraits information about special handling for a particular
236  ///        region/symbol.
237  ProgramStateRef
238  invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
239                    unsigned BlockCount, const LocationContext *LCtx,
240                    bool CausesPointerEscape, InvalidatedSymbols *IS = 0,
241                    const CallEvent *Call = 0,
242                    RegionAndSymbolInvalidationTraits *HTraits = 0) const;
243
244  ProgramStateRef
245  invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
246                    unsigned BlockCount, const LocationContext *LCtx,
247                    bool CausesPointerEscape, InvalidatedSymbols *IS = 0,
248                    const CallEvent *Call = 0,
249                    RegionAndSymbolInvalidationTraits *HTraits = 0) const;
250
251  /// enterStackFrame - Returns the state for entry to the given stack frame,
252  ///  preserving the current state.
253  ProgramStateRef enterStackFrame(const CallEvent &Call,
254                                  const StackFrameContext *CalleeCtx) const;
255
256  /// Get the lvalue for a variable reference.
257  Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
258
259  Loc getLValue(const CompoundLiteralExpr *literal,
260                const LocationContext *LC) const;
261
262  /// Get the lvalue for an ivar reference.
263  SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
264
265  /// Get the lvalue for a field reference.
266  SVal getLValue(const FieldDecl *decl, SVal Base) const;
267
268  /// Get the lvalue for an indirect field reference.
269  SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
270
271  /// Get the lvalue for an array index.
272  SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
273
274  /// Returns the SVal bound to the statement 'S' in the state's environment.
275  SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
276
277  SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
278
279  /// \brief Return the value bound to the specified location.
280  /// Returns UnknownVal() if none found.
281  SVal getSVal(Loc LV, QualType T = QualType()) const;
282
283  /// Returns the "raw" SVal bound to LV before any value simplfication.
284  SVal getRawSVal(Loc LV, QualType T= QualType()) const;
285
286  /// \brief Return the value bound to the specified location.
287  /// Returns UnknownVal() if none found.
288  SVal getSVal(const MemRegion* R) const;
289
290  SVal getSValAsScalarOrLoc(const MemRegion *R) const;
291
292  /// \brief Visits the symbols reachable from the given SVal using the provided
293  /// SymbolVisitor.
294  ///
295  /// This is a convenience API. Consider using ScanReachableSymbols class
296  /// directly when making multiple scans on the same state with the same
297  /// visitor to avoid repeated initialization cost.
298  /// \sa ScanReachableSymbols
299  bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
300
301  /// \brief Visits the symbols reachable from the SVals in the given range
302  /// using the provided SymbolVisitor.
303  bool scanReachableSymbols(const SVal *I, const SVal *E,
304                            SymbolVisitor &visitor) const;
305
306  /// \brief Visits the symbols reachable from the regions in the given
307  /// MemRegions range using the provided SymbolVisitor.
308  bool scanReachableSymbols(const MemRegion * const *I,
309                            const MemRegion * const *E,
310                            SymbolVisitor &visitor) const;
311
312  template <typename CB> CB scanReachableSymbols(SVal val) const;
313  template <typename CB> CB scanReachableSymbols(const SVal *beg,
314                                                 const SVal *end) const;
315
316  template <typename CB> CB
317  scanReachableSymbols(const MemRegion * const *beg,
318                       const MemRegion * const *end) const;
319
320  /// Create a new state in which the statement is marked as tainted.
321  ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
322                               TaintTagType Kind = TaintTagGeneric) const;
323
324  /// Create a new state in which the symbol is marked as tainted.
325  ProgramStateRef addTaint(SymbolRef S,
326                               TaintTagType Kind = TaintTagGeneric) const;
327
328  /// Create a new state in which the region symbol is marked as tainted.
329  ProgramStateRef addTaint(const MemRegion *R,
330                               TaintTagType Kind = TaintTagGeneric) const;
331
332  /// Check if the statement is tainted in the current state.
333  bool isTainted(const Stmt *S, const LocationContext *LCtx,
334                 TaintTagType Kind = TaintTagGeneric) const;
335  bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
336  bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
337  bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
338
339  /// \brief Get dynamic type information for a region.
340  DynamicTypeInfo getDynamicTypeInfo(const MemRegion *Reg) const;
341
342  /// \brief Set dynamic type information of the region; return the new state.
343  ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg,
344                                     DynamicTypeInfo NewTy) const;
345
346  /// \brief Set dynamic type information of the region; return the new state.
347  ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg,
348                                     QualType NewTy,
349                                     bool CanBeSubClassed = true) const {
350    return setDynamicTypeInfo(Reg, DynamicTypeInfo(NewTy, CanBeSubClassed));
351  }
352
353  //==---------------------------------------------------------------------==//
354  // Accessing the Generic Data Map (GDM).
355  //==---------------------------------------------------------------------==//
356
357  void *const* FindGDM(void *K) const;
358
359  template<typename T>
360  ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
361
362  template <typename T>
363  typename ProgramStateTrait<T>::data_type
364  get() const {
365    return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
366  }
367
368  template<typename T>
369  typename ProgramStateTrait<T>::lookup_type
370  get(typename ProgramStateTrait<T>::key_type key) const {
371    void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
372    return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
373  }
374
375  template <typename T>
376  typename ProgramStateTrait<T>::context_type get_context() const;
377
378
379  template<typename T>
380  ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
381
382  template<typename T>
383  ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
384                        typename ProgramStateTrait<T>::context_type C) const;
385  template <typename T>
386  ProgramStateRef remove() const;
387
388  template<typename T>
389  ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
390
391  template<typename T>
392  ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
393                     typename ProgramStateTrait<T>::value_type E) const;
394
395  template<typename T>
396  ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
397                     typename ProgramStateTrait<T>::value_type E,
398                     typename ProgramStateTrait<T>::context_type C) const;
399
400  template<typename T>
401  bool contains(typename ProgramStateTrait<T>::key_type key) const {
402    void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
403    return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
404  }
405
406  // Pretty-printing.
407  void print(raw_ostream &Out, const char *nl = "\n",
408             const char *sep = "") const;
409  void printDOT(raw_ostream &Out) const;
410  void printTaint(raw_ostream &Out, const char *nl = "\n",
411                  const char *sep = "") const;
412
413  void dump() const;
414  void dumpTaint() const;
415
416private:
417  friend void ProgramStateRetain(const ProgramState *state);
418  friend void ProgramStateRelease(const ProgramState *state);
419
420  /// \sa invalidateValues()
421  /// \sa invalidateRegions()
422  ProgramStateRef
423  invalidateRegionsImpl(ArrayRef<SVal> Values,
424                        const Expr *E, unsigned BlockCount,
425                        const LocationContext *LCtx,
426                        bool ResultsInSymbolEscape,
427                        InvalidatedSymbols *IS,
428                        RegionAndSymbolInvalidationTraits *HTraits,
429                        const CallEvent *Call) const;
430};
431
432//===----------------------------------------------------------------------===//
433// ProgramStateManager - Factory object for ProgramStates.
434//===----------------------------------------------------------------------===//
435
436class ProgramStateManager {
437  friend class ProgramState;
438  friend void ProgramStateRelease(const ProgramState *state);
439private:
440  /// Eng - The SubEngine that owns this state manager.
441  SubEngine *Eng; /* Can be null. */
442
443  EnvironmentManager                   EnvMgr;
444  OwningPtr<StoreManager>              StoreMgr;
445  OwningPtr<ConstraintManager>         ConstraintMgr;
446
447  ProgramState::GenericDataMap::Factory     GDMFactory;
448
449  typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
450  GDMContextsTy GDMContexts;
451
452  /// StateSet - FoldingSet containing all the states created for analyzing
453  ///  a particular function.  This is used to unique states.
454  llvm::FoldingSet<ProgramState> StateSet;
455
456  /// Object that manages the data for all created SVals.
457  OwningPtr<SValBuilder> svalBuilder;
458
459  /// Manages memory for created CallEvents.
460  OwningPtr<CallEventManager> CallEventMgr;
461
462  /// A BumpPtrAllocator to allocate states.
463  llvm::BumpPtrAllocator &Alloc;
464
465  /// A vector of ProgramStates that we can reuse.
466  std::vector<ProgramState *> freeStates;
467
468public:
469  ProgramStateManager(ASTContext &Ctx,
470                 StoreManagerCreator CreateStoreManager,
471                 ConstraintManagerCreator CreateConstraintManager,
472                 llvm::BumpPtrAllocator& alloc,
473                 SubEngine *subeng);
474
475  ~ProgramStateManager();
476
477  ProgramStateRef getInitialState(const LocationContext *InitLoc);
478
479  ASTContext &getContext() { return svalBuilder->getContext(); }
480  const ASTContext &getContext() const { return svalBuilder->getContext(); }
481
482  BasicValueFactory &getBasicVals() {
483    return svalBuilder->getBasicValueFactory();
484  }
485
486  SValBuilder &getSValBuilder() {
487    return *svalBuilder;
488  }
489
490  SymbolManager &getSymbolManager() {
491    return svalBuilder->getSymbolManager();
492  }
493  const SymbolManager &getSymbolManager() const {
494    return svalBuilder->getSymbolManager();
495  }
496
497  llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
498
499  MemRegionManager& getRegionManager() {
500    return svalBuilder->getRegionManager();
501  }
502  const MemRegionManager& getRegionManager() const {
503    return svalBuilder->getRegionManager();
504  }
505
506  CallEventManager &getCallEventManager() { return *CallEventMgr; }
507
508  StoreManager& getStoreManager() { return *StoreMgr; }
509  ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
510  SubEngine* getOwningEngine() { return Eng; }
511
512  ProgramStateRef removeDeadBindings(ProgramStateRef St,
513                                    const StackFrameContext *LCtx,
514                                    SymbolReaper& SymReaper);
515
516public:
517
518  SVal ArrayToPointer(Loc Array, QualType ElementTy) {
519    return StoreMgr->ArrayToPointer(Array, ElementTy);
520  }
521
522  // Methods that manipulate the GDM.
523  ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
524  ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
525
526  // Methods that query & manipulate the Store.
527
528  void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
529    StoreMgr->iterBindings(state->getStore(), F);
530  }
531
532  ProgramStateRef getPersistentState(ProgramState &Impl);
533  ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
534                                           ProgramStateRef GDMState);
535
536  bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
537    return S1->Env == S2->Env;
538  }
539
540  bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
541    return S1->store == S2->store;
542  }
543
544  //==---------------------------------------------------------------------==//
545  // Generic Data Map methods.
546  //==---------------------------------------------------------------------==//
547  //
548  // ProgramStateManager and ProgramState support a "generic data map" that allows
549  // different clients of ProgramState objects to embed arbitrary data within a
550  // ProgramState object.  The generic data map is essentially an immutable map
551  // from a "tag" (that acts as the "key" for a client) and opaque values.
552  // Tags/keys and values are simply void* values.  The typical way that clients
553  // generate unique tags are by taking the address of a static variable.
554  // Clients are responsible for ensuring that data values referred to by a
555  // the data pointer are immutable (and thus are essentially purely functional
556  // data).
557  //
558  // The templated methods below use the ProgramStateTrait<T> class
559  // to resolve keys into the GDM and to return data values to clients.
560  //
561
562  // Trait based GDM dispatch.
563  template <typename T>
564  ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
565    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
566                  ProgramStateTrait<T>::MakeVoidPtr(D));
567  }
568
569  template<typename T>
570  ProgramStateRef set(ProgramStateRef st,
571                     typename ProgramStateTrait<T>::key_type K,
572                     typename ProgramStateTrait<T>::value_type V,
573                     typename ProgramStateTrait<T>::context_type C) {
574
575    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
576     ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
577  }
578
579  template <typename T>
580  ProgramStateRef add(ProgramStateRef st,
581                     typename ProgramStateTrait<T>::key_type K,
582                     typename ProgramStateTrait<T>::context_type C) {
583    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
584        ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
585  }
586
587  template <typename T>
588  ProgramStateRef remove(ProgramStateRef st,
589                        typename ProgramStateTrait<T>::key_type K,
590                        typename ProgramStateTrait<T>::context_type C) {
591
592    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
593     ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
594  }
595
596  template <typename T>
597  ProgramStateRef remove(ProgramStateRef st) {
598    return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
599  }
600
601  void *FindGDMContext(void *index,
602                       void *(*CreateContext)(llvm::BumpPtrAllocator&),
603                       void  (*DeleteContext)(void*));
604
605  template <typename T>
606  typename ProgramStateTrait<T>::context_type get_context() {
607    void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
608                             ProgramStateTrait<T>::CreateContext,
609                             ProgramStateTrait<T>::DeleteContext);
610
611    return ProgramStateTrait<T>::MakeContext(p);
612  }
613
614  void EndPath(ProgramStateRef St) {
615    ConstraintMgr->EndPath(St);
616  }
617};
618
619
620//===----------------------------------------------------------------------===//
621// Out-of-line method definitions for ProgramState.
622//===----------------------------------------------------------------------===//
623
624inline ConstraintManager &ProgramState::getConstraintManager() const {
625  return stateMgr->getConstraintManager();
626}
627
628inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
629                                                const LocationContext *LC) const
630{
631  return getStateManager().getRegionManager().getVarRegion(D, LC);
632}
633
634inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
635                                      bool Assumption) const {
636  if (Cond.isUnknown())
637    return this;
638
639  return getStateManager().ConstraintMgr
640      ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
641}
642
643inline std::pair<ProgramStateRef , ProgramStateRef >
644ProgramState::assume(DefinedOrUnknownSVal Cond) const {
645  if (Cond.isUnknown())
646    return std::make_pair(this, this);
647
648  return getStateManager().ConstraintMgr
649      ->assumeDual(this, Cond.castAs<DefinedSVal>());
650}
651
652inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
653  if (Optional<Loc> L = LV.getAs<Loc>())
654    return bindLoc(*L, V);
655  return this;
656}
657
658inline Loc ProgramState::getLValue(const VarDecl *VD,
659                               const LocationContext *LC) const {
660  return getStateManager().StoreMgr->getLValueVar(VD, LC);
661}
662
663inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
664                               const LocationContext *LC) const {
665  return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
666}
667
668inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
669  return getStateManager().StoreMgr->getLValueIvar(D, Base);
670}
671
672inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
673  return getStateManager().StoreMgr->getLValueField(D, Base);
674}
675
676inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
677                                    SVal Base) const {
678  StoreManager &SM = *getStateManager().StoreMgr;
679  for (IndirectFieldDecl::chain_iterator I = D->chain_begin(),
680                                         E = D->chain_end();
681       I != E; ++I) {
682    Base = SM.getLValueField(cast<FieldDecl>(*I), Base);
683  }
684
685  return Base;
686}
687
688inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
689  if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
690    return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
691  return UnknownVal();
692}
693
694inline SVal ProgramState::getSVal(const Stmt *Ex,
695                                  const LocationContext *LCtx) const{
696  return Env.getSVal(EnvironmentEntry(Ex, LCtx),
697                     *getStateManager().svalBuilder);
698}
699
700inline SVal
701ProgramState::getSValAsScalarOrLoc(const Stmt *S,
702                                   const LocationContext *LCtx) const {
703  if (const Expr *Ex = dyn_cast<Expr>(S)) {
704    QualType T = Ex->getType();
705    if (Ex->isGLValue() || Loc::isLocType(T) ||
706        T->isIntegralOrEnumerationType())
707      return getSVal(S, LCtx);
708  }
709
710  return UnknownVal();
711}
712
713inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
714  return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
715}
716
717inline SVal ProgramState::getSVal(const MemRegion* R) const {
718  return getStateManager().StoreMgr->getBinding(getStore(),
719                                                loc::MemRegionVal(R));
720}
721
722inline BasicValueFactory &ProgramState::getBasicVals() const {
723  return getStateManager().getBasicVals();
724}
725
726inline SymbolManager &ProgramState::getSymbolManager() const {
727  return getStateManager().getSymbolManager();
728}
729
730template<typename T>
731ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
732  return getStateManager().add<T>(this, K, get_context<T>());
733}
734
735template <typename T>
736typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
737  return getStateManager().get_context<T>();
738}
739
740template<typename T>
741ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
742  return getStateManager().remove<T>(this, K, get_context<T>());
743}
744
745template<typename T>
746ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
747                               typename ProgramStateTrait<T>::context_type C) const {
748  return getStateManager().remove<T>(this, K, C);
749}
750
751template <typename T>
752ProgramStateRef ProgramState::remove() const {
753  return getStateManager().remove<T>(this);
754}
755
756template<typename T>
757ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
758  return getStateManager().set<T>(this, D);
759}
760
761template<typename T>
762ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
763                            typename ProgramStateTrait<T>::value_type E) const {
764  return getStateManager().set<T>(this, K, E, get_context<T>());
765}
766
767template<typename T>
768ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
769                            typename ProgramStateTrait<T>::value_type E,
770                            typename ProgramStateTrait<T>::context_type C) const {
771  return getStateManager().set<T>(this, K, E, C);
772}
773
774template <typename CB>
775CB ProgramState::scanReachableSymbols(SVal val) const {
776  CB cb(this);
777  scanReachableSymbols(val, cb);
778  return cb;
779}
780
781template <typename CB>
782CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
783  CB cb(this);
784  scanReachableSymbols(beg, end, cb);
785  return cb;
786}
787
788template <typename CB>
789CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
790                                 const MemRegion * const *end) const {
791  CB cb(this);
792  scanReachableSymbols(beg, end, cb);
793  return cb;
794}
795
796/// \class ScanReachableSymbols
797/// A Utility class that allows to visit the reachable symbols using a custom
798/// SymbolVisitor.
799class ScanReachableSymbols {
800  typedef llvm::DenseSet<const void*> VisitedItems;
801
802  VisitedItems visited;
803  ProgramStateRef state;
804  SymbolVisitor &visitor;
805public:
806
807  ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
808    : state(st), visitor(v) {}
809
810  bool scan(nonloc::LazyCompoundVal val);
811  bool scan(nonloc::CompoundVal val);
812  bool scan(SVal val);
813  bool scan(const MemRegion *R);
814  bool scan(const SymExpr *sym);
815};
816
817} // end ento namespace
818
819} // end clang namespace
820
821#endif
822