ProgramState.h revision 47cbd0f3892c7965cf16a58393f9f17a22d4d4d9
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) const; // Do not implement.
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  const BasicValueFactory& getBasicVals() const {
463    return svalBuilder->getBasicValueFactory();
464  }
465
466  SValBuilder &getSValBuilder() {
467    return *svalBuilder;
468  }
469
470  SymbolManager &getSymbolManager() {
471    return svalBuilder->getSymbolManager();
472  }
473  const SymbolManager &getSymbolManager() const {
474    return svalBuilder->getSymbolManager();
475  }
476
477  llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
478
479  MemRegionManager& getRegionManager() {
480    return svalBuilder->getRegionManager();
481  }
482  const MemRegionManager& getRegionManager() const {
483    return svalBuilder->getRegionManager();
484  }
485
486  CallEventManager &getCallEventManager() { return *CallEventMgr; }
487
488  StoreManager& getStoreManager() { return *StoreMgr; }
489  ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
490  SubEngine* getOwningEngine() { return Eng; }
491
492  ProgramStateRef removeDeadBindings(ProgramStateRef St,
493                                    const StackFrameContext *LCtx,
494                                    SymbolReaper& SymReaper);
495
496  /// Marshal a new state for the callee in another translation unit.
497  /// 'state' is owned by the caller's engine.
498  ProgramStateRef MarshalState(ProgramStateRef state, const StackFrameContext *L);
499
500public:
501
502  SVal ArrayToPointer(Loc Array) {
503    return StoreMgr->ArrayToPointer(Array);
504  }
505
506  // Methods that manipulate the GDM.
507  ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
508  ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
509
510  // Methods that query & manipulate the Store.
511
512  void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
513    StoreMgr->iterBindings(state->getStore(), F);
514  }
515
516  ProgramStateRef getPersistentState(ProgramState &Impl);
517  ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
518                                           ProgramStateRef GDMState);
519
520  bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
521    return S1->Env == S2->Env;
522  }
523
524  bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
525    return S1->store == S2->store;
526  }
527
528  //==---------------------------------------------------------------------==//
529  // Generic Data Map methods.
530  //==---------------------------------------------------------------------==//
531  //
532  // ProgramStateManager and ProgramState support a "generic data map" that allows
533  // different clients of ProgramState objects to embed arbitrary data within a
534  // ProgramState object.  The generic data map is essentially an immutable map
535  // from a "tag" (that acts as the "key" for a client) and opaque values.
536  // Tags/keys and values are simply void* values.  The typical way that clients
537  // generate unique tags are by taking the address of a static variable.
538  // Clients are responsible for ensuring that data values referred to by a
539  // the data pointer are immutable (and thus are essentially purely functional
540  // data).
541  //
542  // The templated methods below use the ProgramStateTrait<T> class
543  // to resolve keys into the GDM and to return data values to clients.
544  //
545
546  // Trait based GDM dispatch.
547  template <typename T>
548  ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
549    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
550                  ProgramStateTrait<T>::MakeVoidPtr(D));
551  }
552
553  template<typename T>
554  ProgramStateRef set(ProgramStateRef st,
555                     typename ProgramStateTrait<T>::key_type K,
556                     typename ProgramStateTrait<T>::value_type V,
557                     typename ProgramStateTrait<T>::context_type C) {
558
559    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
560     ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
561  }
562
563  template <typename T>
564  ProgramStateRef add(ProgramStateRef st,
565                     typename ProgramStateTrait<T>::key_type K,
566                     typename ProgramStateTrait<T>::context_type C) {
567    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
568        ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
569  }
570
571  template <typename T>
572  ProgramStateRef remove(ProgramStateRef st,
573                        typename ProgramStateTrait<T>::key_type K,
574                        typename ProgramStateTrait<T>::context_type C) {
575
576    return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
577     ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
578  }
579
580  template <typename T>
581  ProgramStateRef remove(ProgramStateRef st) {
582    return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
583  }
584
585  void *FindGDMContext(void *index,
586                       void *(*CreateContext)(llvm::BumpPtrAllocator&),
587                       void  (*DeleteContext)(void*));
588
589  template <typename T>
590  typename ProgramStateTrait<T>::context_type get_context() {
591    void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
592                             ProgramStateTrait<T>::CreateContext,
593                             ProgramStateTrait<T>::DeleteContext);
594
595    return ProgramStateTrait<T>::MakeContext(p);
596  }
597
598  void EndPath(ProgramStateRef St) {
599    ConstraintMgr->EndPath(St);
600  }
601};
602
603
604//===----------------------------------------------------------------------===//
605// Out-of-line method definitions for ProgramState.
606//===----------------------------------------------------------------------===//
607
608inline ConstraintManager &ProgramState::getConstraintManager() const {
609  return stateMgr->getConstraintManager();
610}
611
612inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
613                                                const LocationContext *LC) const
614{
615  return getStateManager().getRegionManager().getVarRegion(D, LC);
616}
617
618inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
619                                      bool Assumption) const {
620  if (Cond.isUnknown())
621    return this;
622
623  return getStateManager().ConstraintMgr->assume(this, cast<DefinedSVal>(Cond),
624                                                 Assumption);
625}
626
627inline std::pair<ProgramStateRef , ProgramStateRef >
628ProgramState::assume(DefinedOrUnknownSVal Cond) const {
629  if (Cond.isUnknown())
630    return std::make_pair(this, this);
631
632  return getStateManager().ConstraintMgr->assumeDual(this,
633                                                     cast<DefinedSVal>(Cond));
634}
635
636inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
637  return !isa<Loc>(LV) ? this : bindLoc(cast<Loc>(LV), V);
638}
639
640inline Loc ProgramState::getLValue(const VarDecl *VD,
641                               const LocationContext *LC) const {
642  return getStateManager().StoreMgr->getLValueVar(VD, LC);
643}
644
645inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
646                               const LocationContext *LC) const {
647  return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
648}
649
650inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
651  return getStateManager().StoreMgr->getLValueIvar(D, Base);
652}
653
654inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
655  return getStateManager().StoreMgr->getLValueField(D, Base);
656}
657
658inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
659                                    SVal Base) const {
660  StoreManager &SM = *getStateManager().StoreMgr;
661  for (IndirectFieldDecl::chain_iterator I = D->chain_begin(),
662                                         E = D->chain_end();
663       I != E; ++I) {
664    Base = SM.getLValueField(cast<FieldDecl>(*I), Base);
665  }
666
667  return Base;
668}
669
670inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
671  if (NonLoc *N = dyn_cast<NonLoc>(&Idx))
672    return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
673  return UnknownVal();
674}
675
676inline SVal ProgramState::getSVal(const Stmt *Ex, const LocationContext *LCtx,
677                                  bool useOnlyDirectBindings) const{
678  return Env.getSVal(EnvironmentEntry(Ex, LCtx),
679                     *getStateManager().svalBuilder,
680                     useOnlyDirectBindings);
681}
682
683inline SVal
684ProgramState::getSValAsScalarOrLoc(const Stmt *S,
685                                   const LocationContext *LCtx) const {
686  if (const Expr *Ex = dyn_cast<Expr>(S)) {
687    QualType T = Ex->getType();
688    if (Ex->isGLValue() || Loc::isLocType(T) || T->isIntegerType())
689      return getSVal(S, LCtx);
690  }
691
692  return UnknownVal();
693}
694
695inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
696  return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
697}
698
699inline SVal ProgramState::getSVal(const MemRegion* R) const {
700  return getStateManager().StoreMgr->getBinding(getStore(),
701                                                loc::MemRegionVal(R));
702}
703
704inline BasicValueFactory &ProgramState::getBasicVals() const {
705  return getStateManager().getBasicVals();
706}
707
708inline SymbolManager &ProgramState::getSymbolManager() const {
709  return getStateManager().getSymbolManager();
710}
711
712template<typename T>
713ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
714  return getStateManager().add<T>(this, K, get_context<T>());
715}
716
717template <typename T>
718typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
719  return getStateManager().get_context<T>();
720}
721
722template<typename T>
723ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
724  return getStateManager().remove<T>(this, K, get_context<T>());
725}
726
727template<typename T>
728ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
729                               typename ProgramStateTrait<T>::context_type C) const {
730  return getStateManager().remove<T>(this, K, C);
731}
732
733template <typename T>
734ProgramStateRef ProgramState::remove() const {
735  return getStateManager().remove<T>(this);
736}
737
738template<typename T>
739ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
740  return getStateManager().set<T>(this, D);
741}
742
743template<typename T>
744ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
745                            typename ProgramStateTrait<T>::value_type E) const {
746  return getStateManager().set<T>(this, K, E, get_context<T>());
747}
748
749template<typename T>
750ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
751                            typename ProgramStateTrait<T>::value_type E,
752                            typename ProgramStateTrait<T>::context_type C) const {
753  return getStateManager().set<T>(this, K, E, C);
754}
755
756template <typename CB>
757CB ProgramState::scanReachableSymbols(SVal val) const {
758  CB cb(this);
759  scanReachableSymbols(val, cb);
760  return cb;
761}
762
763template <typename CB>
764CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
765  CB cb(this);
766  scanReachableSymbols(beg, end, cb);
767  return cb;
768}
769
770template <typename CB>
771CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
772                                 const MemRegion * const *end) const {
773  CB cb(this);
774  scanReachableSymbols(beg, end, cb);
775  return cb;
776}
777
778/// \class ScanReachableSymbols
779/// A Utility class that allows to visit the reachable symbols using a custom
780/// SymbolVisitor.
781class ScanReachableSymbols {
782  typedef llvm::DenseMap<const void*, unsigned> VisitedItems;
783
784  VisitedItems visited;
785  ProgramStateRef state;
786  SymbolVisitor &visitor;
787public:
788
789  ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
790    : state(st), visitor(v) {}
791
792  bool scan(nonloc::CompoundVal val);
793  bool scan(SVal val);
794  bool scan(const MemRegion *R);
795  bool scan(const SymExpr *sym);
796};
797
798} // end ento namespace
799
800} // end clang namespace
801
802#endif
803