ProgramState.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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 SymbolRef, ExprBindKey, and ProgramState*.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_GR_VALUESTATE_H
  14. #define LLVM_CLANG_GR_VALUESTATE_H
  15. #include "clang/Basic/LLVM.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
  22. #include "llvm/ADT/PointerIntPair.h"
  23. #include "llvm/ADT/FoldingSet.h"
  24. #include "llvm/ADT/ImmutableMap.h"
  25. namespace llvm {
  26. class APSInt;
  27. class BumpPtrAllocator;
  28. }
  29. namespace clang {
  30. class ASTContext;
  31. namespace ento {
  32. class CallOrObjCMessage;
  33. typedef ConstraintManager* (*ConstraintManagerCreator)(ProgramStateManager&,
  34. SubEngine&);
  35. typedef StoreManager* (*StoreManagerCreator)(ProgramStateManager&);
  36. //===----------------------------------------------------------------------===//
  37. // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
  38. //===----------------------------------------------------------------------===//
  39. template <typename T> struct ProgramStatePartialTrait;
  40. template <typename T> struct ProgramStateTrait {
  41. typedef typename T::data_type data_type;
  42. static inline void *GDMIndex() { return &T::TagInt; }
  43. static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
  44. static inline data_type MakeData(void *const* P) {
  45. return P ? (data_type) *P : (data_type) 0;
  46. }
  47. };
  48. /// \class ProgramState
  49. /// ProgramState - This class encapsulates:
  50. ///
  51. /// 1. A mapping from expressions to values (Environment)
  52. /// 2. A mapping from locations to values (Store)
  53. /// 3. Constraints on symbolic values (GenericDataMap)
  54. ///
  55. /// Together these represent the "abstract state" of a program.
  56. ///
  57. /// ProgramState is intended to be used as a functional object; that is,
  58. /// once it is created and made "persistent" in a FoldingSet, its
  59. /// values will never change.
  60. class ProgramState : public llvm::FoldingSetNode {
  61. public:
  62. typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
  63. typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
  64. private:
  65. void operator=(const ProgramState& R) const; // Do not implement.
  66. friend class ProgramStateManager;
  67. friend class ExplodedGraph;
  68. friend class ExplodedNode;
  69. ProgramStateManager *stateMgr;
  70. Environment Env; // Maps a Stmt to its current SVal.
  71. Store store; // Maps a location to its current value.
  72. GenericDataMap GDM; // Custom data stored by a client of this class.
  73. unsigned refCount;
  74. /// makeWithStore - Return a ProgramState with the same values as the current
  75. /// state with the exception of using the specified Store.
  76. ProgramStateRef makeWithStore(const StoreRef &store) const;
  77. void setStore(const StoreRef &storeRef);
  78. public:
  79. /// This ctor is used when creating the first ProgramState object.
  80. ProgramState(ProgramStateManager *mgr, const Environment& env,
  81. StoreRef st, GenericDataMap gdm);
  82. /// Copy ctor - We must explicitly define this or else the "Next" ptr
  83. /// in FoldingSetNode will also get copied.
  84. ProgramState(const ProgramState &RHS);
  85. ~ProgramState();
  86. /// Return the ProgramStateManager associated with this state.
  87. ProgramStateManager &getStateManager() const { return *stateMgr; }
  88. /// getEnvironment - Return the environment associated with this state.
  89. /// The environment is the mapping from expressions to values.
  90. const Environment& getEnvironment() const { return Env; }
  91. /// Return the store associated with this state. The store
  92. /// is a mapping from locations to values.
  93. Store getStore() const { return store; }
  94. /// getGDM - Return the generic data map associated with this state.
  95. GenericDataMap getGDM() const { return GDM; }
  96. void setGDM(GenericDataMap gdm) { GDM = gdm; }
  97. /// Profile - Profile the contents of a ProgramState object for use in a
  98. /// FoldingSet. Two ProgramState objects are considered equal if they
  99. /// have the same Environment, Store, and GenericDataMap.
  100. static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
  101. V->Env.Profile(ID);
  102. ID.AddPointer(V->store);
  103. V->GDM.Profile(ID);
  104. }
  105. /// Profile - Used to profile the contents of this object for inclusion
  106. /// in a FoldingSet.
  107. void Profile(llvm::FoldingSetNodeID& ID) const {
  108. Profile(ID, this);
  109. }
  110. BasicValueFactory &getBasicVals() const;
  111. SymbolManager &getSymbolManager() const;
  112. //==---------------------------------------------------------------------==//
  113. // Constraints on values.
  114. //==---------------------------------------------------------------------==//
  115. //
  116. // Each ProgramState records constraints on symbolic values. These constraints
  117. // are managed using the ConstraintManager associated with a ProgramStateManager.
  118. // As constraints gradually accrue on symbolic values, added constraints
  119. // may conflict and indicate that a state is infeasible (as no real values
  120. // could satisfy all the constraints). This is the principal mechanism
  121. // for modeling path-sensitivity in ExprEngine/ProgramState.
  122. //
  123. // Various "assume" methods form the interface for adding constraints to
  124. // symbolic values. A call to 'assume' indicates an assumption being placed
  125. // on one or symbolic values. 'assume' methods take the following inputs:
  126. //
  127. // (1) A ProgramState object representing the current state.
  128. //
  129. // (2) The assumed constraint (which is specific to a given "assume" method).
  130. //
  131. // (3) A binary value "Assumption" that indicates whether the constraint is
  132. // assumed to be true or false.
  133. //
  134. // The output of "assume*" is a new ProgramState object with the added constraints.
  135. // If no new state is feasible, NULL is returned.
  136. //
  137. ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
  138. /// This method assumes both "true" and "false" for 'cond', and
  139. /// returns both corresponding states. It's shorthand for doing
  140. /// 'assume' twice.
  141. std::pair<ProgramStateRef , ProgramStateRef >
  142. assume(DefinedOrUnknownSVal cond) const;
  143. ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
  144. DefinedOrUnknownSVal upperBound,
  145. bool assumption,
  146. QualType IndexType = QualType()) const;
  147. /// Utility method for getting regions.
  148. const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
  149. //==---------------------------------------------------------------------==//
  150. // Binding and retrieving values to/from the environment and symbolic store.
  151. //==---------------------------------------------------------------------==//
  152. /// BindCompoundLiteral - Return the state that has the bindings currently
  153. /// in this state plus the bindings for the CompoundLiteral.
  154. ProgramStateRef bindCompoundLiteral(const CompoundLiteralExpr *CL,
  155. const LocationContext *LC,
  156. SVal V) const;
  157. /// Create a new state by binding the value 'V' to the statement 'S' in the
  158. /// state's environment.
  159. ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
  160. SVal V, bool Invalidate = true) const;
  161. /// Create a new state by binding the value 'V' and location 'locaton' to the
  162. /// statement 'S' in the state's environment.
  163. ProgramStateRef bindExprAndLocation(const Stmt *S,
  164. const LocationContext *LCtx,
  165. SVal location, SVal V) const;
  166. ProgramStateRef bindDecl(const VarRegion *VR, SVal V) const;
  167. ProgramStateRef bindDeclWithNoInit(const VarRegion *VR) const;
  168. ProgramStateRef bindLoc(Loc location, SVal V) const;
  169. ProgramStateRef bindLoc(SVal location, SVal V) const;
  170. ProgramStateRef bindDefault(SVal loc, SVal V) const;
  171. ProgramStateRef unbindLoc(Loc LV) const;
  172. /// invalidateRegions - Returns the state with bindings for the given regions
  173. /// cleared from the store. The regions are provided as a continuous array
  174. /// from Begin to End. Optionally invalidates global regions as well.
  175. ProgramStateRef invalidateRegions(ArrayRef<const MemRegion *> Regions,
  176. const Expr *E, unsigned BlockCount,
  177. StoreManager::InvalidatedSymbols *IS = 0,
  178. const CallOrObjCMessage *Call = 0) const;
  179. /// enterStackFrame - Returns the state for entry to the given stack frame,
  180. /// preserving the current state.
  181. ProgramStateRef enterStackFrame(const LocationContext *callerCtx,
  182. const StackFrameContext *calleeCtx) const;
  183. /// Get the lvalue for a variable reference.
  184. Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
  185. /// Get the lvalue for a StringLiteral.
  186. Loc getLValue(const StringLiteral *literal) const;
  187. Loc getLValue(const CompoundLiteralExpr *literal,
  188. const LocationContext *LC) const;
  189. /// Get the lvalue for an ivar reference.
  190. SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
  191. /// Get the lvalue for a field reference.
  192. SVal getLValue(const FieldDecl *decl, SVal Base) const;
  193. /// Get the lvalue for an array index.
  194. SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
  195. const llvm::APSInt *getSymVal(SymbolRef sym) const;
  196. /// Returns the SVal bound to the statement 'S' in the state's environment.
  197. SVal getSVal(const Stmt *S, const LocationContext *LCtx,
  198. bool useOnlyDirectBindings = false) const;
  199. SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
  200. SVal getSVal(Loc LV, QualType T = QualType()) const;
  201. /// Returns the "raw" SVal bound to LV before any value simplfication.
  202. SVal getRawSVal(Loc LV, QualType T= QualType()) const;
  203. SVal getSVal(const MemRegion* R) const;
  204. SVal getSValAsScalarOrLoc(const MemRegion *R) const;
  205. /// \brief Visits the symbols reachable from the given SVal using the provided
  206. /// SymbolVisitor.
  207. ///
  208. /// This is a convenience API. Consider using ScanReachableSymbols class
  209. /// directly when making multiple scans on the same state with the same
  210. /// visitor to avoid repeated initialization cost.
  211. /// \sa ScanReachableSymbols
  212. bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
  213. /// \brief Visits the symbols reachable from the SVals in the given range
  214. /// using the provided SymbolVisitor.
  215. bool scanReachableSymbols(const SVal *I, const SVal *E,
  216. SymbolVisitor &visitor) const;
  217. /// \brief Visits the symbols reachable from the regions in the given
  218. /// MemRegions range using the provided SymbolVisitor.
  219. bool scanReachableSymbols(const MemRegion * const *I,
  220. const MemRegion * const *E,
  221. SymbolVisitor &visitor) const;
  222. template <typename CB> CB scanReachableSymbols(SVal val) const;
  223. template <typename CB> CB scanReachableSymbols(const SVal *beg,
  224. const SVal *end) const;
  225. template <typename CB> CB
  226. scanReachableSymbols(const MemRegion * const *beg,
  227. const MemRegion * const *end) const;
  228. /// Create a new state in which the statement is marked as tainted.
  229. ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
  230. TaintTagType Kind = TaintTagGeneric) const;
  231. /// Create a new state in which the symbol is marked as tainted.
  232. ProgramStateRef addTaint(SymbolRef S,
  233. TaintTagType Kind = TaintTagGeneric) const;
  234. /// Create a new state in which the region symbol is marked as tainted.
  235. ProgramStateRef addTaint(const MemRegion *R,
  236. TaintTagType Kind = TaintTagGeneric) const;
  237. /// Check if the statement is tainted in the current state.
  238. bool isTainted(const Stmt *S, const LocationContext *LCtx,
  239. TaintTagType Kind = TaintTagGeneric) const;
  240. bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
  241. bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
  242. bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
  243. //==---------------------------------------------------------------------==//
  244. // Accessing the Generic Data Map (GDM).
  245. //==---------------------------------------------------------------------==//
  246. void *const* FindGDM(void *K) const;
  247. template<typename T>
  248. ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
  249. template <typename T>
  250. typename ProgramStateTrait<T>::data_type
  251. get() const {
  252. return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
  253. }
  254. template<typename T>
  255. typename ProgramStateTrait<T>::lookup_type
  256. get(typename ProgramStateTrait<T>::key_type key) const {
  257. void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
  258. return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
  259. }
  260. template <typename T>
  261. typename ProgramStateTrait<T>::context_type get_context() const;
  262. template<typename T>
  263. ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
  264. template<typename T>
  265. ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
  266. typename ProgramStateTrait<T>::context_type C) const;
  267. template <typename T>
  268. ProgramStateRef remove() const;
  269. template<typename T>
  270. ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
  271. template<typename T>
  272. ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
  273. typename ProgramStateTrait<T>::value_type E) const;
  274. template<typename T>
  275. ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
  276. typename ProgramStateTrait<T>::value_type E,
  277. typename ProgramStateTrait<T>::context_type C) const;
  278. template<typename T>
  279. bool contains(typename ProgramStateTrait<T>::key_type key) const {
  280. void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
  281. return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
  282. }
  283. // Pretty-printing.
  284. void print(raw_ostream &Out, const char *nl = "\n",
  285. const char *sep = "") const;
  286. void printDOT(raw_ostream &Out) const;
  287. void printTaint(raw_ostream &Out, const char *nl = "\n",
  288. const char *sep = "") const;
  289. void dump() const;
  290. void dumpTaint() const;
  291. private:
  292. friend void ProgramStateRetain(const ProgramState *state);
  293. friend void ProgramStateRelease(const ProgramState *state);
  294. ProgramStateRef
  295. invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
  296. const Expr *E, unsigned BlockCount,
  297. StoreManager::InvalidatedSymbols &IS,
  298. const CallOrObjCMessage *Call) const;
  299. };
  300. //===----------------------------------------------------------------------===//
  301. // ProgramStateManager - Factory object for ProgramStates.
  302. //===----------------------------------------------------------------------===//
  303. class ProgramStateManager {
  304. friend class ProgramState;
  305. friend void ProgramStateRelease(const ProgramState *state);
  306. private:
  307. /// Eng - The SubEngine that owns this state manager.
  308. SubEngine *Eng; /* Can be null. */
  309. EnvironmentManager EnvMgr;
  310. llvm::OwningPtr<StoreManager> StoreMgr;
  311. llvm::OwningPtr<ConstraintManager> ConstraintMgr;
  312. ProgramState::GenericDataMap::Factory GDMFactory;
  313. typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
  314. GDMContextsTy GDMContexts;
  315. /// StateSet - FoldingSet containing all the states created for analyzing
  316. /// a particular function. This is used to unique states.
  317. llvm::FoldingSet<ProgramState> StateSet;
  318. /// Object that manages the data for all created SVals.
  319. llvm::OwningPtr<SValBuilder> svalBuilder;
  320. /// A BumpPtrAllocator to allocate states.
  321. llvm::BumpPtrAllocator &Alloc;
  322. /// A vector of ProgramStates that we can reuse.
  323. std::vector<ProgramState *> freeStates;
  324. public:
  325. ProgramStateManager(ASTContext &Ctx,
  326. StoreManagerCreator CreateStoreManager,
  327. ConstraintManagerCreator CreateConstraintManager,
  328. llvm::BumpPtrAllocator& alloc,
  329. SubEngine &subeng)
  330. : Eng(&subeng),
  331. EnvMgr(alloc),
  332. GDMFactory(alloc),
  333. svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
  334. Alloc(alloc) {
  335. StoreMgr.reset((*CreateStoreManager)(*this));
  336. ConstraintMgr.reset((*CreateConstraintManager)(*this, subeng));
  337. }
  338. ProgramStateManager(ASTContext &Ctx,
  339. StoreManagerCreator CreateStoreManager,
  340. ConstraintManager* ConstraintManagerPtr,
  341. llvm::BumpPtrAllocator& alloc)
  342. : Eng(0),
  343. EnvMgr(alloc),
  344. GDMFactory(alloc),
  345. svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
  346. Alloc(alloc) {
  347. StoreMgr.reset((*CreateStoreManager)(*this));
  348. ConstraintMgr.reset(ConstraintManagerPtr);
  349. }
  350. ~ProgramStateManager();
  351. ProgramStateRef getInitialState(const LocationContext *InitLoc);
  352. ASTContext &getContext() { return svalBuilder->getContext(); }
  353. const ASTContext &getContext() const { return svalBuilder->getContext(); }
  354. BasicValueFactory &getBasicVals() {
  355. return svalBuilder->getBasicValueFactory();
  356. }
  357. const BasicValueFactory& getBasicVals() const {
  358. return svalBuilder->getBasicValueFactory();
  359. }
  360. SValBuilder &getSValBuilder() {
  361. return *svalBuilder;
  362. }
  363. SymbolManager &getSymbolManager() {
  364. return svalBuilder->getSymbolManager();
  365. }
  366. const SymbolManager &getSymbolManager() const {
  367. return svalBuilder->getSymbolManager();
  368. }
  369. llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
  370. MemRegionManager& getRegionManager() {
  371. return svalBuilder->getRegionManager();
  372. }
  373. const MemRegionManager& getRegionManager() const {
  374. return svalBuilder->getRegionManager();
  375. }
  376. StoreManager& getStoreManager() { return *StoreMgr; }
  377. ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
  378. SubEngine* getOwningEngine() { return Eng; }
  379. ProgramStateRef removeDeadBindings(ProgramStateRef St,
  380. const StackFrameContext *LCtx,
  381. SymbolReaper& SymReaper);
  382. /// Marshal a new state for the callee in another translation unit.
  383. /// 'state' is owned by the caller's engine.
  384. ProgramStateRef MarshalState(ProgramStateRef state, const StackFrameContext *L);
  385. public:
  386. SVal ArrayToPointer(Loc Array) {
  387. return StoreMgr->ArrayToPointer(Array);
  388. }
  389. // Methods that manipulate the GDM.
  390. ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
  391. ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
  392. // Methods that query & manipulate the Store.
  393. void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
  394. StoreMgr->iterBindings(state->getStore(), F);
  395. }
  396. ProgramStateRef getPersistentState(ProgramState &Impl);
  397. ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
  398. ProgramStateRef GDMState);
  399. bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
  400. return S1->Env == S2->Env;
  401. }
  402. bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
  403. return S1->store == S2->store;
  404. }
  405. //==---------------------------------------------------------------------==//
  406. // Generic Data Map methods.
  407. //==---------------------------------------------------------------------==//
  408. //
  409. // ProgramStateManager and ProgramState support a "generic data map" that allows
  410. // different clients of ProgramState objects to embed arbitrary data within a
  411. // ProgramState object. The generic data map is essentially an immutable map
  412. // from a "tag" (that acts as the "key" for a client) and opaque values.
  413. // Tags/keys and values are simply void* values. The typical way that clients
  414. // generate unique tags are by taking the address of a static variable.
  415. // Clients are responsible for ensuring that data values referred to by a
  416. // the data pointer are immutable (and thus are essentially purely functional
  417. // data).
  418. //
  419. // The templated methods below use the ProgramStateTrait<T> class
  420. // to resolve keys into the GDM and to return data values to clients.
  421. //
  422. // Trait based GDM dispatch.
  423. template <typename T>
  424. ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
  425. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  426. ProgramStateTrait<T>::MakeVoidPtr(D));
  427. }
  428. template<typename T>
  429. ProgramStateRef set(ProgramStateRef st,
  430. typename ProgramStateTrait<T>::key_type K,
  431. typename ProgramStateTrait<T>::value_type V,
  432. typename ProgramStateTrait<T>::context_type C) {
  433. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  434. ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
  435. }
  436. template <typename T>
  437. ProgramStateRef add(ProgramStateRef st,
  438. typename ProgramStateTrait<T>::key_type K,
  439. typename ProgramStateTrait<T>::context_type C) {
  440. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  441. ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
  442. }
  443. template <typename T>
  444. ProgramStateRef remove(ProgramStateRef st,
  445. typename ProgramStateTrait<T>::key_type K,
  446. typename ProgramStateTrait<T>::context_type C) {
  447. return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
  448. ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
  449. }
  450. template <typename T>
  451. ProgramStateRef remove(ProgramStateRef st) {
  452. return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
  453. }
  454. void *FindGDMContext(void *index,
  455. void *(*CreateContext)(llvm::BumpPtrAllocator&),
  456. void (*DeleteContext)(void*));
  457. template <typename T>
  458. typename ProgramStateTrait<T>::context_type get_context() {
  459. void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
  460. ProgramStateTrait<T>::CreateContext,
  461. ProgramStateTrait<T>::DeleteContext);
  462. return ProgramStateTrait<T>::MakeContext(p);
  463. }
  464. const llvm::APSInt* getSymVal(ProgramStateRef St, SymbolRef sym) {
  465. return ConstraintMgr->getSymVal(St, sym);
  466. }
  467. void EndPath(ProgramStateRef St) {
  468. ConstraintMgr->EndPath(St);
  469. }
  470. };
  471. //===----------------------------------------------------------------------===//
  472. // Out-of-line method definitions for ProgramState.
  473. //===----------------------------------------------------------------------===//
  474. inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
  475. const LocationContext *LC) const
  476. {
  477. return getStateManager().getRegionManager().getVarRegion(D, LC);
  478. }
  479. inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
  480. bool Assumption) const {
  481. if (Cond.isUnknown())
  482. return this;
  483. return getStateManager().ConstraintMgr->assume(this, cast<DefinedSVal>(Cond),
  484. Assumption);
  485. }
  486. inline std::pair<ProgramStateRef , ProgramStateRef >
  487. ProgramState::assume(DefinedOrUnknownSVal Cond) const {
  488. if (Cond.isUnknown())
  489. return std::make_pair(this, this);
  490. return getStateManager().ConstraintMgr->assumeDual(this,
  491. cast<DefinedSVal>(Cond));
  492. }
  493. inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
  494. return !isa<Loc>(LV) ? this : bindLoc(cast<Loc>(LV), V);
  495. }
  496. inline Loc ProgramState::getLValue(const VarDecl *VD,
  497. const LocationContext *LC) const {
  498. return getStateManager().StoreMgr->getLValueVar(VD, LC);
  499. }
  500. inline Loc ProgramState::getLValue(const StringLiteral *literal) const {
  501. return getStateManager().StoreMgr->getLValueString(literal);
  502. }
  503. inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
  504. const LocationContext *LC) const {
  505. return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
  506. }
  507. inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
  508. return getStateManager().StoreMgr->getLValueIvar(D, Base);
  509. }
  510. inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
  511. return getStateManager().StoreMgr->getLValueField(D, Base);
  512. }
  513. inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
  514. if (NonLoc *N = dyn_cast<NonLoc>(&Idx))
  515. return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
  516. return UnknownVal();
  517. }
  518. inline const llvm::APSInt *ProgramState::getSymVal(SymbolRef sym) const {
  519. return getStateManager().getSymVal(this, sym);
  520. }
  521. inline SVal ProgramState::getSVal(const Stmt *Ex, const LocationContext *LCtx,
  522. bool useOnlyDirectBindings) const{
  523. return Env.getSVal(EnvironmentEntry(Ex, LCtx),
  524. *getStateManager().svalBuilder,
  525. useOnlyDirectBindings);
  526. }
  527. inline SVal
  528. ProgramState::getSValAsScalarOrLoc(const Stmt *S,
  529. const LocationContext *LCtx) const {
  530. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  531. QualType T = Ex->getType();
  532. if (Ex->isLValue() || Loc::isLocType(T) || T->isIntegerType())
  533. return getSVal(S, LCtx);
  534. }
  535. return UnknownVal();
  536. }
  537. inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
  538. return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
  539. }
  540. inline SVal ProgramState::getSVal(const MemRegion* R) const {
  541. return getStateManager().StoreMgr->getBinding(getStore(),
  542. loc::MemRegionVal(R));
  543. }
  544. inline BasicValueFactory &ProgramState::getBasicVals() const {
  545. return getStateManager().getBasicVals();
  546. }
  547. inline SymbolManager &ProgramState::getSymbolManager() const {
  548. return getStateManager().getSymbolManager();
  549. }
  550. template<typename T>
  551. ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
  552. return getStateManager().add<T>(this, K, get_context<T>());
  553. }
  554. template <typename T>
  555. typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
  556. return getStateManager().get_context<T>();
  557. }
  558. template<typename T>
  559. ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
  560. return getStateManager().remove<T>(this, K, get_context<T>());
  561. }
  562. template<typename T>
  563. ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
  564. typename ProgramStateTrait<T>::context_type C) const {
  565. return getStateManager().remove<T>(this, K, C);
  566. }
  567. template <typename T>
  568. ProgramStateRef ProgramState::remove() const {
  569. return getStateManager().remove<T>(this);
  570. }
  571. template<typename T>
  572. ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
  573. return getStateManager().set<T>(this, D);
  574. }
  575. template<typename T>
  576. ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
  577. typename ProgramStateTrait<T>::value_type E) const {
  578. return getStateManager().set<T>(this, K, E, get_context<T>());
  579. }
  580. template<typename T>
  581. ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
  582. typename ProgramStateTrait<T>::value_type E,
  583. typename ProgramStateTrait<T>::context_type C) const {
  584. return getStateManager().set<T>(this, K, E, C);
  585. }
  586. template <typename CB>
  587. CB ProgramState::scanReachableSymbols(SVal val) const {
  588. CB cb(this);
  589. scanReachableSymbols(val, cb);
  590. return cb;
  591. }
  592. template <typename CB>
  593. CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
  594. CB cb(this);
  595. scanReachableSymbols(beg, end, cb);
  596. return cb;
  597. }
  598. template <typename CB>
  599. CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
  600. const MemRegion * const *end) const {
  601. CB cb(this);
  602. scanReachableSymbols(beg, end, cb);
  603. return cb;
  604. }
  605. /// \class ScanReachableSymbols
  606. /// A Utility class that allows to visit the reachable symbols using a custom
  607. /// SymbolVisitor.
  608. class ScanReachableSymbols : public SubRegionMap::Visitor {
  609. virtual void anchor();
  610. typedef llvm::DenseMap<const void*, unsigned> VisitedItems;
  611. VisitedItems visited;
  612. ProgramStateRef state;
  613. SymbolVisitor &visitor;
  614. llvm::OwningPtr<SubRegionMap> SRM;
  615. public:
  616. ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
  617. : state(st), visitor(v) {}
  618. bool scan(nonloc::CompoundVal val);
  619. bool scan(SVal val);
  620. bool scan(const MemRegion *R);
  621. bool scan(const SymExpr *sym);
  622. // From SubRegionMap::Visitor.
  623. bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) {
  624. return scan(SubRegion);
  625. }
  626. };
  627. } // end GR namespace
  628. } // end clang namespace
  629. #endif