• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SValBuilder.h - Construction of SVals from evaluating expressions -*- C++ -*-
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines SValBuilder, a class that defines the interface for
11 //  "symbolical evaluators" which construct an SVal from an expression.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALBUILDER_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALBUILDER_H
17 
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
25 
26 namespace clang {
27 
28 class CXXBoolLiteralExpr;
29 
30 namespace ento {
31 
32 class SValBuilder {
33   virtual void anchor();
34 protected:
35   ASTContext &Context;
36 
37   /// Manager of APSInt values.
38   BasicValueFactory BasicVals;
39 
40   /// Manages the creation of symbols.
41   SymbolManager SymMgr;
42 
43   /// Manages the creation of memory regions.
44   MemRegionManager MemMgr;
45 
46   ProgramStateManager &StateMgr;
47 
48   /// The scalar type to use for array indices.
49   const QualType ArrayIndexTy;
50 
51   /// The width of the scalar type used for array indices.
52   const unsigned ArrayIndexWidth;
53 
54   virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy) = 0;
55   virtual SVal evalCastFromLoc(Loc val, QualType castTy) = 0;
56 
57 public:
58   // FIXME: Make these protected again once RegionStoreManager correctly
59   // handles loads from different bound value types.
60   virtual SVal dispatchCast(SVal val, QualType castTy) = 0;
61 
62 public:
SValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)63   SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
64               ProgramStateManager &stateMgr)
65     : Context(context), BasicVals(context, alloc),
66       SymMgr(context, BasicVals, alloc),
67       MemMgr(context, alloc),
68       StateMgr(stateMgr),
69       ArrayIndexTy(context.LongLongTy),
70       ArrayIndexWidth(context.getTypeSize(ArrayIndexTy)) {}
71 
~SValBuilder()72   virtual ~SValBuilder() {}
73 
haveSameType(const SymExpr * Sym1,const SymExpr * Sym2)74   bool haveSameType(const SymExpr *Sym1, const SymExpr *Sym2) {
75     return haveSameType(Sym1->getType(), Sym2->getType());
76   }
77 
haveSameType(QualType Ty1,QualType Ty2)78   bool haveSameType(QualType Ty1, QualType Ty2) {
79     // FIXME: Remove the second disjunct when we support symbolic
80     // truncation/extension.
81     return (Context.getCanonicalType(Ty1) == Context.getCanonicalType(Ty2) ||
82             (Ty1->isIntegralOrEnumerationType() &&
83              Ty2->isIntegralOrEnumerationType()));
84   }
85 
86   SVal evalCast(SVal val, QualType castTy, QualType originalType);
87 
88   // Handles casts of type CK_IntegralCast.
89   SVal evalIntegralCast(ProgramStateRef state, SVal val, QualType castTy,
90                         QualType originalType);
91 
92   virtual SVal evalMinus(NonLoc val) = 0;
93 
94   virtual SVal evalComplement(NonLoc val) = 0;
95 
96   /// Create a new value which represents a binary expression with two non-
97   /// location operands.
98   virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
99                            NonLoc lhs, NonLoc rhs, QualType resultTy) = 0;
100 
101   /// Create a new value which represents a binary expression with two memory
102   /// location operands.
103   virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
104                            Loc lhs, Loc rhs, QualType resultTy) = 0;
105 
106   /// Create a new value which represents a binary expression with a memory
107   /// location and non-location operands. For example, this would be used to
108   /// evaluate a pointer arithmetic operation.
109   virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
110                            Loc lhs, NonLoc rhs, QualType resultTy) = 0;
111 
112   /// Evaluates a given SVal. If the SVal has only one possible (integer) value,
113   /// that value is returned. Otherwise, returns NULL.
114   virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal val) = 0;
115 
116   /// Constructs a symbolic expression for two non-location values.
117   SVal makeSymExprValNN(ProgramStateRef state, BinaryOperator::Opcode op,
118                       NonLoc lhs, NonLoc rhs, QualType resultTy);
119 
120   SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
121                  SVal lhs, SVal rhs, QualType type);
122 
123   DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal lhs,
124                               DefinedOrUnknownSVal rhs);
125 
getContext()126   ASTContext &getContext() { return Context; }
getContext()127   const ASTContext &getContext() const { return Context; }
128 
getStateManager()129   ProgramStateManager &getStateManager() { return StateMgr; }
130 
getConditionType()131   QualType getConditionType() const {
132     return Context.getLangOpts().CPlusPlus ? Context.BoolTy : Context.IntTy;
133   }
134 
getArrayIndexType()135   QualType getArrayIndexType() const {
136     return ArrayIndexTy;
137   }
138 
getBasicValueFactory()139   BasicValueFactory &getBasicValueFactory() { return BasicVals; }
getBasicValueFactory()140   const BasicValueFactory &getBasicValueFactory() const { return BasicVals; }
141 
getSymbolManager()142   SymbolManager &getSymbolManager() { return SymMgr; }
getSymbolManager()143   const SymbolManager &getSymbolManager() const { return SymMgr; }
144 
getRegionManager()145   MemRegionManager &getRegionManager() { return MemMgr; }
getRegionManager()146   const MemRegionManager &getRegionManager() const { return MemMgr; }
147 
148   // Forwarding methods to SymbolManager.
149 
150   const SymbolConjured* conjureSymbol(const Stmt *stmt,
151                                       const LocationContext *LCtx,
152                                       QualType type,
153                                       unsigned visitCount,
154                                       const void *symbolTag = nullptr) {
155     return SymMgr.conjureSymbol(stmt, LCtx, type, visitCount, symbolTag);
156   }
157 
158   const SymbolConjured* conjureSymbol(const Expr *expr,
159                                       const LocationContext *LCtx,
160                                       unsigned visitCount,
161                                       const void *symbolTag = nullptr) {
162     return SymMgr.conjureSymbol(expr, LCtx, visitCount, symbolTag);
163   }
164 
165   /// Construct an SVal representing '0' for the specified type.
166   DefinedOrUnknownSVal makeZeroVal(QualType type);
167 
168   /// Make a unique symbol for value of region.
169   DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *region);
170 
171   /// \brief Create a new symbol with a unique 'name'.
172   ///
173   /// We resort to conjured symbols when we cannot construct a derived symbol.
174   /// The advantage of symbols derived/built from other symbols is that we
175   /// preserve the relation between related(or even equivalent) expressions, so
176   /// conjured symbols should be used sparingly.
177   DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag,
178                                         const Expr *expr,
179                                         const LocationContext *LCtx,
180                                         unsigned count);
181   DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag,
182                                         const Expr *expr,
183                                         const LocationContext *LCtx,
184                                         QualType type,
185                                         unsigned count);
186 
187   DefinedOrUnknownSVal conjureSymbolVal(const Stmt *stmt,
188                                         const LocationContext *LCtx,
189                                         QualType type,
190                                         unsigned visitCount);
191   /// \brief Conjure a symbol representing heap allocated memory region.
192   ///
193   /// Note, the expression should represent a location.
194   DefinedOrUnknownSVal getConjuredHeapSymbolVal(const Expr *E,
195                                                 const LocationContext *LCtx,
196                                                 unsigned Count);
197 
198   DefinedOrUnknownSVal getDerivedRegionValueSymbolVal(
199       SymbolRef parentSymbol, const TypedValueRegion *region);
200 
201   DefinedSVal getMetadataSymbolVal(
202       const void *symbolTag, const MemRegion *region,
203       const Expr *expr, QualType type, unsigned count);
204 
205   DefinedSVal getFunctionPointer(const FunctionDecl *func);
206 
207   DefinedSVal getBlockPointer(const BlockDecl *block, CanQualType locTy,
208                               const LocationContext *locContext,
209                               unsigned blockCount);
210 
211   /// Returns the value of \p E, if it can be determined in a non-path-sensitive
212   /// manner.
213   ///
214   /// If \p E is not a constant or cannot be modeled, returns \c None.
215   Optional<SVal> getConstantVal(const Expr *E);
216 
makeCompoundVal(QualType type,llvm::ImmutableList<SVal> vals)217   NonLoc makeCompoundVal(QualType type, llvm::ImmutableList<SVal> vals) {
218     return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals));
219   }
220 
makeLazyCompoundVal(const StoreRef & store,const TypedValueRegion * region)221   NonLoc makeLazyCompoundVal(const StoreRef &store,
222                              const TypedValueRegion *region) {
223     return nonloc::LazyCompoundVal(
224         BasicVals.getLazyCompoundValData(store, region));
225   }
226 
makeZeroArrayIndex()227   NonLoc makeZeroArrayIndex() {
228     return nonloc::ConcreteInt(BasicVals.getValue(0, ArrayIndexTy));
229   }
230 
makeArrayIndex(uint64_t idx)231   NonLoc makeArrayIndex(uint64_t idx) {
232     return nonloc::ConcreteInt(BasicVals.getValue(idx, ArrayIndexTy));
233   }
234 
235   SVal convertToArrayIndex(SVal val);
236 
makeIntVal(const IntegerLiteral * integer)237   nonloc::ConcreteInt makeIntVal(const IntegerLiteral* integer) {
238     return nonloc::ConcreteInt(
239         BasicVals.getValue(integer->getValue(),
240                      integer->getType()->isUnsignedIntegerOrEnumerationType()));
241   }
242 
makeBoolVal(const ObjCBoolLiteralExpr * boolean)243   nonloc::ConcreteInt makeBoolVal(const ObjCBoolLiteralExpr *boolean) {
244     return makeTruthVal(boolean->getValue(), boolean->getType());
245   }
246 
247   nonloc::ConcreteInt makeBoolVal(const CXXBoolLiteralExpr *boolean);
248 
makeIntVal(const llvm::APSInt & integer)249   nonloc::ConcreteInt makeIntVal(const llvm::APSInt& integer) {
250     return nonloc::ConcreteInt(BasicVals.getValue(integer));
251   }
252 
makeIntLocVal(const llvm::APSInt & integer)253   loc::ConcreteInt makeIntLocVal(const llvm::APSInt &integer) {
254     return loc::ConcreteInt(BasicVals.getValue(integer));
255   }
256 
makeIntVal(const llvm::APInt & integer,bool isUnsigned)257   NonLoc makeIntVal(const llvm::APInt& integer, bool isUnsigned) {
258     return nonloc::ConcreteInt(BasicVals.getValue(integer, isUnsigned));
259   }
260 
makeIntVal(uint64_t integer,QualType type)261   DefinedSVal makeIntVal(uint64_t integer, QualType type) {
262     if (Loc::isLocType(type))
263       return loc::ConcreteInt(BasicVals.getValue(integer, type));
264 
265     return nonloc::ConcreteInt(BasicVals.getValue(integer, type));
266   }
267 
makeIntVal(uint64_t integer,bool isUnsigned)268   NonLoc makeIntVal(uint64_t integer, bool isUnsigned) {
269     return nonloc::ConcreteInt(BasicVals.getIntValue(integer, isUnsigned));
270   }
271 
makeIntValWithPtrWidth(uint64_t integer,bool isUnsigned)272   NonLoc makeIntValWithPtrWidth(uint64_t integer, bool isUnsigned) {
273     return nonloc::ConcreteInt(
274         BasicVals.getIntWithPtrWidth(integer, isUnsigned));
275   }
276 
makeLocAsInteger(Loc loc,unsigned bits)277   NonLoc makeLocAsInteger(Loc loc, unsigned bits) {
278     return nonloc::LocAsInteger(BasicVals.getPersistentSValWithData(loc, bits));
279   }
280 
281   NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
282                     const llvm::APSInt& rhs, QualType type);
283 
284   NonLoc makeNonLoc(const llvm::APSInt& rhs, BinaryOperator::Opcode op,
285                     const SymExpr *lhs, QualType type);
286 
287   NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
288                     const SymExpr *rhs, QualType type);
289 
290   /// \brief Create a NonLoc value for cast.
291   NonLoc makeNonLoc(const SymExpr *operand, QualType fromTy, QualType toTy);
292 
makeTruthVal(bool b,QualType type)293   nonloc::ConcreteInt makeTruthVal(bool b, QualType type) {
294     return nonloc::ConcreteInt(BasicVals.getTruthValue(b, type));
295   }
296 
makeTruthVal(bool b)297   nonloc::ConcreteInt makeTruthVal(bool b) {
298     return nonloc::ConcreteInt(BasicVals.getTruthValue(b));
299   }
300 
makeNull()301   Loc makeNull() {
302     return loc::ConcreteInt(BasicVals.getZeroWithPtrWidth());
303   }
304 
makeLoc(SymbolRef sym)305   Loc makeLoc(SymbolRef sym) {
306     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
307   }
308 
makeLoc(const MemRegion * region)309   Loc makeLoc(const MemRegion* region) {
310     return loc::MemRegionVal(region);
311   }
312 
makeLoc(const AddrLabelExpr * expr)313   Loc makeLoc(const AddrLabelExpr *expr) {
314     return loc::GotoLabel(expr->getLabel());
315   }
316 
makeLoc(const llvm::APSInt & integer)317   Loc makeLoc(const llvm::APSInt& integer) {
318     return loc::ConcreteInt(BasicVals.getValue(integer));
319   }
320 
321   /// Return a memory region for the 'this' object reference.
322   loc::MemRegionVal getCXXThis(const CXXMethodDecl *D,
323                                const StackFrameContext *SFC);
324 
325   /// Return a memory region for the 'this' object reference.
326   loc::MemRegionVal getCXXThis(const CXXRecordDecl *D,
327                                const StackFrameContext *SFC);
328 };
329 
330 SValBuilder* createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
331                                      ASTContext &context,
332                                      ProgramStateManager &stateMgr);
333 
334 } // end GR namespace
335 
336 } // end clang namespace
337 
338 #endif
339