ProgramState.h revision ca5d78d0bc3010164f2f9682967d64d7e305a167
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/Store.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
24#include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/ImmutableMap.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  ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
174
175  /// This method assumes both "true" and "false" for 'cond', and
176  ///  returns both corresponding states.  It's shorthand for doing
177  ///  'assume' twice.
178  std::pair<ProgramStateRef , ProgramStateRef >
179  assume(DefinedOrUnknownSVal cond) const;
180
181  ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
182                               DefinedOrUnknownSVal upperBound,
183                               bool assumption,
184                               QualType IndexType = QualType()) const;
185
186  /// Utility method for getting regions.
187  const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
188
189  //==---------------------------------------------------------------------==//
190  // Binding and retrieving values to/from the environment and symbolic store.
191  //==---------------------------------------------------------------------==//
192
193  /// \brief Create a new state with the specified CompoundLiteral binding.
194  /// \param CL the compound literal expression (the binding key)
195  /// \param LC the LocationContext of the binding
196  /// \param V the value to bind.
197  ProgramStateRef bindCompoundLiteral(const CompoundLiteralExpr *CL,
198                                      const LocationContext *LC,
199                                      SVal V) const;
200
201  /// Create a new state by binding the value 'V' to the statement 'S' in the
202  /// state's environment.
203  ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
204                               SVal V, bool Invalidate = true) const;
205
206  /// Create a new state by binding the value 'V' and location 'locaton' to the
207  /// statement 'S' in the state's environment.
208  ProgramStateRef bindExprAndLocation(const Stmt *S,
209                                          const LocationContext *LCtx,
210                                          SVal location, SVal V) const;
211
212  ProgramStateRef bindLoc(Loc location,
213                          SVal V,
214                          bool notifyChanges = true) const;
215
216  ProgramStateRef bindLoc(SVal location, SVal V) const;
217
218  ProgramStateRef bindDefault(SVal loc, SVal V) const;
219
220  ProgramStateRef killBinding(Loc LV) const;
221
222  /// invalidateRegions - Returns the state with bindings for the given regions
223  ///  cleared from the store. The regions are provided as a continuous array
224  ///  from Begin to End. Optionally invalidates global regions as well.
225  ProgramStateRef invalidateRegions(ArrayRef<const MemRegion *> Regions,
226                               const Expr *E, unsigned BlockCount,
227                               const LocationContext *LCtx,
228                               StoreManager::InvalidatedSymbols *IS = 0,
229                               const CallEvent *Call = 0) const;
230
231  /// enterStackFrame - Returns the state for entry to the given stack frame,
232  ///  preserving the current state.
233  ProgramStateRef enterStackFrame(const CallEvent &Call,
234                                  const StackFrameContext *CalleeCtx) const;
235
236  /// Get the lvalue for a variable reference.
237  Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
238
239  Loc getLValue(const CompoundLiteralExpr *literal,
240                const LocationContext *LC) const;
241
242  /// Get the lvalue for an ivar reference.
243  SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
244
245  /// Get the lvalue for a field reference.
246  SVal getLValue(const FieldDecl *decl, SVal Base) const;
247
248  /// Get the lvalue for an indirect field reference.
249  SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
250
251  /// Get the lvalue for an array index.
252  SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
253
254  /// Returns the SVal bound to the statement 'S' in the state's environment.
255  SVal getSVal(const Stmt *S, const LocationContext *LCtx,
256               bool useOnlyDirectBindings = false) const;
257
258  SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
259
260  /// \brief Return the value bound to the specified location.
261  /// Returns UnknownVal() if none found.
262  SVal getSVal(Loc LV, QualType T = QualType()) const;
263
264  /// Returns the "raw" SVal bound to LV before any value simplfication.
265  SVal getRawSVal(Loc LV, QualType T= QualType()) const;
266
267  /// \brief Return the value bound to the specified location.
268  /// Returns UnknownVal() if none found.
269  SVal getSVal(const MemRegion* R) const;
270
271  SVal getSValAsScalarOrLoc(const MemRegion *R) const;
272
273  /// \brief Visits the symbols reachable from the given SVal using the provided
274  /// SymbolVisitor.
275  ///
276  /// This is a convenience API. Consider using ScanReachableSymbols class
277  /// directly when making multiple scans on the same state with the same
278  /// visitor to avoid repeated initialization cost.
279  /// \sa ScanReachableSymbols
280  bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
281
282  /// \brief Visits the symbols reachable from the SVals in the given range
283  /// using the provided SymbolVisitor.
284  bool scanReachableSymbols(const SVal *I, const SVal *E,
285                            SymbolVisitor &visitor) const;
286
287  /// \brief Visits the symbols reachable from the regions in the given
288  /// MemRegions range using the provided SymbolVisitor.
289  bool scanReachableSymbols(const MemRegion * const *I,
290                            const MemRegion * const *E,
291                            SymbolVisitor &visitor) const;
292
293  template <typename CB> CB scanReachableSymbols(SVal val) const;
294  template <typename CB> CB scanReachableSymbols(const SVal *beg,
295                                                 const SVal *end) const;
296
297  template <typename CB> CB
298  scanReachableSymbols(const MemRegion * const *beg,
299                       const MemRegion * const *end) const;
300
301  /// Create a new state in which the statement is marked as tainted.
302  ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
303                               TaintTagType Kind = TaintTagGeneric) const;
304
305  /// Create a new state in which the symbol is marked as tainted.
306  ProgramStateRef addTaint(SymbolRef S,
307                               TaintTagType Kind = TaintTagGeneric) const;
308
309  /// Create a new state in which the region symbol is marked as tainted.
310  ProgramStateRef addTaint(const MemRegion *R,
311                               TaintTagType Kind = TaintTagGeneric) const;
312
313  /// Check if the statement is tainted in the current state.
314  bool isTainted(const Stmt *S, const LocationContext *LCtx,
315                 TaintTagType Kind = TaintTagGeneric) const;
316  bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
317  bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
318  bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
319
320  /// \brief Get dynamic type information for a region.
321  DynamicTypeInfo getDynamicTypeInfo(const MemRegion *Reg) const;
322
323  /// \brief Set dynamic type information of the region; return the new state.
324  ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg,
325                                     DynamicTypeInfo NewTy) const;
326
327  /// \brief Set dynamic type information of the region; return the new state.
328  ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg,
329                                     QualType NewTy,
330                                     bool CanBeSubClassed = true) const {
331    return setDynamicTypeInfo(Reg, DynamicTypeInfo(NewTy, CanBeSubClassed));
332  }
333
334  //==---------------------------------------------------------------------==//
335  // Accessing the Generic Data Map (GDM).
336  //==---------------------------------------------------------------------==//
337
338  void *const* FindGDM(void *K) const;
339
340  template<typename T>
341  ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
342
343  template <typename T>
344  typename ProgramStateTrait<T>::data_type
345  get() const {
346    return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
347  }
348
349  template<typename T>
350  typename ProgramStateTrait<T>::lookup_type
351  get(typename ProgramStateTrait<T>::key_type key) const {
352    void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
353    return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
354  }
355
356  template <typename T>
357  typename ProgramStateTrait<T>::context_type get_context() const;
358
359
360  template<typename T>
361  ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
362
363  template<typename T>
364  ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
365                        typename ProgramStateTrait<T>::context_type C) const;
366  template <typename T>
367  ProgramStateRef remove() const;
368
369  template<typename T>
370  ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
371
372  template<typename T>
373  ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
374                     typename ProgramStateTrait<T>::value_type E) const;
375
376  template<typename T>
377  ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
378                     typename ProgramStateTrait<T>::value_type E,
379                     typename ProgramStateTrait<T>::context_type C) const;
380
381  template<typename T>
382  bool contains(typename ProgramStateTrait<T>::key_type key) const {
383    void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
384    return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
385  }
386
387  // Pretty-printing.
388  void print(raw_ostream &Out, const char *nl = "\n",
389             const char *sep = "") const;
390  void printDOT(raw_ostream &Out) const;
391  void printTaint(raw_ostream &Out, const char *nl = "\n",
392                  const char *sep = "") const;
393
394  void dump() const;
395  void dumpTaint() const;
396
397private:
398  friend void ProgramStateRetain(const ProgramState *state);
399  friend void ProgramStateRelease(const ProgramState *state);
400
401  ProgramStateRef
402  invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
403                        const Expr *E, unsigned BlockCount,
404                        const LocationContext *LCtx,
405                        StoreManager::InvalidatedSymbols &IS,
406                        const CallEvent *Call) const;
407};
408
409//===----------------------------------------------------------------------===//
410// ProgramStateManager - Factory object for ProgramStates.
411//===----------------------------------------------------------------------===//
412
413class ProgramStateManager {
414  friend class ProgramState;
415  friend void ProgramStateRelease(const ProgramState *state);
416private:
417  /// Eng - The SubEngine that owns this state manager.
418  SubEngine *Eng; /* Can be null. */
419
420  EnvironmentManager                   EnvMgr;
421  OwningPtr<StoreManager>              StoreMgr;
422  OwningPtr<ConstraintManager>         ConstraintMgr;
423
424  ProgramState::GenericDataMap::Factory     GDMFactory;
425
426  typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
427  GDMContextsTy GDMContexts;
428
429  /// StateSet - FoldingSet containing all the states created for analyzing
430  ///  a particular function.  This is used to unique states.
431  llvm::FoldingSet<ProgramState> StateSet;
432
433  /// Object that manages the data for all created SVals.
434  OwningPtr<SValBuilder> svalBuilder;
435
436  /// Manages memory for created CallEvents.
437  OwningPtr<CallEventManager> CallEventMgr;
438
439  /// A BumpPtrAllocator to allocate states.
440  llvm::BumpPtrAllocator &Alloc;
441
442  /// A vector of ProgramStates that we can reuse.
443  std::vector<ProgramState *> freeStates;
444
445public:
446  ProgramStateManager(ASTContext &Ctx,
447                 StoreManagerCreator CreateStoreManager,
448                 ConstraintManagerCreator CreateConstraintManager,
449                 llvm::BumpPtrAllocator& alloc,
450                 SubEngine *subeng);
451
452  ~ProgramStateManager();
453
454  ProgramStateRef getInitialState(const LocationContext *InitLoc);
455
456  ASTContext &getContext() { return svalBuilder->getContext(); }
457  const ASTContext &getContext() const { return svalBuilder->getContext(); }
458
459  BasicValueFactory &getBasicVals() {
460    return svalBuilder->getBasicValueFactory();
461  }
462
463  SValBuilder &getSValBuilder() {
464    return *svalBuilder;
465  }
466
467  SymbolManager &getSymbolManager() {
468    return svalBuilder->getSymbolManager();
469  }
470  const SymbolManager &getSymbolManager() const {
471    return svalBuilder->getSymbolManager();
472  }
473
474  llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
475
476  MemRegionManager& getRegionManager() {
477    return svalBuilder->getRegionManager();
478  }
479  const MemRegionManager& getRegionManager() const {
480    return svalBuilder->getRegionManager();
481  }
482
483  CallEventManager &getCallEventManager() { return *CallEventMgr; }
484
485  StoreManager& getStoreManager() { return *StoreMgr; }
486  ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
487  SubEngine* getOwningEngine() { return Eng; }
488
489  ProgramStateRef removeDeadBindings(ProgramStateRef St,
490                                    const StackFrameContext *LCtx,
491                                    SymbolReaper& SymReaper);
492
493public:
494
495  SVal ArrayToPointer(Loc Array) {
496    return StoreMgr->ArrayToPointer(Array);
497  }
498
499  // Methods that manipulate the GDM.
500  ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
501  ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
502
503  // Methods that query & manipulate the Store.
504
505  void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
506    StoreMgr->iterBindings(state->getStore(), F);
507  }
508
509  ProgramStateRef getPersistentState(ProgramState &Impl);
510  ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
511                                           ProgramStateRef GDMState);
512
513  bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
514    return S1->Env == S2->Env;
515  }
516
517  bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
518    return S1->store == S2->store;
519  }
520
521  //==---------------------------------------------------------------------==//
522  // Generic Data Map methods.
523  //==---------------------------------------------------------------------==//
524  //
525  // ProgramStateManager and ProgramState support a "generic data map" that allows
526  // different clients of ProgramState objects to embed arbitrary data within a
527  // ProgramState object.  The generic data map is essentially an immutable map
528  // from a "tag" (that acts as the "key" for a client) and opaque values.
529  // Tags/keys and values are simply void* values.  The typical way that clients
530  // generate unique tags are by taking the address of a static variable.
531  // Clients are responsible for ensuring that data values referred to by a
532  // the data pointer are immutable (and thus are essentially purely functional
533  // data).
534  //
535  // The templated methods below use the ProgramStateTrait<T> class
536  // to resolve keys into the GDM and to return data values to clients.
537  //
538
539  // Trait based GDM dispatch.
540  template <typename T>
541  ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
542    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
543                  ProgramStateTrait<T>::MakeVoidPtr(D));
544  }
545
546  template<typename T>
547  ProgramStateRef set(ProgramStateRef st,
548                     typename ProgramStateTrait<T>::key_type K,
549                     typename ProgramStateTrait<T>::value_type V,
550                     typename ProgramStateTrait<T>::context_type C) {
551
552    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
553     ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
554  }
555
556  template <typename T>
557  ProgramStateRef add(ProgramStateRef st,
558                     typename ProgramStateTrait<T>::key_type K,
559                     typename ProgramStateTrait<T>::context_type C) {
560    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
561        ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
562  }
563
564  template <typename T>
565  ProgramStateRef remove(ProgramStateRef st,
566                        typename ProgramStateTrait<T>::key_type K,
567                        typename ProgramStateTrait<T>::context_type C) {
568
569    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
570     ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
571  }
572
573  template <typename T>
574  ProgramStateRef remove(ProgramStateRef st) {
575    return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
576  }
577
578  void *FindGDMContext(void *index,
579                       void *(*CreateContext)(llvm::BumpPtrAllocator&),
580                       void  (*DeleteContext)(void*));
581
582  template <typename T>
583  typename ProgramStateTrait<T>::context_type get_context() {
584    void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
585                             ProgramStateTrait<T>::CreateContext,
586                             ProgramStateTrait<T>::DeleteContext);
587
588    return ProgramStateTrait<T>::MakeContext(p);
589  }
590
591  void EndPath(ProgramStateRef St) {
592    ConstraintMgr->EndPath(St);
593  }
594};
595
596
597//===----------------------------------------------------------------------===//
598// Out-of-line method definitions for ProgramState.
599//===----------------------------------------------------------------------===//
600
601inline ConstraintManager &ProgramState::getConstraintManager() const {
602  return stateMgr->getConstraintManager();
603}
604
605inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
606                                                const LocationContext *LC) const
607{
608  return getStateManager().getRegionManager().getVarRegion(D, LC);
609}
610
611inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
612                                      bool Assumption) const {
613  if (Cond.isUnknown())
614    return this;
615
616  return getStateManager().ConstraintMgr->assume(this, cast<DefinedSVal>(Cond),
617                                                 Assumption);
618}
619
620inline std::pair<ProgramStateRef , ProgramStateRef >
621ProgramState::assume(DefinedOrUnknownSVal Cond) const {
622  if (Cond.isUnknown())
623    return std::make_pair(this, this);
624
625  return getStateManager().ConstraintMgr->assumeDual(this,
626                                                     cast<DefinedSVal>(Cond));
627}
628
629inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
630  return !isa<Loc>(LV) ? this : bindLoc(cast<Loc>(LV), V);
631}
632
633inline Loc ProgramState::getLValue(const VarDecl *VD,
634                               const LocationContext *LC) const {
635  return getStateManager().StoreMgr->getLValueVar(VD, LC);
636}
637
638inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
639                               const LocationContext *LC) const {
640  return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
641}
642
643inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
644  return getStateManager().StoreMgr->getLValueIvar(D, Base);
645}
646
647inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
648  return getStateManager().StoreMgr->getLValueField(D, Base);
649}
650
651inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
652                                    SVal Base) const {
653  StoreManager &SM = *getStateManager().StoreMgr;
654  for (IndirectFieldDecl::chain_iterator I = D->chain_begin(),
655                                         E = D->chain_end();
656       I != E; ++I) {
657    Base = SM.getLValueField(cast<FieldDecl>(*I), Base);
658  }
659
660  return Base;
661}
662
663inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
664  if (NonLoc *N = dyn_cast<NonLoc>(&Idx))
665    return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
666  return UnknownVal();
667}
668
669inline SVal ProgramState::getSVal(const Stmt *Ex, const LocationContext *LCtx,
670                                  bool useOnlyDirectBindings) const{
671  return Env.getSVal(EnvironmentEntry(Ex, LCtx),
672                     *getStateManager().svalBuilder,
673                     useOnlyDirectBindings);
674}
675
676inline SVal
677ProgramState::getSValAsScalarOrLoc(const Stmt *S,
678                                   const LocationContext *LCtx) const {
679  if (const Expr *Ex = dyn_cast<Expr>(S)) {
680    QualType T = Ex->getType();
681    if (Ex->isGLValue() || Loc::isLocType(T) || T->isIntegerType())
682      return getSVal(S, LCtx);
683  }
684
685  return UnknownVal();
686}
687
688inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
689  return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
690}
691
692inline SVal ProgramState::getSVal(const MemRegion* R) const {
693  return getStateManager().StoreMgr->getBinding(getStore(),
694                                                loc::MemRegionVal(R));
695}
696
697inline BasicValueFactory &ProgramState::getBasicVals() const {
698  return getStateManager().getBasicVals();
699}
700
701inline SymbolManager &ProgramState::getSymbolManager() const {
702  return getStateManager().getSymbolManager();
703}
704
705template<typename T>
706ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
707  return getStateManager().add<T>(this, K, get_context<T>());
708}
709
710template <typename T>
711typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
712  return getStateManager().get_context<T>();
713}
714
715template<typename T>
716ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
717  return getStateManager().remove<T>(this, K, get_context<T>());
718}
719
720template<typename T>
721ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
722                               typename ProgramStateTrait<T>::context_type C) const {
723  return getStateManager().remove<T>(this, K, C);
724}
725
726template <typename T>
727ProgramStateRef ProgramState::remove() const {
728  return getStateManager().remove<T>(this);
729}
730
731template<typename T>
732ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
733  return getStateManager().set<T>(this, D);
734}
735
736template<typename T>
737ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
738                            typename ProgramStateTrait<T>::value_type E) const {
739  return getStateManager().set<T>(this, K, E, get_context<T>());
740}
741
742template<typename T>
743ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
744                            typename ProgramStateTrait<T>::value_type E,
745                            typename ProgramStateTrait<T>::context_type C) const {
746  return getStateManager().set<T>(this, K, E, C);
747}
748
749template <typename CB>
750CB ProgramState::scanReachableSymbols(SVal val) const {
751  CB cb(this);
752  scanReachableSymbols(val, cb);
753  return cb;
754}
755
756template <typename CB>
757CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
758  CB cb(this);
759  scanReachableSymbols(beg, end, cb);
760  return cb;
761}
762
763template <typename CB>
764CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
765                                 const MemRegion * const *end) const {
766  CB cb(this);
767  scanReachableSymbols(beg, end, cb);
768  return cb;
769}
770
771/// \class ScanReachableSymbols
772/// A Utility class that allows to visit the reachable symbols using a custom
773/// SymbolVisitor.
774class ScanReachableSymbols {
775  typedef llvm::DenseMap<const void*, unsigned> VisitedItems;
776
777  VisitedItems visited;
778  ProgramStateRef state;
779  SymbolVisitor &visitor;
780public:
781
782  ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
783    : state(st), visitor(v) {}
784
785  bool scan(nonloc::CompoundVal val);
786  bool scan(SVal val);
787  bool scan(const MemRegion *R);
788  bool scan(const SymExpr *sym);
789};
790
791} // end ento namespace
792
793} // end clang namespace
794
795#endif
796