clang 24.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/ADT/STLExtras.h"
26#include "llvm/Support/Allocator.h"
27#include <optional>
28#include <utility>
29
30namespace llvm {
31class APSInt;
32}
33
34namespace clang {
35class ASTContext;
36
37namespace ento {
38
39class AnalysisManager;
40class CallEvent;
42
43typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
45typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
47
48//===----------------------------------------------------------------------===//
49// ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
50//===----------------------------------------------------------------------===//
51
52template <typename T> struct ProgramStateTrait {
53 typedef typename T::data_type data_type;
54 static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
55 static inline data_type MakeData(void *const* P) {
56 return P ? (data_type) *P : (data_type) 0;
57 }
58};
59
60/// \class ProgramState
61/// ProgramState - This class encapsulates:
62///
63/// 1. A mapping from expressions to values (Environment)
64/// 2. A mapping from locations to values (Store)
65/// 3. Constraints on symbolic values (GenericDataMap)
66///
67/// Together these represent the "abstract state" of a program.
68///
69/// ProgramState is intended to be used as a functional object; that is,
70/// once it is created and made "persistent" in a FoldingSet, its
71/// values will never change.
72class ProgramState : public llvm::FoldingSetNode {
73public:
74 typedef llvm::ImmutableMap<const 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
83 ProgramStateManager *stateMgr;
84 Environment Env; // Maps a Stmt to its current SVal.
85 Store store; // Maps a location to its current value.
86 GenericDataMap GDM; // Custom data stored by a client of this class.
87
88 // A state is infeasible if there is a contradiction among the constraints.
89 // An infeasible state is represented by a `nullptr`.
90 // In the sense of `assumeDual`, a state can have two children by adding a
91 // new constraint and the negation of that new constraint. A parent state is
92 // over-constrained if both of its children are infeasible. In the
93 // mathematical sense, it means that the parent is infeasible and we should
94 // have realized that at the moment when we have created it. However, we
95 // could not recognize that because of the imperfection of the underlying
96 // constraint solver. We say it is posteriorly over-constrained because we
97 // recognize that a parent is infeasible only *after* a new and more specific
98 // constraint and its negation are evaluated.
99 //
100 // Example:
101 //
102 // x * x = 4 and x is in the range [0, 1]
103 // This is an already infeasible state, but the constraint solver is not
104 // capable of handling sqrt, thus we don't know it yet.
105 //
106 // Then a new constraint `x = 0` is added. At this moment the constraint
107 // solver re-evaluates the existing constraints and realizes the
108 // contradiction `0 * 0 = 4`.
109 // We also evaluate the negated constraint `x != 0`; the constraint solver
110 // deduces `x = 1` and then realizes the contradiction `1 * 1 = 4`.
111 // Both children are infeasible, thus the parent state is marked as
112 // posteriorly over-constrained. These parents are handled with special care:
113 // we do not allow transitions to exploded nodes with such states.
114 bool PosteriorlyOverconstrained = false;
115 // Make internal constraint solver entities friends so they can access the
116 // overconstrained-related functions. We want to keep this API inaccessible
117 // for Checkers.
118 friend class ConstraintManager;
119 // The CoreEngine also needs to be a friend to mark nodes as sinks if they
120 // are generated with a PosteriorlyOverconstrained state.
121 // FIXME: Perform this check in the relevant methods of `ExplodedGraph` and
122 // remove this `friend` declaration.
123 friend class CoreEngine;
124 bool isPosteriorlyOverconstrained() const {
125 return PosteriorlyOverconstrained;
126 }
127 ProgramStateRef cloneAsPosteriorlyOverconstrained() const;
128
129 mutable unsigned refCount;
130
131 /// makeWithStore - Return a ProgramState with the same values as the current
132 /// state with the exception of using the specified Store.
133 ProgramStateRef makeWithStore(const StoreRef &store) const;
134 ProgramStateRef makeWithStore(const BindResult &BindRes) const;
135
136 void setStore(const StoreRef &storeRef);
137
138public:
139 /// This ctor is used when creating the first ProgramState object.
141 StoreRef st, GenericDataMap gdm);
142
143 /// Copy ctor - We must explicitly define this or else the "Next" ptr
144 /// in FoldingSetNode will also get copied.
145 ProgramState(const ProgramState &RHS);
147
149
150 int64_t getID() const;
151
152 /// Return the ProgramStateManager associated with this state.
154 return *stateMgr;
155 }
156
158
159 /// Return the ConstraintManager.
161
162 /// getEnvironment - Return the environment associated with this state.
163 /// The environment is the mapping from expressions to values.
164 const Environment& getEnvironment() const { return Env; }
165
166 /// Return the store associated with this state. The store
167 /// is a mapping from locations to values.
168 Store getStore() const { return store; }
169
170 /// getGDM - Return the generic data map associated with this state.
171 GenericDataMap getGDM() const { return GDM; }
172
173 void setGDM(GenericDataMap gdm) { GDM = gdm; }
174
175 /// Profile - Profile the contents of a ProgramState object for use in a
176 /// FoldingSet. Two ProgramState objects are considered equal if they
177 /// have the same Environment, Store, and GenericDataMap.
178 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
179 V->Env.Profile(ID);
180 ID.AddPointer(V->store);
181 V->GDM.Profile(ID);
182 ID.AddBoolean(V->PosteriorlyOverconstrained);
183 }
184
185 /// Profile - Used to profile the contents of this object for inclusion
186 /// in a FoldingSet.
187 void Profile(llvm::FoldingSetNodeID& ID) const {
188 Profile(ID, this);
189 }
190
193
194 //==---------------------------------------------------------------------==//
195 // Constraints on values.
196 //==---------------------------------------------------------------------==//
197 //
198 // Each ProgramState records constraints on symbolic values. These constraints
199 // are managed using the ConstraintManager associated with a ProgramStateManager.
200 // As constraints gradually accrue on symbolic values, added constraints
201 // may conflict and indicate that a state is infeasible (as no real values
202 // could satisfy all the constraints). This is the principal mechanism
203 // for modeling path-sensitivity in ExprEngine/ProgramState.
204 //
205 // Various "assume" methods form the interface for adding constraints to
206 // symbolic values. A call to 'assume' indicates an assumption being placed
207 // on one or symbolic values. 'assume' methods take the following inputs:
208 //
209 // (1) A ProgramState object representing the current state.
210 //
211 // (2) The assumed constraint (which is specific to a given "assume" method).
212 //
213 // (3) A binary value "Assumption" that indicates whether the constraint is
214 // assumed to be true or false.
215 //
216 // The output of "assume*" is a new ProgramState object with the added constraints.
217 // If no new state is feasible, NULL is returned.
218 //
219
220 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
221 /// or non-zero (if \p assumption is "true").
222 ///
223 /// This returns a new state with the added constraint on \p cond.
224 /// If no new state is feasible, NULL is returned.
226 bool assumption) const;
227
228 /// Assumes both "true" and "false" for \p cond, and returns both
229 /// corresponding states (respectively).
230 ///
231 /// This is more efficient than calling assume() twice. Note that one (but not
232 /// both) of the returned states may be NULL.
233 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
234 assume(DefinedOrUnknownSVal cond) const;
235
236 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
238 QualType IndexType = QualType()) const;
239
240 [[nodiscard]] ProgramStateRef
242 bool assumption, QualType IndexType = QualType()) const;
243
244 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
245 /// (if \p assumption is "true") or it is fully out of this range
246 /// (if \p assumption is "false").
247 ///
248 /// This returns a new state with the added constraint on \p cond.
249 /// If no new state is feasible, NULL is returned.
251 const llvm::APSInt &From,
252 const llvm::APSInt &To,
253 bool assumption) const;
254
255 /// Assumes given range both "true" and "false" for \p Val, and returns both
256 /// corresponding states (respectively).
257 ///
258 /// This is more efficient than calling assume() twice. Note that one (but not
259 /// both) of the returned states may be NULL.
260 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
261 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
262 const llvm::APSInt &To) const;
263
264 /// Check if the given SVal is not constrained to zero and is not
265 /// a zero constant.
267
268 /// Check if the given SVal is constrained to zero or is a zero
269 /// constant.
271
272 /// \return Whether values \p Lhs and \p Rhs are equal.
273 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
274
275 /// Utility method for getting regions.
276 LLVM_ATTRIBUTE_RETURNS_NONNULL
277 const VarRegion *getRegion(const VarDecl *D, const StackFrame *SF) const;
278
279 //==---------------------------------------------------------------------==//
280 // Binding and retrieving values to/from the environment and symbolic store.
281 //==---------------------------------------------------------------------==//
282
283 /// Create a new state by binding the value \p V to the expression \p E in
284 /// the state's environment.
285 [[nodiscard]] ProgramStateRef BindExpr(const Expr *E, const StackFrame *SF,
286 SVal V, bool Invalidate = true) const;
287
288 [[nodiscard]] ProgramStateRef bindLoc(Loc location, SVal V,
289 const StackFrame *SF,
290 bool notifyChanges = true) const;
291
292 [[nodiscard]] ProgramStateRef bindLoc(SVal location, SVal V,
293 const StackFrame *SF) const;
294
295 /// Initializes the region of memory represented by \p loc with an initial
296 /// value. Once initialized, all values loaded from any sub-regions of that
297 /// region will be equal to \p V, unless overwritten later by the program.
298 /// This method should not be used on regions that are already initialized.
299 /// If you need to indicate that memory contents have suddenly become unknown
300 /// within a certain region of memory, consider invalidateRegions().
302 const StackFrame *SF) const;
303
304 /// Performs C++ zero-initialization procedure on the region of memory
305 /// represented by \p loc.
307 const StackFrame *SF) const;
308
309 [[nodiscard]] ProgramStateRef killBinding(Loc LV) const;
310
311 /// Returns the state with bindings for the given regions cleared from the
312 /// store. If \p Call is non-null, also invalidates global regions (but if
313 /// \p Call is from a system header, then this is limited to globals declared
314 /// in system headers).
315 ///
316 /// This calls the lower-level method \c StoreManager::invalidateRegions to
317 /// do the actual invalidation, then calls the checker callbacks which should
318 /// be triggered by this event.
319 ///
320 /// \param Regions the set of regions to be invalidated.
321 /// \param Elem The CFG Element that caused the invalidation.
322 /// \param BlockCount The number of times the current basic block has been
323 /// visited.
324 /// \param CausesPointerEscape the flag is set to true when the invalidation
325 /// entails escape of a symbol (representing a pointer). For example,
326 /// due to it being passed as an argument in a call.
327 /// \param IS the set of invalidated symbols.
328 /// \param Call if non-null, the invalidated regions represent parameters to
329 /// the call and should be considered directly invalidated.
330 /// \param ITraits information about special handling for particular regions
331 /// or symbols.
334 unsigned BlockCount, const StackFrame *SF, bool CausesPointerEscape,
335 InvalidatedSymbols *IS = nullptr, const CallEvent *Call = nullptr,
336 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
337
338 [[nodiscard]] ProgramStateRef
340 unsigned BlockCount, const StackFrame *SF,
341 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
342 const CallEvent *Call = nullptr,
343 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
344
345 /// enterStackFrame - Returns the state for entry to the given stack frame,
346 /// preserving the current state.
347 [[nodiscard]] ProgramStateRef
348 enterStackFrame(const CallEvent &Call, const StackFrame *CalleeSF) const;
349
350 /// Return the value of 'self' if available in the given context.
351 SVal getSelfSVal(const StackFrame *SF) const;
352
353 /// Get the lvalue for a base class object reference.
354 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
355
356 /// Get the lvalue for a base class object reference.
357 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
358 bool IsVirtual) const;
359
360 /// Get the lvalue for a variable reference.
361 Loc getLValue(const VarDecl *D, const StackFrame *SF) const;
362
363 Loc getLValue(const CompoundLiteralExpr *literal, const StackFrame *SF) const;
364
365 /// Get the lvalue for an ivar reference.
366 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
367
368 /// Get the lvalue for a field reference.
369 SVal getLValue(const FieldDecl *decl, SVal Base) const;
370
371 /// Get the lvalue for an indirect field reference.
373
374 /// Get the lvalue for an array index.
375 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
376
377 /// Returns the SVal bound to the expression \p E in the state's environment.
378 SVal getSVal(const Expr *E, const StackFrame *SF) const;
379
380 SVal getSValAsScalarOrLoc(const Expr *E, const StackFrame *SF) const;
381
382 /// Return the value bound to the specified location.
383 /// Returns UnknownVal() if none found.
384 SVal getSVal(Loc LV, QualType T = QualType()) const;
385
386 /// Returns the "raw" SVal bound to LV before any value simplification.
387 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
388
389 /// Return the value bound to the specified location.
390 /// Returns UnknownVal() if none found.
391 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
392
393 /// Return the value bound to the specified location, assuming
394 /// that the value is a scalar integer or an enumeration or a pointer.
395 /// Returns UnknownVal() if none found or the region is not known to hold
396 /// a value of such type.
397 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
398
399 using region_iterator = const MemRegion **;
400
401 /// Visits the symbols reachable from the given SVal using the provided
402 /// SymbolVisitor.
403 ///
404 /// This is a convenience API. Consider using ScanReachableSymbols class
405 /// directly when making multiple scans on the same state with the same
406 /// visitor to avoid repeated initialization cost.
407 /// \sa ScanReachableSymbols
408 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
409
410 /// Visits the symbols reachable from the regions in the given
411 /// MemRegions range using the provided SymbolVisitor.
412 bool scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable,
413 SymbolVisitor &visitor) const;
414
415 template <typename CB> CB scanReachableSymbols(SVal val) const;
416 template <typename CB> CB
417 scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable) const;
418
419 //==---------------------------------------------------------------------==//
420 // Accessing the Generic Data Map (GDM).
421 //==---------------------------------------------------------------------==//
422
423 void *const *FindGDM(const void *K) const;
424
425 template <typename T>
426 [[nodiscard]] ProgramStateRef
427 add(typename ProgramStateTrait<T>::key_type K) const;
428
429 template <typename T>
434
435 template<typename T>
441
442 template <typename T>
444
445 template <typename T>
446 [[nodiscard]] ProgramStateRef
447 remove(typename ProgramStateTrait<T>::key_type K) const;
448
449 template <typename T>
450 [[nodiscard]] ProgramStateRef
453
454 template <typename T> [[nodiscard]] ProgramStateRef remove() const;
455
456 template <typename T>
457 [[nodiscard]] ProgramStateRef
458 set(typename ProgramStateTrait<T>::data_type D) const;
459
460 template <typename T>
461 [[nodiscard]] ProgramStateRef
463 typename ProgramStateTrait<T>::value_type E) const;
464
465 template <typename T>
466 [[nodiscard]] ProgramStateRef
470
471 template<typename T>
476
477 // Pretty-printing.
478 void printJson(raw_ostream &Out, const StackFrame *SF = nullptr,
479 const char *NL = "\n", unsigned int Space = 0,
480 bool IsDot = false) const;
481
482 void printDOT(raw_ostream &Out, const StackFrame *SF = nullptr,
483 unsigned int Space = 0) const;
484
485 void dump() const;
486
487private:
488 friend struct llvm::IntrusiveRefCntPtrInfo<const ProgramState>;
489
490 void retain() const { ++refCount; }
491 void release() const;
492
493 SVal desugarReference(SVal Val) const;
494 SVal wrapSymbolicRegion(SVal Base) const;
495};
496
497//===----------------------------------------------------------------------===//
498// ProgramStateManager - Factory object for ProgramStates.
499//===----------------------------------------------------------------------===//
500
502 friend class ProgramState;
503
504private:
505 /// Eng - The ExprEngine that owns this state manager.
506 ExprEngine *Eng; /* Can be null. */
507
508 EnvironmentManager EnvMgr;
509 std::unique_ptr<StoreManager> StoreMgr;
510
511 ProgramState::GenericDataMap::Factory GDMFactory;
512
513 /// Owns the GDM contexts:
514 /// Maps a GDM key to its context and to the function that destroys it.
515 class GDMContextsTy {
516 public:
517 using GDMKey = void *;
518 using ConstGDMKey = const void *;
519 using DeleterTy = void (*)(GDMKey);
520 using ContextAndDeleter = std::pair<GDMKey, DeleterTy>;
521
522 GDMContextsTy() = default;
523 GDMContextsTy(const GDMContextsTy &) = delete;
524 GDMContextsTy &operator=(const GDMContextsTy &) = delete;
525
526 ~GDMContextsTy() {
527 for (auto [Ctx, Deleter] : llvm::make_second_range(Contexts))
528 Deleter(Ctx);
529 }
530
531 ContextAndDeleter &operator[](ConstGDMKey Key) { return Contexts[Key]; }
532
533 private:
534 llvm::DenseMap<ConstGDMKey, ContextAndDeleter> Contexts;
535 };
536 GDMContextsTy GDMContexts;
537
538 /// StateSet - FoldingSet containing all the states created for analyzing
539 /// a particular function. This is used to unique states.
540 llvm::FoldingSet<ProgramState> StateSet;
541
542 /// Object that manages the data for all created SVals.
543 std::unique_ptr<SValBuilder> svalBuilder;
544
545 /// Manages memory for created CallEvents.
546 std::unique_ptr<CallEventManager> CallEventMgr;
547
548 /// A BumpPtrAllocator to allocate states.
549 llvm::BumpPtrAllocator &Alloc;
550
551 /// A vector of ProgramStates that we can reuse.
552 std::vector<ProgramState *> freeStates;
553
554 /// Declared last, so that it is destroyed first. A constraint manager may
555 /// cache ProgramStateRefs, and releasing a state needs the members above
556 /// (the state set, the allocator, the GDM contexts, ...) to still be alive.
557 std::unique_ptr<ConstraintManager> ConstraintMgr;
558
559 /// Called when the reference count of \p State drops to zero.
560 void freeState(ProgramState *State);
561
562public:
564 StoreManagerCreator CreateStoreManager,
565 ConstraintManagerCreator CreateConstraintManager,
566 llvm::BumpPtrAllocator& alloc,
567 ExprEngine *expreng);
568
570
572
573 ASTContext &getContext() { return svalBuilder->getContext(); }
574 const ASTContext &getContext() const { return svalBuilder->getContext(); }
575
577 return svalBuilder->getBasicValueFactory();
578 }
579
581 return *svalBuilder;
582 }
583
585 return *svalBuilder;
586 }
587
589 return svalBuilder->getSymbolManager();
590 }
592 return svalBuilder->getSymbolManager();
593 }
594
595 llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
596
598 return svalBuilder->getRegionManager();
599 }
601 return svalBuilder->getRegionManager();
602 }
603
604 CallEventManager &getCallEventManager() { return *CallEventMgr; }
605
606 StoreManager &getStoreManager() { return *StoreMgr; }
607 const StoreManager &getStoreManager() const { return *StoreMgr; }
608 ConstraintManager &getConstraintManager() { return *ConstraintMgr; }
610 return *ConstraintMgr;
611 }
612 ExprEngine &getOwningEngine() { return *Eng; }
613
615 ProgramStateRef St, const StackFrame *SF, SymbolReaper &SymReaper);
616
617public:
618
620 return StoreMgr->ArrayToPointer(Array, ElementTy);
621 }
622
623 // Methods that manipulate the GDM.
624 ProgramStateRef addGDM(ProgramStateRef St, const void *Key, void *Data);
625 ProgramStateRef removeGDM(ProgramStateRef state, const void *Key);
626
627 // Methods that query & manipulate the Store.
628
630 StoreMgr->iterBindings(state->getStore(), F);
631 }
632
635 ProgramStateRef GDMState);
636
638 return ConstraintMgr->haveEqualConstraints(S1, S2);
639 }
640
642 return S1->Env == S2->Env;
643 }
644
646 return S1->store == S2->store;
647 }
648
649 //==---------------------------------------------------------------------==//
650 // Generic Data Map methods.
651 //==---------------------------------------------------------------------==//
652 //
653 // ProgramStateManager and ProgramState support a "generic data map" that allows
654 // different clients of ProgramState objects to embed arbitrary data within a
655 // ProgramState object. The generic data map is essentially an immutable map
656 // from a "tag" (that acts as the "key" for a client) and opaque values.
657 // Tags/keys and values are simply void* values. The typical way that clients
658 // generate unique tags are by taking the address of a static variable.
659 // Clients are responsible for ensuring that data values referred to by a
660 // the data pointer are immutable (and thus are essentially purely functional
661 // data).
662 //
663 // The templated methods below use the ProgramStateTrait<T> class
664 // to resolve keys into the GDM and to return data values to clients.
665 //
666
667 // Trait based GDM dispatch.
668 template <typename T>
673
674 template<typename T>
683
684 template <typename T>
691
692 template <typename T>
700
701 template <typename T>
705
706 void *FindGDMContext(const void *index,
707 void *(*CreateContext)(llvm::BumpPtrAllocator &),
708 void (*DeleteContext)(void *));
709
710 template <typename T>
718};
719
720
721//===----------------------------------------------------------------------===//
722// Out-of-line method definitions for ProgramState.
723//===----------------------------------------------------------------------===//
724
725inline void ProgramState::release() const {
726 assert(refCount > 0);
727 if (--refCount == 0)
728 stateMgr->freeState(const_cast<ProgramState *>(this));
729}
730
732 return stateMgr->getConstraintManager();
733}
734
736 const StackFrame *SF) const {
738}
739
741 bool Assumption) const {
742 if (Cond.isUnknown())
743 return this;
744
745 return getStateManager().ConstraintMgr
746 ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
747}
748
749inline std::pair<ProgramStateRef , ProgramStateRef >
751 if (Cond.isUnknown())
752 return std::make_pair(this, this);
753
754 return getStateManager().ConstraintMgr
755 ->assumeDual(this, Cond.castAs<DefinedSVal>());
756}
757
759 DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
760 bool Assumption) const {
761 if (Val.isUnknown())
762 return this;
763
764 assert(isa<NonLoc>(Val) && "Only NonLocs are supported!");
765
766 return getStateManager().ConstraintMgr->assumeInclusiveRange(
767 this, Val.castAs<NonLoc>(), From, To, Assumption);
768}
769
770inline std::pair<ProgramStateRef, ProgramStateRef>
772 const llvm::APSInt &From,
773 const llvm::APSInt &To) const {
774 if (Val.isUnknown())
775 return std::make_pair(this, this);
776
777 assert(isa<NonLoc>(Val) && "Only NonLocs are supported!");
778
779 return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
780 this, Val.castAs<NonLoc>(), From, To);
781}
782
784 const StackFrame *SF) const {
785 if (std::optional<Loc> L = LV.getAs<Loc>())
786 return bindLoc(*L, V, SF);
787 return this;
788}
789
791 const SubRegion *Super) const {
792 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
793 return loc::MemRegionVal(
794 getStateManager().getRegionManager().getCXXBaseObjectRegion(
795 Base, Super, BaseSpec.isVirtual()));
796}
797
799 const SubRegion *Super,
800 bool IsVirtual) const {
801 return loc::MemRegionVal(
802 getStateManager().getRegionManager().getCXXBaseObjectRegion(
803 BaseClass, Super, IsVirtual));
804}
805
807 const StackFrame *SF) const {
808 return getStateManager().StoreMgr->getLValueVar(VD, SF);
809}
810
812 const StackFrame *SF) const {
813 return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, SF);
814}
815
817 return getStateManager().StoreMgr->getLValueIvar(D, Base);
818}
819
820inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
821 if (std::optional<NonLoc> N = Idx.getAs<NonLoc>())
822 return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
823 return UnknownVal();
824}
825
826inline SVal ProgramState::getSVal(const Expr *E, const StackFrame *SF) const {
827 return Env.getSVal(EnvironmentEntry(E, SF), *getStateManager().svalBuilder);
828}
829
831 const StackFrame *SF) const {
832 QualType T = E->getType();
833 if (E->isGLValue() || Loc::isLocType(T) || T->isIntegralOrEnumerationType())
834 return getSVal(E, SF);
835 return UnknownVal();
836}
837
839 return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
840}
841
842inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
843 return getStateManager().StoreMgr->getBinding(getStore(),
845 T);
846}
847
851
855
856template<typename T>
860
861template <typename T>
865
866template<typename T>
870
871template<typename T>
876
877template <typename T>
879 return getStateManager().remove<T>(this);
880}
881
882template<typename T>
886
887template<typename T>
892
893template<typename T>
899
900template <typename CB>
902 CB cb(this);
903 scanReachableSymbols(val, cb);
904 return cb;
905}
906
907template <typename CB>
909 llvm::iterator_range<region_iterator> Reachable) const {
910 CB cb(this);
911 scanReachableSymbols(Reachable, cb);
912 return cb;
913}
914
915/// \class ScanReachableSymbols
916/// A utility class that visits the reachable symbols using a custom
917/// SymbolVisitor. Terminates recursive traversal when the visitor function
918/// returns false.
920 typedef llvm::DenseSet<const void*> VisitedItems;
921
922 VisitedItems visited;
923 ProgramStateRef state;
924 SymbolVisitor &visitor;
925public:
927 : state(std::move(st)), visitor(v) {}
928
930 bool scan(nonloc::CompoundVal val);
931 bool scan(SVal val);
932 bool scan(const MemRegion *R);
933 bool scan(const SymExpr *sym);
934};
935
936} // end ento namespace
937
938} // end clang namespace
939
940#endif
#define V(N, I)
llvm::APSInt APSInt
Definition Compiler.cpp:26
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::json::Array Array
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
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:3674
This represents one expression.
Definition Expr.h:114
bool isGLValue() const
Definition Expr.h:289
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3346
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3654
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
A (possibly-)qualified type.
Definition TypeBase.h:938
It represents a stack frame of the call stack.
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:934
Manages the lifetime of CallEvent objects.
Definition CallEvent.h:1335
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:151
An entry in the environment consists of a Stmt and an StackFrame.
Definition Environment.h:35
An immutable map from EnvironmentEntries to SVals.
Definition Environment.h:55
static bool isLocType(QualType T)
Definition SVals.h:265
const VarRegion * getVarRegion(const VarDecl *VD, const StackFrame *SF)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and StackFram...
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
ProgramStateRef remove(ProgramStateRef st)
const MemRegionManager & getRegionManager() const
bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) const
const ASTContext & getContext() const
ProgramStateRef getInitialState(const StackFrame *InitSF)
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
ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait< T >::data_type D)
ProgramStateRef removeDeadBindingsFromEnvironmentAndStore(ProgramStateRef St, const StackFrame *SF, SymbolReaper &SymReaper)
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)
void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler &F)
SVal ArrayToPointer(Loc Array, QualType ElementTy)
const ConstraintManager & getConstraintManager() const
llvm::BumpPtrAllocator & getAllocator()
BasicValueFactory & getBasicVals()
ProgramStateTrait< T >::context_type get_context()
ProgramStateRef getPersistentState(ProgramState &&Impl)
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 class ProgramStateManager
llvm::ImmutableMap< const void *, void * > GenericDataMap
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 StackFrame *SF) const
Initializes the region of memory represented by loc with an initial value.
ConstraintManager & getConstraintManager() const
Return the ConstraintManager.
LLVM_ATTRIBUTE_RETURNS_NONNULL const VarRegion * getRegion(const VarDecl *D, const StackFrame *SF) const
Utility method for getting regions.
ProgramStateRef invalidateRegions(ArrayRef< SVal > Values, ConstCFGElementRef Elem, unsigned BlockCount, const StackFrame *SF, bool CausesPointerEscape, InvalidatedSymbols *IS=nullptr, const CallEvent *Call=nullptr, RegionAndSymbolInvalidationTraits *ITraits=nullptr) const
ProgramStateRef add(typename ProgramStateTrait< T >::key_type K) const
void Profile(llvm::FoldingSetNodeID &ID) const
Profile - Used to profile the contents of this object for inclusion in a FoldingSet.
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.
ProgramStateRef bindLoc(Loc location, SVal V, const StackFrame *SF, bool notifyChanges=true) const
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.
ProgramStateRef BindExpr(const Expr *E, const StackFrame *SF, SVal V, bool Invalidate=true) const
Create a new state by binding the value V to the expression E in the state's environment.
ProgramStateRef bindDefaultZero(SVal loc, const StackFrame *SF) const
Performs C++ zero-initialization procedure on the region of memory represented by loc.
SVal getSVal(const Expr *E, const StackFrame *SF) const
Returns the SVal bound to the expression E in the state's environment.
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
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
ProgramStateTrait< T >::lookup_type get(typename ProgramStateTrait< T >::key_type key) const
SVal getSValAsScalarOrLoc(const Expr *E, const StackFrame *SF) const
ProgramStateRef invalidateRegions(ArrayRef< const MemRegion * > Regions, ConstCFGElementRef Elem, unsigned BlockCount, const StackFrame *SF, 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.
const MemRegion ** region_iterator
ProgramStateTrait< T >::context_type get_context() const
void printDOT(raw_ostream &Out, const StackFrame *SF=nullptr, unsigned int Space=0) const
SVal getSelfSVal(const StackFrame *SF) const
Return the value of 'self' if available in the given context.
void printJson(raw_ostream &Out, const StackFrame *SF=nullptr, const char *NL="\n", unsigned int Space=0, bool IsDot=false) 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
void *const * FindGDM(const void *K) const
ProgramStateRef remove() const
void setGDM(GenericDataMap gdm)
AnalysisManager & getAnalysisManager() const
ProgramStateRef enterStackFrame(const CallEvent &Call, const StackFrame *CalleeSF) const
enterStackFrame - Returns the state for entry to the given stack frame, preserving the current state.
SymbolManager & getSymbolManager() const
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1664
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
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:88
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
bool isUnknown() const
Definition SVals.h:111
ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
bool scan(nonloc::LazyCompoundVal val)
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:481
Symbolic value.
Definition SymExpr.h:33
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:342
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition SVals.h:392
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
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
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition CFG.h:1271
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
static void * MakeVoidPtr(data_type D)
static data_type MakeData(void *const *P)