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