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