1 //===- SymbolManager.h - Management of Symbolic Values ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines SymbolManager, a class that manages symbolic values
11 // created for use by ExprEngine and related classes.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SYMBOLMANAGER_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SYMBOLMANAGER_H
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Analysis/AnalysisDeclContext.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/FoldingSet.h"
28 #include "llvm/Support/Allocator.h"
38 class BasicValueFactory;
41 ///A symbol representing the value stored at a MemRegion.
42 class SymbolRegionValue : public SymbolData {
43 const TypedValueRegion *R;
46 SymbolRegionValue(SymbolID sym, const TypedValueRegion *r)
47 : SymbolData(SymbolRegionValueKind, sym), R(r) {
49 assert(isValidTypeForSymbol(r->getValueType()));
52 const TypedValueRegion* getRegion() const { return R; }
54 static void Profile(llvm::FoldingSetNodeID& profile, const TypedValueRegion* R) {
55 profile.AddInteger((unsigned) SymbolRegionValueKind);
56 profile.AddPointer(R);
59 void Profile(llvm::FoldingSetNodeID& profile) override {
63 void dumpToStream(raw_ostream &os) const override;
64 const MemRegion *getOriginRegion() const override { return getRegion(); }
66 QualType getType() const override;
68 // Implement isa<T> support.
69 static bool classof(const SymExpr *SE) {
70 return SE->getKind() == SymbolRegionValueKind;
74 /// A symbol representing the result of an expression in the case when we do
75 /// not know anything about what the expression is.
76 class SymbolConjured : public SymbolData {
80 const LocationContext *LCtx;
81 const void *SymbolTag;
84 SymbolConjured(SymbolID sym, const Stmt *s, const LocationContext *lctx,
85 QualType t, unsigned count, const void *symbolTag)
86 : SymbolData(SymbolConjuredKind, sym), S(s), T(t), Count(count),
87 LCtx(lctx), SymbolTag(symbolTag) {
88 // FIXME: 's' might be a nullptr if we're conducting invalidation
89 // that was caused by a destructor call on a temporary object,
90 // which has no statement associated with it.
91 // Due to this, we might be creating the same invalidation symbol for
92 // two different invalidation passes (for two different temporaries).
94 assert(isValidTypeForSymbol(t));
97 const Stmt *getStmt() const { return S; }
98 unsigned getCount() const { return Count; }
99 const void *getTag() const { return SymbolTag; }
101 QualType getType() const override;
103 void dumpToStream(raw_ostream &os) const override;
105 static void Profile(llvm::FoldingSetNodeID& profile, const Stmt *S,
106 QualType T, unsigned Count, const LocationContext *LCtx,
107 const void *SymbolTag) {
108 profile.AddInteger((unsigned) SymbolConjuredKind);
109 profile.AddPointer(S);
110 profile.AddPointer(LCtx);
112 profile.AddInteger(Count);
113 profile.AddPointer(SymbolTag);
116 void Profile(llvm::FoldingSetNodeID& profile) override {
117 Profile(profile, S, T, Count, LCtx, SymbolTag);
120 // Implement isa<T> support.
121 static bool classof(const SymExpr *SE) {
122 return SE->getKind() == SymbolConjuredKind;
126 /// A symbol representing the value of a MemRegion whose parent region has
128 class SymbolDerived : public SymbolData {
129 SymbolRef parentSymbol;
130 const TypedValueRegion *R;
133 SymbolDerived(SymbolID sym, SymbolRef parent, const TypedValueRegion *r)
134 : SymbolData(SymbolDerivedKind, sym), parentSymbol(parent), R(r) {
137 assert(isValidTypeForSymbol(r->getValueType()));
140 SymbolRef getParentSymbol() const { return parentSymbol; }
141 const TypedValueRegion *getRegion() const { return R; }
143 QualType getType() const override;
145 void dumpToStream(raw_ostream &os) const override;
146 const MemRegion *getOriginRegion() const override { return getRegion(); }
148 static void Profile(llvm::FoldingSetNodeID& profile, SymbolRef parent,
149 const TypedValueRegion *r) {
150 profile.AddInteger((unsigned) SymbolDerivedKind);
151 profile.AddPointer(r);
152 profile.AddPointer(parent);
155 void Profile(llvm::FoldingSetNodeID& profile) override {
156 Profile(profile, parentSymbol, R);
159 // Implement isa<T> support.
160 static bool classof(const SymExpr *SE) {
161 return SE->getKind() == SymbolDerivedKind;
165 /// SymbolExtent - Represents the extent (size in bytes) of a bounded region.
166 /// Clients should not ask the SymbolManager for a region's extent. Always use
167 /// SubRegion::getExtent instead -- the value returned may not be a symbol.
168 class SymbolExtent : public SymbolData {
172 SymbolExtent(SymbolID sym, const SubRegion *r)
173 : SymbolData(SymbolExtentKind, sym), R(r) {
177 const SubRegion *getRegion() const { return R; }
179 QualType getType() const override;
181 void dumpToStream(raw_ostream &os) const override;
183 static void Profile(llvm::FoldingSetNodeID& profile, const SubRegion *R) {
184 profile.AddInteger((unsigned) SymbolExtentKind);
185 profile.AddPointer(R);
188 void Profile(llvm::FoldingSetNodeID& profile) override {
192 // Implement isa<T> support.
193 static bool classof(const SymExpr *SE) {
194 return SE->getKind() == SymbolExtentKind;
198 /// SymbolMetadata - Represents path-dependent metadata about a specific region.
199 /// Metadata symbols remain live as long as they are marked as in use before
200 /// dead-symbol sweeping AND their associated regions are still alive.
201 /// Intended for use by checkers.
202 class SymbolMetadata : public SymbolData {
206 const LocationContext *LCtx;
211 SymbolMetadata(SymbolID sym, const MemRegion* r, const Stmt *s, QualType t,
212 const LocationContext *LCtx, unsigned count, const void *tag)
213 : SymbolData(SymbolMetadataKind, sym), R(r), S(s), T(t), LCtx(LCtx),
214 Count(count), Tag(tag) {
217 assert(isValidTypeForSymbol(t));
222 const MemRegion *getRegion() const { return R; }
223 const Stmt *getStmt() const { return S; }
224 const LocationContext *getLocationContext() const { return LCtx; }
225 unsigned getCount() const { return Count; }
226 const void *getTag() const { return Tag; }
228 QualType getType() const override;
230 void dumpToStream(raw_ostream &os) const override;
232 static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R,
233 const Stmt *S, QualType T, const LocationContext *LCtx,
234 unsigned Count, const void *Tag) {
235 profile.AddInteger((unsigned) SymbolMetadataKind);
236 profile.AddPointer(R);
237 profile.AddPointer(S);
239 profile.AddPointer(LCtx);
240 profile.AddInteger(Count);
241 profile.AddPointer(Tag);
244 void Profile(llvm::FoldingSetNodeID& profile) override {
245 Profile(profile, R, S, T, LCtx, Count, Tag);
248 // Implement isa<T> support.
249 static bool classof(const SymExpr *SE) {
250 return SE->getKind() == SymbolMetadataKind;
254 /// Represents a cast expression.
255 class SymbolCast : public SymExpr {
256 const SymExpr *Operand;
258 /// Type of the operand.
261 /// The type of the result.
265 SymbolCast(const SymExpr *In, QualType From, QualType To)
266 : SymExpr(SymbolCastKind), Operand(In), FromTy(From), ToTy(To) {
268 assert(isValidTypeForSymbol(From));
269 // FIXME: GenericTaintChecker creates symbols of void type.
270 // Otherwise, 'To' should also be a valid type.
273 unsigned computeComplexity() const override {
275 Complexity = 1 + Operand->computeComplexity();
279 QualType getType() const override { return ToTy; }
281 const SymExpr *getOperand() const { return Operand; }
283 void dumpToStream(raw_ostream &os) const override;
285 static void Profile(llvm::FoldingSetNodeID& ID,
286 const SymExpr *In, QualType From, QualType To) {
287 ID.AddInteger((unsigned) SymbolCastKind);
293 void Profile(llvm::FoldingSetNodeID& ID) override {
294 Profile(ID, Operand, FromTy, ToTy);
297 // Implement isa<T> support.
298 static bool classof(const SymExpr *SE) {
299 return SE->getKind() == SymbolCastKind;
303 /// Represents a symbolic expression involving a binary operator
304 class BinarySymExpr : public SymExpr {
305 BinaryOperator::Opcode Op;
309 BinarySymExpr(Kind k, BinaryOperator::Opcode op, QualType t)
310 : SymExpr(k), Op(op), T(t) {
311 assert(classof(this));
312 // Binary expressions are results of arithmetic. Pointer arithmetic is not
313 // handled by binary expressions, but it is instead handled by applying
314 // sub-regions to regions.
315 assert(isValidTypeForSymbol(t) && !Loc::isLocType(t));
319 // FIXME: We probably need to make this out-of-line to avoid redundant
320 // generation of virtual functions.
321 QualType getType() const override { return T; }
323 BinaryOperator::Opcode getOpcode() const { return Op; }
325 // Implement isa<T> support.
326 static bool classof(const SymExpr *SE) {
327 Kind k = SE->getKind();
328 return k >= BEGIN_BINARYSYMEXPRS && k <= END_BINARYSYMEXPRS;
332 /// Represents a symbolic expression like 'x' + 3.
333 class SymIntExpr : public BinarySymExpr {
335 const llvm::APSInt& RHS;
338 SymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op,
339 const llvm::APSInt &rhs, QualType t)
340 : BinarySymExpr(SymIntExprKind, op, t), LHS(lhs), RHS(rhs) {
344 void dumpToStream(raw_ostream &os) const override;
346 const SymExpr *getLHS() const { return LHS; }
347 const llvm::APSInt &getRHS() const { return RHS; }
349 unsigned computeComplexity() const override {
351 Complexity = 1 + LHS->computeComplexity();
355 static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs,
356 BinaryOperator::Opcode op, const llvm::APSInt& rhs,
358 ID.AddInteger((unsigned) SymIntExprKind);
365 void Profile(llvm::FoldingSetNodeID& ID) override {
366 Profile(ID, LHS, getOpcode(), RHS, getType());
369 // Implement isa<T> support.
370 static bool classof(const SymExpr *SE) {
371 return SE->getKind() == SymIntExprKind;
375 /// Represents a symbolic expression like 3 - 'x'.
376 class IntSymExpr : public BinarySymExpr {
377 const llvm::APSInt& LHS;
381 IntSymExpr(const llvm::APSInt &lhs, BinaryOperator::Opcode op,
382 const SymExpr *rhs, QualType t)
383 : BinarySymExpr(IntSymExprKind, op, t), LHS(lhs), RHS(rhs) {
387 void dumpToStream(raw_ostream &os) const override;
389 const SymExpr *getRHS() const { return RHS; }
390 const llvm::APSInt &getLHS() const { return LHS; }
392 unsigned computeComplexity() const override {
394 Complexity = 1 + RHS->computeComplexity();
398 static void Profile(llvm::FoldingSetNodeID& ID, const llvm::APSInt& lhs,
399 BinaryOperator::Opcode op, const SymExpr *rhs,
401 ID.AddInteger((unsigned) IntSymExprKind);
408 void Profile(llvm::FoldingSetNodeID& ID) override {
409 Profile(ID, LHS, getOpcode(), RHS, getType());
412 // Implement isa<T> support.
413 static bool classof(const SymExpr *SE) {
414 return SE->getKind() == IntSymExprKind;
418 /// Represents a symbolic expression like 'x' + 'y'.
419 class SymSymExpr : public BinarySymExpr {
424 SymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs,
426 : BinarySymExpr(SymSymExprKind, op, t), LHS(lhs), RHS(rhs) {
431 const SymExpr *getLHS() const { return LHS; }
432 const SymExpr *getRHS() const { return RHS; }
434 void dumpToStream(raw_ostream &os) const override;
436 unsigned computeComplexity() const override {
438 Complexity = RHS->computeComplexity() + LHS->computeComplexity();
442 static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs,
443 BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) {
444 ID.AddInteger((unsigned) SymSymExprKind);
451 void Profile(llvm::FoldingSetNodeID& ID) override {
452 Profile(ID, LHS, getOpcode(), RHS, getType());
455 // Implement isa<T> support.
456 static bool classof(const SymExpr *SE) {
457 return SE->getKind() == SymSymExprKind;
461 class SymbolManager {
462 using DataSetTy = llvm::FoldingSet<SymExpr>;
463 using SymbolDependTy = llvm::DenseMap<SymbolRef, SymbolRefSmallVectorTy *>;
467 /// Stores the extra dependencies between symbols: the data should be kept
468 /// alive as long as the key is live.
469 SymbolDependTy SymbolDependencies;
471 unsigned SymbolCounter = 0;
472 llvm::BumpPtrAllocator& BPAlloc;
473 BasicValueFactory &BV;
477 SymbolManager(ASTContext &ctx, BasicValueFactory &bv,
478 llvm::BumpPtrAllocator& bpalloc)
479 : SymbolDependencies(16), BPAlloc(bpalloc), BV(bv), Ctx(ctx) {}
482 static bool canSymbolicate(QualType T);
484 /// Make a unique symbol for MemRegion R according to its kind.
485 const SymbolRegionValue* getRegionValueSymbol(const TypedValueRegion* R);
487 const SymbolConjured* conjureSymbol(const Stmt *E,
488 const LocationContext *LCtx,
491 const void *SymbolTag = nullptr);
493 const SymbolConjured* conjureSymbol(const Expr *E,
494 const LocationContext *LCtx,
496 const void *SymbolTag = nullptr) {
497 return conjureSymbol(E, LCtx, E->getType(), VisitCount, SymbolTag);
500 const SymbolDerived *getDerivedSymbol(SymbolRef parentSymbol,
501 const TypedValueRegion *R);
503 const SymbolExtent *getExtentSymbol(const SubRegion *R);
505 /// Creates a metadata symbol associated with a specific region.
507 /// VisitCount can be used to differentiate regions corresponding to
508 /// different loop iterations, thus, making the symbol path-dependent.
509 const SymbolMetadata *getMetadataSymbol(const MemRegion *R, const Stmt *S,
511 const LocationContext *LCtx,
513 const void *SymbolTag = nullptr);
515 const SymbolCast* getCastSymbol(const SymExpr *Operand,
516 QualType From, QualType To);
518 const SymIntExpr *getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op,
519 const llvm::APSInt& rhs, QualType t);
521 const SymIntExpr *getSymIntExpr(const SymExpr &lhs, BinaryOperator::Opcode op,
522 const llvm::APSInt& rhs, QualType t) {
523 return getSymIntExpr(&lhs, op, rhs, t);
526 const IntSymExpr *getIntSymExpr(const llvm::APSInt& lhs,
527 BinaryOperator::Opcode op,
528 const SymExpr *rhs, QualType t);
530 const SymSymExpr *getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op,
531 const SymExpr *rhs, QualType t);
533 QualType getType(const SymExpr *SE) const {
534 return SE->getType();
537 /// Add artificial symbol dependency.
539 /// The dependent symbol should stay alive as long as the primary is alive.
540 void addSymbolDependency(const SymbolRef Primary, const SymbolRef Dependent);
542 const SymbolRefSmallVectorTy *getDependentSymbols(const SymbolRef Primary);
544 ASTContext &getContext() { return Ctx; }
545 BasicValueFactory &getBasicVals() { return BV; }
548 /// A class responsible for cleaning up unused symbols.
555 using SymbolSetTy = llvm::DenseSet<SymbolRef>;
556 using SymbolMapTy = llvm::DenseMap<SymbolRef, SymbolStatus>;
557 using RegionSetTy = llvm::DenseSet<const MemRegion *>;
559 SymbolMapTy TheLiving;
560 SymbolSetTy MetadataInUse;
562 RegionSetTy RegionRoots;
564 const StackFrameContext *LCtx;
566 SymbolManager& SymMgr;
567 StoreRef reapedStore;
568 llvm::DenseMap<const MemRegion *, unsigned> includedRegionCache;
571 /// Construct a reaper object, which removes everything which is not
572 /// live before we execute statement s in the given location context.
574 /// If the statement is NULL, everything is this and parent contexts is
576 /// If the stack frame context is NULL, everything on stack is considered
578 SymbolReaper(const StackFrameContext *Ctx, const Stmt *s,
579 SymbolManager &symmgr, StoreManager &storeMgr)
580 : LCtx(Ctx), Loc(s), SymMgr(symmgr), reapedStore(nullptr, storeMgr) {}
582 const LocationContext *getLocationContext() const { return LCtx; }
584 bool isLive(SymbolRef sym);
585 bool isLiveRegion(const MemRegion *region);
586 bool isLive(const Stmt *ExprVal, const LocationContext *LCtx) const;
587 bool isLive(const VarRegion *VR, bool includeStoreBindings = false) const;
589 /// Unconditionally marks a symbol as live.
591 /// This should never be
592 /// used by checkers, only by the state infrastructure such as the store and
593 /// environment. Checkers should instead use metadata symbols and markInUse.
594 void markLive(SymbolRef sym);
596 /// Marks a symbol as important to a checker.
598 /// For metadata symbols,
599 /// this will keep the symbol alive as long as its associated region is also
600 /// live. For other symbols, this has no effect; checkers are not permitted
601 /// to influence the life of other symbols. This should be used before any
602 /// symbol marking has occurred, i.e. in the MarkLiveSymbols callback.
603 void markInUse(SymbolRef sym);
605 using region_iterator = RegionSetTy::const_iterator;
607 region_iterator region_begin() const { return RegionRoots.begin(); }
608 region_iterator region_end() const { return RegionRoots.end(); }
610 /// Returns whether or not a symbol has been confirmed dead.
612 /// This should only be called once all marking of dead symbols has completed.
613 /// (For checkers, this means only in the checkDeadSymbols callback.)
614 bool isDead(SymbolRef sym) {
618 void markLive(const MemRegion *region);
619 void markElementIndicesLive(const MemRegion *region);
621 /// Set to the value of the symbolic store after
622 /// StoreManager::removeDeadBindings has been called.
623 void setReapedStore(StoreRef st) { reapedStore = st; }
626 /// Mark the symbols dependent on the input symbol as live.
627 void markDependentsLive(SymbolRef sym);
630 class SymbolVisitor {
632 ~SymbolVisitor() = default;
635 SymbolVisitor() = default;
636 SymbolVisitor(const SymbolVisitor &) = default;
637 SymbolVisitor(SymbolVisitor &&) {}
639 /// A visitor method invoked by ProgramStateManager::scanReachableSymbols.
641 /// The method returns \c true if symbols should continue be scanned and \c
643 virtual bool VisitSymbol(SymbolRef sym) = 0;
644 virtual bool VisitMemRegion(const MemRegion *) { return true; }
651 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SYMBOLMANAGER_H