Home | History | Annotate | Download | only in PathSensitive
      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:
     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 
     72   virtual ~SValBuilder() {}
     73 
     74   bool haveSameType(const SymExpr *Sym1, const SymExpr *Sym2) {
     75     return haveSameType(Sym1->getType(), Sym2->getType());
     76   }
     77 
     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   /// Simplify symbolic expressions within a given SVal. Return an SVal
    117   /// that represents the same value, but is hopefully easier to work with
    118   /// than the original SVal.
    119   virtual SVal simplifySVal(ProgramStateRef State, SVal Val) = 0;
    120 
    121   /// Constructs a symbolic expression for two non-location values.
    122   SVal makeSymExprValNN(ProgramStateRef state, BinaryOperator::Opcode op,
    123                       NonLoc lhs, NonLoc rhs, QualType resultTy);
    124 
    125   SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
    126                  SVal lhs, SVal rhs, QualType type);
    127 
    128   DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal lhs,
    129                               DefinedOrUnknownSVal rhs);
    130 
    131   ASTContext &getContext() { return Context; }
    132   const ASTContext &getContext() const { return Context; }
    133 
    134   ProgramStateManager &getStateManager() { return StateMgr; }
    135 
    136   QualType getConditionType() const {
    137     return Context.getLangOpts().CPlusPlus ? Context.BoolTy : Context.IntTy;
    138   }
    139 
    140   QualType getArrayIndexType() const {
    141     return ArrayIndexTy;
    142   }
    143 
    144   BasicValueFactory &getBasicValueFactory() { return BasicVals; }
    145   const BasicValueFactory &getBasicValueFactory() const { return BasicVals; }
    146 
    147   SymbolManager &getSymbolManager() { return SymMgr; }
    148   const SymbolManager &getSymbolManager() const { return SymMgr; }
    149 
    150   MemRegionManager &getRegionManager() { return MemMgr; }
    151   const MemRegionManager &getRegionManager() const { return MemMgr; }
    152 
    153   // Forwarding methods to SymbolManager.
    154 
    155   const SymbolConjured* conjureSymbol(const Stmt *stmt,
    156                                       const LocationContext *LCtx,
    157                                       QualType type,
    158                                       unsigned visitCount,
    159                                       const void *symbolTag = nullptr) {
    160     return SymMgr.conjureSymbol(stmt, LCtx, type, visitCount, symbolTag);
    161   }
    162 
    163   const SymbolConjured* conjureSymbol(const Expr *expr,
    164                                       const LocationContext *LCtx,
    165                                       unsigned visitCount,
    166                                       const void *symbolTag = nullptr) {
    167     return SymMgr.conjureSymbol(expr, LCtx, visitCount, symbolTag);
    168   }
    169 
    170   /// Construct an SVal representing '0' for the specified type.
    171   DefinedOrUnknownSVal makeZeroVal(QualType type);
    172 
    173   /// Make a unique symbol for value of region.
    174   DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *region);
    175 
    176   /// \brief Create a new symbol with a unique 'name'.
    177   ///
    178   /// We resort to conjured symbols when we cannot construct a derived symbol.
    179   /// The advantage of symbols derived/built from other symbols is that we
    180   /// preserve the relation between related(or even equivalent) expressions, so
    181   /// conjured symbols should be used sparingly.
    182   DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag,
    183                                         const Expr *expr,
    184                                         const LocationContext *LCtx,
    185                                         unsigned count);
    186   DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag,
    187                                         const Expr *expr,
    188                                         const LocationContext *LCtx,
    189                                         QualType type,
    190                                         unsigned count);
    191 
    192   DefinedOrUnknownSVal conjureSymbolVal(const Stmt *stmt,
    193                                         const LocationContext *LCtx,
    194                                         QualType type,
    195                                         unsigned visitCount);
    196   /// \brief Conjure a symbol representing heap allocated memory region.
    197   ///
    198   /// Note, the expression should represent a location.
    199   DefinedOrUnknownSVal getConjuredHeapSymbolVal(const Expr *E,
    200                                                 const LocationContext *LCtx,
    201                                                 unsigned Count);
    202 
    203   DefinedOrUnknownSVal getDerivedRegionValueSymbolVal(
    204       SymbolRef parentSymbol, const TypedValueRegion *region);
    205 
    206   DefinedSVal getMetadataSymbolVal(const void *symbolTag,
    207                                    const MemRegion *region,
    208                                    const Expr *expr, QualType type,
    209                                    const LocationContext *LCtx,
    210                                    unsigned count);
    211 
    212   DefinedSVal getMemberPointer(const DeclaratorDecl *DD);
    213 
    214   DefinedSVal getFunctionPointer(const FunctionDecl *func);
    215 
    216   DefinedSVal getBlockPointer(const BlockDecl *block, CanQualType locTy,
    217                               const LocationContext *locContext,
    218                               unsigned blockCount);
    219 
    220   /// Returns the value of \p E, if it can be determined in a non-path-sensitive
    221   /// manner.
    222   ///
    223   /// If \p E is not a constant or cannot be modeled, returns \c None.
    224   Optional<SVal> getConstantVal(const Expr *E);
    225 
    226   NonLoc makeCompoundVal(QualType type, llvm::ImmutableList<SVal> vals) {
    227     return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals));
    228   }
    229 
    230   NonLoc makeLazyCompoundVal(const StoreRef &store,
    231                              const TypedValueRegion *region) {
    232     return nonloc::LazyCompoundVal(
    233         BasicVals.getLazyCompoundValData(store, region));
    234   }
    235 
    236   NonLoc makePointerToMember(const DeclaratorDecl *DD) {
    237     return nonloc::PointerToMember(DD);
    238   }
    239 
    240   NonLoc makePointerToMember(const PointerToMemberData *PTMD) {
    241     return nonloc::PointerToMember(PTMD);
    242   }
    243 
    244   NonLoc makeZeroArrayIndex() {
    245     return nonloc::ConcreteInt(BasicVals.getValue(0, ArrayIndexTy));
    246   }
    247 
    248   NonLoc makeArrayIndex(uint64_t idx) {
    249     return nonloc::ConcreteInt(BasicVals.getValue(idx, ArrayIndexTy));
    250   }
    251 
    252   SVal convertToArrayIndex(SVal val);
    253 
    254   nonloc::ConcreteInt makeIntVal(const IntegerLiteral* integer) {
    255     return nonloc::ConcreteInt(
    256         BasicVals.getValue(integer->getValue(),
    257                      integer->getType()->isUnsignedIntegerOrEnumerationType()));
    258   }
    259 
    260   nonloc::ConcreteInt makeBoolVal(const ObjCBoolLiteralExpr *boolean) {
    261     return makeTruthVal(boolean->getValue(), boolean->getType());
    262   }
    263 
    264   nonloc::ConcreteInt makeBoolVal(const CXXBoolLiteralExpr *boolean);
    265 
    266   nonloc::ConcreteInt makeIntVal(const llvm::APSInt& integer) {
    267     return nonloc::ConcreteInt(BasicVals.getValue(integer));
    268   }
    269 
    270   loc::ConcreteInt makeIntLocVal(const llvm::APSInt &integer) {
    271     return loc::ConcreteInt(BasicVals.getValue(integer));
    272   }
    273 
    274   NonLoc makeIntVal(const llvm::APInt& integer, bool isUnsigned) {
    275     return nonloc::ConcreteInt(BasicVals.getValue(integer, isUnsigned));
    276   }
    277 
    278   DefinedSVal makeIntVal(uint64_t integer, QualType type) {
    279     if (Loc::isLocType(type))
    280       return loc::ConcreteInt(BasicVals.getValue(integer, type));
    281 
    282     return nonloc::ConcreteInt(BasicVals.getValue(integer, type));
    283   }
    284 
    285   NonLoc makeIntVal(uint64_t integer, bool isUnsigned) {
    286     return nonloc::ConcreteInt(BasicVals.getIntValue(integer, isUnsigned));
    287   }
    288 
    289   NonLoc makeIntValWithPtrWidth(uint64_t integer, bool isUnsigned) {
    290     return nonloc::ConcreteInt(
    291         BasicVals.getIntWithPtrWidth(integer, isUnsigned));
    292   }
    293 
    294   NonLoc makeLocAsInteger(Loc loc, unsigned bits) {
    295     return nonloc::LocAsInteger(BasicVals.getPersistentSValWithData(loc, bits));
    296   }
    297 
    298   NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
    299                     const llvm::APSInt& rhs, QualType type);
    300 
    301   NonLoc makeNonLoc(const llvm::APSInt& rhs, BinaryOperator::Opcode op,
    302                     const SymExpr *lhs, QualType type);
    303 
    304   NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
    305                     const SymExpr *rhs, QualType type);
    306 
    307   /// \brief Create a NonLoc value for cast.
    308   NonLoc makeNonLoc(const SymExpr *operand, QualType fromTy, QualType toTy);
    309 
    310   nonloc::ConcreteInt makeTruthVal(bool b, QualType type) {
    311     return nonloc::ConcreteInt(BasicVals.getTruthValue(b, type));
    312   }
    313 
    314   nonloc::ConcreteInt makeTruthVal(bool b) {
    315     return nonloc::ConcreteInt(BasicVals.getTruthValue(b));
    316   }
    317 
    318   /// Create NULL pointer, with proper pointer bit-width for given address
    319   /// space.
    320   /// \param type pointer type.
    321   Loc makeNullWithType(QualType type) {
    322     return loc::ConcreteInt(BasicVals.getZeroWithTypeSize(type));
    323   }
    324 
    325   Loc makeNull() {
    326     return loc::ConcreteInt(BasicVals.getZeroWithPtrWidth());
    327   }
    328 
    329   Loc makeLoc(SymbolRef sym) {
    330     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
    331   }
    332 
    333   Loc makeLoc(const MemRegion* region) {
    334     return loc::MemRegionVal(region);
    335   }
    336 
    337   Loc makeLoc(const AddrLabelExpr *expr) {
    338     return loc::GotoLabel(expr->getLabel());
    339   }
    340 
    341   Loc makeLoc(const llvm::APSInt& integer) {
    342     return loc::ConcreteInt(BasicVals.getValue(integer));
    343   }
    344 
    345   /// Return a memory region for the 'this' object reference.
    346   loc::MemRegionVal getCXXThis(const CXXMethodDecl *D,
    347                                const StackFrameContext *SFC);
    348 
    349   /// Return a memory region for the 'this' object reference.
    350   loc::MemRegionVal getCXXThis(const CXXRecordDecl *D,
    351                                const StackFrameContext *SFC);
    352 };
    353 
    354 SValBuilder* createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
    355                                      ASTContext &context,
    356                                      ProgramStateManager &stateMgr);
    357 
    358 } // end GR namespace
    359 
    360 } // end clang namespace
    361 
    362 #endif
    363