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