clang 20.0.0git
ProgramState.h
Go to the documentation of this file.
1//== ProgramState.h - Path-sensitive "State" for tracking values -*- C++ -*--=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the state of the program along the analysisa path.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
14#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
15
16#include "clang/Basic/LLVM.h"
23#include "llvm/ADT/FoldingSet.h"
24#include "llvm/ADT/ImmutableMap.h"
25#include "llvm/Support/Allocator.h"
26#include <optional>
27#include <utility>
28
29namespace llvm {
30class APSInt;
31}
32
33namespace clang {
34class ASTContext;
35
36namespace ento {
37
38class AnalysisManager;
39class CallEvent;
40class CallEventManager;
41
42typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
44typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
46
47//===----------------------------------------------------------------------===//
48// ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
49//===----------------------------------------------------------------------===//
50
51template <typename T> struct ProgramStateTrait {
52 typedef typename T::data_type data_type;
53 static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
54 static inline data_type MakeData(void *const* P) {
55 return P ? (data_type) *P : (data_type) 0;
56 }
57};
58
59/// \class ProgramState
60/// ProgramState - This class encapsulates:
61///
62/// 1. A mapping from expressions to values (Environment)
63/// 2. A mapping from locations to values (Store)
64/// 3. Constraints on symbolic values (GenericDataMap)
65///
66/// Together these represent the "abstract state" of a program.
67///
68/// ProgramState is intended to be used as a functional object; that is,
69/// once it is created and made "persistent" in a FoldingSet, its
70/// values will never change.
71class ProgramState : public llvm::FoldingSetNode {
72public:
73 typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
74 typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
75
76private:
77 void operator=(const ProgramState& R) = delete;
78
79 friend class ProgramStateManager;
80 friend class ExplodedGraph;
81 friend class ExplodedNode;
82 friend class NodeBuilder;
83
84 ProgramStateManager *stateMgr;
85 Environment Env; // Maps a Stmt to its current SVal.
86 Store store; // Maps a location to its current value.
87 GenericDataMap GDM; // Custom data stored by a client of this class.
88
89 // A state is infeasible if there is a contradiction among the constraints.
90 // An infeasible state is represented by a `nullptr`.
91 // In the sense of `assumeDual`, a state can have two children by adding a
92 // new constraint and the negation of that new constraint. A parent state is
93 // over-constrained if both of its children are infeasible. In the
94 // mathematical sense, it means that the parent is infeasible and we should
95 // have realized that at the moment when we have created it. However, we
96 // could not recognize that because of the imperfection of the underlying
97 // constraint solver. We say it is posteriorly over-constrained because we
98 // recognize that a parent is infeasible only *after* a new and more specific
99 // constraint and its negation are evaluated.
100 //
101 // Example:
102 //
103 // x * x = 4 and x is in the range [0, 1]
104 // This is an already infeasible state, but the constraint solver is not
105 // capable of handling sqrt, thus we don't know it yet.
106 //
107 // Then a new constraint `x = 0` is added. At this moment the constraint
108 // solver re-evaluates the existing constraints and realizes the
109 // contradiction `0 * 0 = 4`.
110 // We also evaluate the negated constraint `x != 0`; the constraint solver
111 // deduces `x = 1` and then realizes the contradiction `1 * 1 = 4`.
112 // Both children are infeasible, thus the parent state is marked as
113 // posteriorly over-constrained. These parents are handled with special care:
114 // we do not allow transitions to exploded nodes with such states.
115 bool PosteriorlyOverconstrained = false;
116 // Make internal constraint solver entities friends so they can access the
117 // overconstrained-related functions. We want to keep this API inaccessible
118 // for Checkers.
119 friend class ConstraintManager;
120 bool isPosteriorlyOverconstrained() const {
121 return PosteriorlyOverconstrained;
122 }
123 ProgramStateRef cloneAsPosteriorlyOverconstrained() const;
124
125 unsigned refCount;
126
127 /// makeWithStore - Return a ProgramState with the same values as the current
128 /// state with the exception of using the specified Store.
129 ProgramStateRef makeWithStore(const StoreRef &store) const;
130
131 void setStore(const StoreRef &storeRef);
132
133public:
134 /// This ctor is used when creating the first ProgramState object.
136 StoreRef st, GenericDataMap gdm);
137
138 /// Copy ctor - We must explicitly define this or else the "Next" ptr
139 /// in FoldingSetNode will also get copied.
140 ProgramState(const ProgramState &RHS);
141
143
144 int64_t getID() const;
145
146 /// Return the ProgramStateManager associated with this state.
148 return *stateMgr;
149 }
150
152
153 /// Return the ConstraintManager.
155
156 /// getEnvironment - Return the environment associated with this state.
157 /// The environment is the mapping from expressions to values.
158 const Environment& getEnvironment() const { return Env; }
159
160 /// Return the store associated with this state. The store
161 /// is a mapping from locations to values.
162 Store getStore() const { return store; }
163
164
165 /// getGDM - Return the generic data map associated with this state.
166 GenericDataMap getGDM() const { return GDM; }
167
168 void setGDM(GenericDataMap gdm) { GDM = gdm; }
169
170 /// Profile - Profile the contents of a ProgramState object for use in a
171 /// FoldingSet. Two ProgramState objects are considered equal if they
172 /// have the same Environment, Store, and GenericDataMap.
173 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
174 V->Env.Profile(ID);
175 ID.AddPointer(V->store);
176 V->GDM.Profile(ID);
177 ID.AddBoolean(V->PosteriorlyOverconstrained);
178 }
179
180 /// Profile - Used to profile the contents of this object for inclusion
181 /// in a FoldingSet.
182 void Profile(llvm::FoldingSetNodeID& ID) const {
183 Profile(ID, this);
184 }
185
188
189 //==---------------------------------------------------------------------==//
190 // Constraints on values.
191 //==---------------------------------------------------------------------==//
192 //
193 // Each ProgramState records constraints on symbolic values. These constraints
194 // are managed using the ConstraintManager associated with a ProgramStateManager.
195 // As constraints gradually accrue on symbolic values, added constraints
196 // may conflict and indicate that a state is infeasible (as no real values
197 // could satisfy all the constraints). This is the principal mechanism
198 // for modeling path-sensitivity in ExprEngine/ProgramState.
199 //
200 // Various "assume" methods form the interface for adding constraints to
201 // symbolic values. A call to 'assume' indicates an assumption being placed
202 // on one or symbolic values. 'assume' methods take the following inputs:
203 //
204 // (1) A ProgramState object representing the current state.
205 //
206 // (2) The assumed constraint (which is specific to a given "assume" method).
207 //
208 // (3) A binary value "Assumption" that indicates whether the constraint is
209 // assumed to be true or false.
210 //
211 // The output of "assume*" is a new ProgramState object with the added constraints.
212 // If no new state is feasible, NULL is returned.
213 //
214
215 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
216 /// or non-zero (if \p assumption is "true").
217 ///
218 /// This returns a new state with the added constraint on \p cond.
219 /// If no new state is feasible, NULL is returned.
221 bool assumption) const;
222
223 /// Assumes both "true" and "false" for \p cond, and returns both
224 /// corresponding states (respectively).
225 ///
226 /// This is more efficient than calling assume() twice. Note that one (but not
227 /// both) of the returned states may be NULL.
228 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
229 assume(DefinedOrUnknownSVal cond) const;
230
231 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
233 QualType IndexType = QualType()) const;
234
235 [[nodiscard]] ProgramStateRef
237 bool assumption, QualType IndexType = QualType()) const;
238
239 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
240 /// (if \p assumption is "true") or it is fully out of this range
241 /// (if \p assumption is "false").
242 ///
243 /// This returns a new state with the added constraint on \p cond.
244 /// If no new state is feasible, NULL is returned.
246 const llvm::APSInt &From,
247 const llvm::APSInt &To,
248 bool assumption) const;
249
250 /// Assumes given range both "true" and "false" for \p Val, and returns both
251 /// corresponding states (respectively).
252 ///
253 /// This is more efficient than calling assume() twice. Note that one (but not
254 /// both) of the returned states may be NULL.
255 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
256 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
257 const llvm::APSInt &To) const;
258
259 /// Check if the given SVal is not constrained to zero and is not
260 /// a zero constant.
262
263 /// Check if the given SVal is constrained to zero or is a zero
264 /// constant.
266
267 /// \return Whether values \p Lhs and \p Rhs are equal.
268 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
269
270 /// Utility method for getting regions.
271 LLVM_ATTRIBUTE_RETURNS_NONNULL
272 const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
273
274 //==---------------------------------------------------------------------==//
275 // Binding and retrieving values to/from the environment and symbolic store.
276 //==---------------------------------------------------------------------==//
277
278 /// Create a new state by binding the value 'V' to the statement 'S' in the
279 /// state's environment.
280 [[nodiscard]] ProgramStateRef BindExpr(const Stmt *S,
281 const LocationContext *LCtx, SVal V,
282 bool Invalidate = true) const;
283
284 [[nodiscard]] ProgramStateRef bindLoc(Loc location, SVal V,
285 const LocationContext *LCtx,
286 bool notifyChanges = true) const;
287
288 [[nodiscard]] ProgramStateRef bindLoc(SVal location, SVal V,
289 const LocationContext *LCtx) const;
290
291 /// Initializes the region of memory represented by \p loc with an initial
292 /// value. Once initialized, all values loaded from any sub-regions of that
293 /// region will be equal to \p V, unless overwritten later by the program.
294 /// This method should not be used on regions that are already initialized.
295 /// If you need to indicate that memory contents have suddenly become unknown
296 /// within a certain region of memory, consider invalidateRegions().
297 [[nodiscard]] ProgramStateRef
298 bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const;
299
300 /// Performs C++ zero-initialization procedure on the region of memory
301 /// represented by \p loc.
302 [[nodiscard]] ProgramStateRef
303 bindDefaultZero(SVal loc, const LocationContext *LCtx) const;
304
305 [[nodiscard]] ProgramStateRef killBinding(Loc LV) const;
306
307 /// Returns the state with bindings for the given regions cleared from the
308 /// store. If \p Call is non-null, also invalidates global regions (but if
309 /// \p Call is from a system header, then this is limited to globals declared
310 /// in system headers).
311 ///
312 /// This calls the lower-level method \c StoreManager::invalidateRegions to
313 /// do the actual invalidation, then calls the checker callbacks which should
314 /// be triggered by this event.
315 ///
316 /// \param Regions the set of regions to be invalidated.
317 /// \param E the expression that caused the invalidation.
318 /// \param BlockCount The number of times the current basic block has been
319 /// visited.
320 /// \param CausesPointerEscape the flag is set to true when the invalidation
321 /// entails escape of a symbol (representing a pointer). For example,
322 /// due to it being passed as an argument in a call.
323 /// \param IS the set of invalidated symbols.
324 /// \param Call if non-null, the invalidated regions represent parameters to
325 /// the call and should be considered directly invalidated.
326 /// \param ITraits information about special handling for particular regions
327 /// or symbols.
328 [[nodiscard]] ProgramStateRef
330 unsigned BlockCount, const LocationContext *LCtx,
331 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
332 const CallEvent *Call = nullptr,
333 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
334
335 [[nodiscard]] ProgramStateRef
336 invalidateRegions(ArrayRef<SVal> Values, const Expr *E, unsigned BlockCount,
337 const LocationContext *LCtx, bool CausesPointerEscape,
338 InvalidatedSymbols *IS = nullptr,
339 const CallEvent *Call = nullptr,
340 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
341
342 /// enterStackFrame - Returns the state for entry to the given stack frame,
343 /// preserving the current state.
344 [[nodiscard]] ProgramStateRef
346 const StackFrameContext *CalleeCtx) const;
347
348 /// Return the value of 'self' if available in the given context.
349 SVal getSelfSVal(const LocationContext *LC) const;
350
351 /// Get the lvalue for a base class object reference.
352 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
353
354 /// Get the lvalue for a base class object reference.
355 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
356 bool IsVirtual) const;
357
358 /// Get the lvalue for a variable reference.
359 Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
360
361 Loc getLValue(const CompoundLiteralExpr *literal,
362 const LocationContext *LC) const;
363
364 /// Get the lvalue for an ivar reference.
365 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
366
367 /// Get the lvalue for a field reference.
368 SVal getLValue(const FieldDecl *decl, SVal Base) const;
369
370 /// Get the lvalue for an indirect field reference.
372
373 /// Get the lvalue for an array index.
374 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
375
376 /// Returns the SVal bound to the statement 'S' in the state's environment.
377 SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
378
379 SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
380
381 /// Return the value bound to the specified location.
382 /// Returns UnknownVal() if none found.
383 SVal getSVal(Loc LV, QualType T = QualType()) const;
384
385 /// Returns the "raw" SVal bound to LV before any value simplfication.
386 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
387
388 /// Return the value bound to the specified location.
389 /// Returns UnknownVal() if none found.
390 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
391
392 /// Return the value bound to the specified location, assuming
393 /// that the value is a scalar integer or an enumeration or a pointer.
394 /// Returns UnknownVal() if none found or the region is not known to hold
395 /// a value of such type.
396 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
397
398 using region_iterator = const MemRegion **;
399
400 /// Visits the symbols reachable from the given SVal using the provided
401 /// SymbolVisitor.
402 ///
403 /// This is a convenience API. Consider using ScanReachableSymbols class
404 /// directly when making multiple scans on the same state with the same
405 /// visitor to avoid repeated initialization cost.
406 /// \sa ScanReachableSymbols
407 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
408
409 /// Visits the symbols reachable from the regions in the given
410 /// MemRegions range using the provided SymbolVisitor.
411 bool scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable,
412 SymbolVisitor &visitor) const;
413
414 template <typename CB> CB scanReachableSymbols(SVal val) const;
415 template <typename CB> CB
416 scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable) const;
417
418 //==---------------------------------------------------------------------==//
419 // Accessing the Generic Data Map (GDM).
420 //==---------------------------------------------------------------------==//
421
422 void *const* FindGDM(void *K) const;
423
424 template <typename T>
425 [[nodiscard]] ProgramStateRef
426 add(typename ProgramStateTrait<T>::key_type K) const;
427
428 template <typename T>
430 get() const {
432 }
433
434 template<typename T>
437 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
439 }
440
441 template <typename T>
443
444 template <typename T>
445 [[nodiscard]] ProgramStateRef
446 remove(typename ProgramStateTrait<T>::key_type K) const;
447
448 template <typename T>
449 [[nodiscard]] ProgramStateRef
452
453 template <typename T> [[nodiscard]] ProgramStateRef remove() const;
454
455 template <typename T>
456 [[nodiscard]] ProgramStateRef
457 set(typename ProgramStateTrait<T>::data_type D) const;
458
459 template <typename T>
460 [[nodiscard]] ProgramStateRef
462 typename ProgramStateTrait<T>::value_type E) const;
463
464 template <typename T>
465 [[nodiscard]] ProgramStateRef
469
470 template<typename T>
471 bool contains(typename ProgramStateTrait<T>::key_type key) const {
472 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
474 }
475
476 // Pretty-printing.
477 void printJson(raw_ostream &Out, const LocationContext *LCtx = nullptr,
478 const char *NL = "\n", unsigned int Space = 0,
479 bool IsDot = false) const;
480
481 void printDOT(raw_ostream &Out, const LocationContext *LCtx = nullptr,
482 unsigned int Space = 0) const;
483
484 void dump() const;
485
486private:
487 friend void ProgramStateRetain(const ProgramState *state);
488 friend void ProgramStateRelease(const ProgramState *state);
489
490 SVal wrapSymbolicRegion(SVal Base) const;
491};
492
493//===----------------------------------------------------------------------===//
494// ProgramStateManager - Factory object for ProgramStates.
495//===----------------------------------------------------------------------===//
496
498 friend class ProgramState;
499 friend void ProgramStateRelease(const ProgramState *state);
500private:
501 /// Eng - The ExprEngine that owns this state manager.
502 ExprEngine *Eng; /* Can be null. */
503
504 EnvironmentManager EnvMgr;
505 std::unique_ptr<StoreManager> StoreMgr;
506 std::unique_ptr<ConstraintManager> ConstraintMgr;
507
508 ProgramState::GenericDataMap::Factory GDMFactory;
509
510 typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
511 GDMContextsTy GDMContexts;
512
513 /// StateSet - FoldingSet containing all the states created for analyzing
514 /// a particular function. This is used to unique states.
515 llvm::FoldingSet<ProgramState> StateSet;
516
517 /// Object that manages the data for all created SVals.
518 std::unique_ptr<SValBuilder> svalBuilder;
519
520 /// Manages memory for created CallEvents.
521 std::unique_ptr<CallEventManager> CallEventMgr;
522
523 /// A BumpPtrAllocator to allocate states.
524 llvm::BumpPtrAllocator &Alloc;
525
526 /// A vector of ProgramStates that we can reuse.
527 std::vector<ProgramState *> freeStates;
528
529public:
531 StoreManagerCreator CreateStoreManager,
532 ConstraintManagerCreator CreateConstraintManager,
533 llvm::BumpPtrAllocator& alloc,
534 ExprEngine *expreng);
535
537
539
540 ASTContext &getContext() { return svalBuilder->getContext(); }
541 const ASTContext &getContext() const { return svalBuilder->getContext(); }
542
544 return svalBuilder->getBasicValueFactory();
545 }
546
548 return *svalBuilder;
549 }
550
552 return *svalBuilder;
553 }
554
556 return svalBuilder->getSymbolManager();
557 }
559 return svalBuilder->getSymbolManager();
560 }
561
562 llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
563
565 return svalBuilder->getRegionManager();
566 }
568 return svalBuilder->getRegionManager();
569 }
570
571 CallEventManager &getCallEventManager() { return *CallEventMgr; }
572
573 StoreManager &getStoreManager() { return *StoreMgr; }
574 ConstraintManager &getConstraintManager() { return *ConstraintMgr; }
575 ExprEngine &getOwningEngine() { return *Eng; }
576
579 const StackFrameContext *LCtx,
580 SymbolReaper &SymReaper);
581
582public:
583
584 SVal ArrayToPointer(Loc Array, QualType ElementTy) {
585 return StoreMgr->ArrayToPointer(Array, ElementTy);
586 }
587
588 // Methods that manipulate the GDM.
589 ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
590 ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
591
592 // Methods that query & manipulate the Store.
593
595 StoreMgr->iterBindings(state->getStore(), F);
596 }
597
600 ProgramStateRef GDMState);
601
603 return ConstraintMgr->haveEqualConstraints(S1, S2);
604 }
605
607 return S1->Env == S2->Env;
608 }
609
611 return S1->store == S2->store;
612 }
613
614 //==---------------------------------------------------------------------==//
615 // Generic Data Map methods.
616 //==---------------------------------------------------------------------==//
617 //
618 // ProgramStateManager and ProgramState support a "generic data map" that allows
619 // different clients of ProgramState objects to embed arbitrary data within a
620 // ProgramState object. The generic data map is essentially an immutable map
621 // from a "tag" (that acts as the "key" for a client) and opaque values.
622 // Tags/keys and values are simply void* values. The typical way that clients
623 // generate unique tags are by taking the address of a static variable.
624 // Clients are responsible for ensuring that data values referred to by a
625 // the data pointer are immutable (and thus are essentially purely functional
626 // data).
627 //
628 // The templated methods below use the ProgramStateTrait<T> class
629 // to resolve keys into the GDM and to return data values to clients.
630 //
631
632 // Trait based GDM dispatch.
633 template <typename T>
637 }
638
639 template<typename T>
644
647 }
648
649 template <typename T>
655 }
656
657 template <typename T>
661
664 }
665
666 template <typename T>
669 }
670
671 void *FindGDMContext(void *index,
672 void *(*CreateContext)(llvm::BumpPtrAllocator&),
673 void (*DeleteContext)(void*));
674
675 template <typename T>
680
682 }
683};
684
685
686//===----------------------------------------------------------------------===//
687// Out-of-line method definitions for ProgramState.
688//===----------------------------------------------------------------------===//
689
691 return stateMgr->getConstraintManager();
692}
693
695 const LocationContext *LC) const
696{
698}
699
701 bool Assumption) const {
702 if (Cond.isUnknown())
703 return this;
704
705 return getStateManager().ConstraintMgr
706 ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
707}
708
709inline std::pair<ProgramStateRef , ProgramStateRef >
711 if (Cond.isUnknown())
712 return std::make_pair(this, this);
713
714 return getStateManager().ConstraintMgr
715 ->assumeDual(this, Cond.castAs<DefinedSVal>());
716}
717
719 DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
720 bool Assumption) const {
721 if (Val.isUnknown())
722 return this;
723
724 assert(isa<NonLoc>(Val) && "Only NonLocs are supported!");
725
726 return getStateManager().ConstraintMgr->assumeInclusiveRange(
727 this, Val.castAs<NonLoc>(), From, To, Assumption);
728}
729
730inline std::pair<ProgramStateRef, ProgramStateRef>
732 const llvm::APSInt &From,
733 const llvm::APSInt &To) const {
734 if (Val.isUnknown())
735 return std::make_pair(this, this);
736
737 assert(isa<NonLoc>(Val) && "Only NonLocs are supported!");
738
739 return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
740 this, Val.castAs<NonLoc>(), From, To);
741}
742
744 if (std::optional<Loc> L = LV.getAs<Loc>())
745 return bindLoc(*L, V, LCtx);
746 return this;
747}
748
750 const SubRegion *Super) const {
751 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
752 return loc::MemRegionVal(
753 getStateManager().getRegionManager().getCXXBaseObjectRegion(
754 Base, Super, BaseSpec.isVirtual()));
755}
756
758 const SubRegion *Super,
759 bool IsVirtual) const {
760 return loc::MemRegionVal(
761 getStateManager().getRegionManager().getCXXBaseObjectRegion(
762 BaseClass, Super, IsVirtual));
763}
764
766 const LocationContext *LC) const {
767 return getStateManager().StoreMgr->getLValueVar(VD, LC);
768}
769
771 const LocationContext *LC) const {
772 return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
773}
774
776 return getStateManager().StoreMgr->getLValueIvar(D, Base);
777}
778
779inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
780 if (std::optional<NonLoc> N = Idx.getAs<NonLoc>())
781 return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
782 return UnknownVal();
783}
784
786 const LocationContext *LCtx) const{
787 return Env.getSVal(EnvironmentEntry(Ex, LCtx),
788 *getStateManager().svalBuilder);
789}
790
791inline SVal
793 const LocationContext *LCtx) const {
794 if (const Expr *Ex = dyn_cast<Expr>(S)) {
795 QualType T = Ex->getType();
796 if (Ex->isGLValue() || Loc::isLocType(T) ||
798 return getSVal(S, LCtx);
799 }
800
801 return UnknownVal();
802}
803
805 return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
806}
807
809 return getStateManager().StoreMgr->getBinding(getStore(),
811 T);
812}
813
815 return getStateManager().getBasicVals();
816}
817
820}
821
822template<typename T>
824 return getStateManager().add<T>(this, K, get_context<T>());
825}
826
827template <typename T>
829 return getStateManager().get_context<T>();
830}
831
832template<typename T>
834 return getStateManager().remove<T>(this, K, get_context<T>());
835}
836
837template<typename T>
839 typename ProgramStateTrait<T>::context_type C) const {
840 return getStateManager().remove<T>(this, K, C);
841}
842
843template <typename T>
845 return getStateManager().remove<T>(this);
846}
847
848template<typename T>
850 return getStateManager().set<T>(this, D);
851}
852
853template<typename T>
855 typename ProgramStateTrait<T>::value_type E) const {
856 return getStateManager().set<T>(this, K, E, get_context<T>());
857}
858
859template<typename T>
862 typename ProgramStateTrait<T>::context_type C) const {
863 return getStateManager().set<T>(this, K, E, C);
864}
865
866template <typename CB>
868 CB cb(this);
869 scanReachableSymbols(val, cb);
870 return cb;
871}
872
873template <typename CB>
875 llvm::iterator_range<region_iterator> Reachable) const {
876 CB cb(this);
877 scanReachableSymbols(Reachable, cb);
878 return cb;
879}
880
881/// \class ScanReachableSymbols
882/// A utility class that visits the reachable symbols using a custom
883/// SymbolVisitor. Terminates recursive traversal when the visitor function
884/// returns false.
886 typedef llvm::DenseSet<const void*> VisitedItems;
887
888 VisitedItems visited;
889 ProgramStateRef state;
890 SymbolVisitor &visitor;
891public:
893 : state(std::move(st)), visitor(v) {}
894
896 bool scan(nonloc::CompoundVal val);
897 bool scan(SVal val);
898 bool scan(const MemRegion *R);
899 bool scan(const SymExpr *sym);
900};
901
902} // end ento namespace
903
904} // end clang namespace
905
906#endif
#define V(N, I)
Definition: ASTContext.h:3341
StringRef P
static char ID
Definition: Arena.cpp:183
const Decl * D
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:22
const Environment & Env
Definition: HTMLLogger.cpp:148
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
do v
Definition: arm_acle.h:91
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
A (possibly-)qualified type.
Definition: Type.h:941
It represents a stack frame of the call stack (based on CallEvent).
Stmt - This represents one statement.
Definition: Stmt.h:84
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8434
Represents a variable declaration or definition.
Definition: Decl.h:879
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1356
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
An entry in the environment consists of a Stmt and an LocationContext.
Definition: Environment.h:36
An immutable map from EnvironemntEntries to SVals.
Definition: Environment.h:56
static bool isLocType(QualType T)
Definition: SVals.h:259
const VarRegion * getVarRegion(const VarDecl *VD, const LocationContext *LC)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and LocationC...
Definition: MemRegion.cpp:1002
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:97
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:232
ProgramStateRef remove(ProgramStateRef st)
Definition: ProgramState.h:667
const MemRegionManager & getRegionManager() const
Definition: ProgramState.h:567
ProgramStateRef removeDeadBindingsFromEnvironmentAndStore(ProgramStateRef St, const StackFrameContext *LCtx, SymbolReaper &SymReaper)
bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) const
Definition: ProgramState.h:610
const ASTContext & getContext() const
Definition: ProgramState.h:541
ProgramStateRef removeGDM(ProgramStateRef state, void *Key)
void * FindGDMContext(void *index, void *(*CreateContext)(llvm::BumpPtrAllocator &), void(*DeleteContext)(void *))
CallEventManager & getCallEventManager()
Definition: ProgramState.h:571
bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) const
Definition: ProgramState.h:606
const SymbolManager & getSymbolManager() const
Definition: ProgramState.h:558
const SValBuilder & getSValBuilder() const
Definition: ProgramState.h:551
friend void ProgramStateRelease(const ProgramState *state)
Decrement the number of times this state is referenced.
ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait< T >::data_type D)
Definition: ProgramState.h:634
ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState, ProgramStateRef GDMState)
MemRegionManager & getRegionManager()
Definition: ProgramState.h:564
bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const
Definition: ProgramState.h:602
ProgramStateRef remove(ProgramStateRef st, typename ProgramStateTrait< T >::key_type K, typename ProgramStateTrait< T >::context_type C)
Definition: ProgramState.h:658
ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data)
ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait< T >::key_type K, typename ProgramStateTrait< T >::value_type V, typename ProgramStateTrait< T >::context_type C)
Definition: ProgramState.h:640
ProgramStateRef add(ProgramStateRef st, typename ProgramStateTrait< T >::key_type K, typename ProgramStateTrait< T >::context_type C)
Definition: ProgramState.h:650
ProgramStateRef getPersistentState(ProgramState &Impl)
void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler &F)
Definition: ProgramState.h:594
SVal ArrayToPointer(Loc Array, QualType ElementTy)
Definition: ProgramState.h:584
ProgramStateRef getInitialState(const LocationContext *InitLoc)
llvm::BumpPtrAllocator & getAllocator()
Definition: ProgramState.h:562
BasicValueFactory & getBasicVals()
Definition: ProgramState.h:543
ProgramStateTrait< T >::context_type get_context()
Definition: ProgramState.h:676
SymbolManager & getSymbolManager()
Definition: ProgramState.h:555
ConstraintManager & getConstraintManager()
Definition: ProgramState.h:574
ProgramState - This class encapsulates:
Definition: ProgramState.h:71
bool scanReachableSymbols(SVal val, SymbolVisitor &visitor) const
Visits the symbols reachable from the given SVal using the provided SymbolVisitor.
ProgramStateTrait< T >::data_type get() const
Definition: ProgramState.h:430
Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const
Get the lvalue for a base class object reference.
Definition: ProgramState.h:749
friend void ProgramStateRetain(const ProgramState *state)
Increments the number of times this state is referenced.
ProgramStateRef bindDefaultZero(SVal loc, const LocationContext *LCtx) const
Performs C++ zero-initialization procedure on the region of memory represented by loc.
llvm::ImmutableSet< llvm::APSInt * > IntSetTy
Definition: ProgramState.h:73
llvm::ImmutableMap< void *, void * > GenericDataMap
Definition: ProgramState.h:74
ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx, SVal V, bool Invalidate=true) const
Create a new state by binding the value 'V' to the statement 'S' in the state's environment.
void printJson(raw_ostream &Out, const LocationContext *LCtx=nullptr, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const
ProgramStateRef assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To, bool assumption) const
Assumes that the value of Val is bounded with [From; To] (if assumption is "true") or it is fully out...
Definition: ProgramState.h:718
bool contains(typename ProgramStateTrait< T >::key_type key) const
Definition: ProgramState.h:471
ProgramStateRef bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const
Initializes the region of memory represented by loc with an initial value.
ConstraintManager & getConstraintManager() const
Return the ConstraintManager.
Definition: ProgramState.h:690
ProgramStateRef add(typename ProgramStateTrait< T >::key_type K) const
Definition: ProgramState.h:823
SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const
Definition: ProgramState.h:792
void Profile(llvm::FoldingSetNodeID &ID) const
Profile - Used to profile the contents of this object for inclusion in a FoldingSet.
Definition: ProgramState.h:182
SVal getSelfSVal(const LocationContext *LC) const
Return the value of 'self' if available in the given context.
SVal getRawSVal(Loc LV, QualType T=QualType()) const
Returns the "raw" SVal bound to LV before any value simplfication.
Definition: ProgramState.h:804
ConditionTruthVal isNull(SVal V) const
Check if the given SVal is constrained to zero or is a zero constant.
ProgramStateManager & getStateManager() const
Return the ProgramStateManager associated with this state.
Definition: ProgramState.h:147
ProgramStateRef killBinding(Loc LV) const
GenericDataMap getGDM() const
getGDM - Return the generic data map associated with this state.
Definition: ProgramState.h:166
const Environment & getEnvironment() const
getEnvironment - Return the environment associated with this state.
Definition: ProgramState.h:158
friend void ProgramStateRelease(const ProgramState *state)
Decrement the number of times this state is referenced.
ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const
Assumes that the value of cond is zero (if assumption is "false") or non-zero (if assumption is "true...
Definition: ProgramState.h:700
Store getStore() const
Return the store associated with this state.
Definition: ProgramState.h:162
ProgramStateRef invalidateRegions(ArrayRef< const MemRegion * > Regions, const Expr *E, unsigned BlockCount, const LocationContext *LCtx, bool CausesPointerEscape, InvalidatedSymbols *IS=nullptr, const CallEvent *Call=nullptr, RegionAndSymbolInvalidationTraits *ITraits=nullptr) const
Returns the state with bindings for the given regions cleared from the store.
ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const
void printDOT(raw_ostream &Out, const LocationContext *LCtx=nullptr, unsigned int Space=0) const
ConditionTruthVal isNonNull(SVal V) const
Check if the given SVal is not constrained to zero and is not a zero constant.
ProgramStateRef set(typename ProgramStateTrait< T >::data_type D) const
Definition: ProgramState.h:849
ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound, bool assumption, QualType IndexType=QualType()) const
ProgramStateRef enterStackFrame(const CallEvent &Call, const StackFrameContext *CalleeCtx) const
enterStackFrame - Returns the state for entry to the given stack frame, preserving the current state.
LLVM_ATTRIBUTE_RETURNS_NONNULL const VarRegion * getRegion(const VarDecl *D, const LocationContext *LC) const
Utility method for getting regions.
Definition: ProgramState.h:694
SVal getSVal(const Stmt *S, const LocationContext *LCtx) const
Returns the SVal bound to the statement 'S' in the state's environment.
Definition: ProgramState.h:785
ProgramStateTrait< T >::lookup_type get(typename ProgramStateTrait< T >::key_type key) const
Definition: ProgramState.h:436
ProgramStateTrait< T >::context_type get_context() const
Definition: ProgramState.h:828
ProgramStateRef invalidateRegions(ArrayRef< SVal > Values, const Expr *E, unsigned BlockCount, const LocationContext *LCtx, bool CausesPointerEscape, InvalidatedSymbols *IS=nullptr, const CallEvent *Call=nullptr, RegionAndSymbolInvalidationTraits *ITraits=nullptr) const
ProgramStateRef bindLoc(Loc location, SVal V, const LocationContext *LCtx, bool notifyChanges=true) const
static void Profile(llvm::FoldingSetNodeID &ID, const ProgramState *V)
Profile - Profile the contents of a ProgramState object for use in a FoldingSet.
Definition: ProgramState.h:173
BasicValueFactory & getBasicVals() const
Definition: ProgramState.h:814
std::pair< ProgramStateRef, ProgramStateRef > assumeInBoundDual(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound, QualType IndexType=QualType()) const
ProgramStateRef remove() const
Definition: ProgramState.h:844
void setGDM(GenericDataMap gdm)
Definition: ProgramState.h:168
AnalysisManager & getAnalysisManager() const
void *const * FindGDM(void *K) const
SymbolManager & getSymbolManager() const
Definition: ProgramState.h:818
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1629
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition: SVals.h:86
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:82
bool isUnknown() const
Definition: SVals.h:102
A utility class that visits the reachable symbols using a custom SymbolVisitor.
Definition: ProgramState.h:885
ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
Definition: ProgramState.h:892
bool scan(nonloc::LazyCompoundVal val)
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:446
Symbolic value.
Definition: SymExpr.h:30
A class responsible for cleaning up unused symbols.
The simplest example of a concrete compound value is nonloc::CompoundVal, which represents a concrete...
Definition: SVals.h:333
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition: SVals.h:383
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
std::unique_ptr< ConstraintManager >(* ConstraintManagerCreator)(ProgramStateManager &, ExprEngine *)
Definition: ProgramState.h:42
std::unique_ptr< StoreManager >(* StoreManagerCreator)(ProgramStateManager &)
Definition: ProgramState.h:44
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition: Store.h:51
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition: StoreRef.h:27
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
static void * MakeVoidPtr(data_type D)
Definition: ProgramState.h:53
static data_type MakeData(void *const *P)
Definition: ProgramState.h:54