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