Home | History | Annotate | Download | only in Core
      1 //===- Calls.cpp - Wrapper for all function and method calls ------*- 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 /// \file This file defines CallEvent and its subclasses, which represent path-
     11 /// sensitive instances of different kinds of function and method calls
     12 /// (C, C++, and Objective-C).
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
     17 #include "clang/Analysis/ProgramPoint.h"
     18 #include "clang/AST/ParentMap.h"
     19 #include "llvm/ADT/SmallSet.h"
     20 #include "llvm/ADT/StringExtras.h"
     21 
     22 using namespace clang;
     23 using namespace ento;
     24 
     25 QualType CallEvent::getResultType() const {
     26   const Expr *E = getOriginExpr();
     27   assert(E && "Calls without origin expressions do not have results");
     28   QualType ResultTy = E->getType();
     29 
     30   ASTContext &Ctx = getState()->getStateManager().getContext();
     31 
     32   // A function that returns a reference to 'int' will have a result type
     33   // of simply 'int'. Check the origin expr's value kind to recover the
     34   // proper type.
     35   switch (E->getValueKind()) {
     36   case VK_LValue:
     37     ResultTy = Ctx.getLValueReferenceType(ResultTy);
     38     break;
     39   case VK_XValue:
     40     ResultTy = Ctx.getRValueReferenceType(ResultTy);
     41     break;
     42   case VK_RValue:
     43     // No adjustment is necessary.
     44     break;
     45   }
     46 
     47   return ResultTy;
     48 }
     49 
     50 static bool isCallbackArg(SVal V, QualType T) {
     51   // If the parameter is 0, it's harmless.
     52   if (V.isZeroConstant())
     53     return false;
     54 
     55   // If a parameter is a block or a callback, assume it can modify pointer.
     56   if (T->isBlockPointerType() ||
     57       T->isFunctionPointerType() ||
     58       T->isObjCSelType())
     59     return true;
     60 
     61   // Check if a callback is passed inside a struct (for both, struct passed by
     62   // reference and by value). Dig just one level into the struct for now.
     63 
     64   if (T->isAnyPointerType() || T->isReferenceType())
     65     T = T->getPointeeType();
     66 
     67   if (const RecordType *RT = T->getAsStructureType()) {
     68     const RecordDecl *RD = RT->getDecl();
     69     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
     70          I != E; ++I) {
     71       QualType FieldT = I->getType();
     72       if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
     73         return true;
     74     }
     75   }
     76 
     77   return false;
     78 }
     79 
     80 bool CallEvent::hasNonZeroCallbackArg() const {
     81   unsigned NumOfArgs = getNumArgs();
     82 
     83   // If calling using a function pointer, assume the function does not
     84   // have a callback. TODO: We could check the types of the arguments here.
     85   if (!getDecl())
     86     return false;
     87 
     88   unsigned Idx = 0;
     89   for (CallEvent::param_type_iterator I = param_type_begin(),
     90                                        E = param_type_end();
     91        I != E && Idx < NumOfArgs; ++I, ++Idx) {
     92     if (NumOfArgs <= Idx)
     93       break;
     94 
     95     if (isCallbackArg(getArgSVal(Idx), *I))
     96       return true;
     97   }
     98 
     99   return false;
    100 }
    101 
    102 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
    103 /// with no further indirection.
    104 static bool isPointerToConst(QualType Ty) {
    105   QualType PointeeTy = Ty->getPointeeType();
    106   if (PointeeTy == QualType())
    107     return false;
    108   if (!PointeeTy.isConstQualified())
    109     return false;
    110   if (PointeeTy->isAnyPointerType())
    111     return false;
    112   return true;
    113 }
    114 
    115 // Try to retrieve the function declaration and find the function parameter
    116 // types which are pointers/references to a non-pointer const.
    117 // We will not invalidate the corresponding argument regions.
    118 static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
    119                                  const CallEvent &Call) {
    120   unsigned Idx = 0;
    121   for (CallEvent::param_type_iterator I = Call.param_type_begin(),
    122                                       E = Call.param_type_end();
    123        I != E; ++I, ++Idx) {
    124     if (isPointerToConst(*I))
    125       PreserveArgs.insert(Idx);
    126   }
    127 }
    128 
    129 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
    130                                               ProgramStateRef Orig) const {
    131   ProgramStateRef Result = (Orig ? Orig : getState());
    132 
    133   SmallVector<const MemRegion *, 8> RegionsToInvalidate;
    134   getExtraInvalidatedRegions(RegionsToInvalidate);
    135 
    136   // Indexes of arguments whose values will be preserved by the call.
    137   llvm::SmallSet<unsigned, 1> PreserveArgs;
    138   if (!argumentsMayEscape())
    139     findPtrToConstParams(PreserveArgs, *this);
    140 
    141   for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
    142     if (PreserveArgs.count(Idx))
    143       continue;
    144 
    145     SVal V = getArgSVal(Idx);
    146 
    147     // If we are passing a location wrapped as an integer, unwrap it and
    148     // invalidate the values referred by the location.
    149     if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
    150       V = Wrapped->getLoc();
    151     else if (!isa<Loc>(V))
    152       continue;
    153 
    154     if (const MemRegion *R = V.getAsRegion()) {
    155       // Invalidate the value of the variable passed by reference.
    156 
    157       // Are we dealing with an ElementRegion?  If the element type is
    158       // a basic integer type (e.g., char, int) and the underlying region
    159       // is a variable region then strip off the ElementRegion.
    160       // FIXME: We really need to think about this for the general case
    161       //   as sometimes we are reasoning about arrays and other times
    162       //   about (char*), etc., is just a form of passing raw bytes.
    163       //   e.g., void *p = alloca(); foo((char*)p);
    164       if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
    165         // Checking for 'integral type' is probably too promiscuous, but
    166         // we'll leave it in for now until we have a systematic way of
    167         // handling all of these cases.  Eventually we need to come up
    168         // with an interface to StoreManager so that this logic can be
    169         // appropriately delegated to the respective StoreManagers while
    170         // still allowing us to do checker-specific logic (e.g.,
    171         // invalidating reference counts), probably via callbacks.
    172         if (ER->getElementType()->isIntegralOrEnumerationType()) {
    173           const MemRegion *superReg = ER->getSuperRegion();
    174           if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
    175               isa<ObjCIvarRegion>(superReg))
    176             R = cast<TypedRegion>(superReg);
    177         }
    178         // FIXME: What about layers of ElementRegions?
    179       }
    180 
    181       // Mark this region for invalidation.  We batch invalidate regions
    182       // below for efficiency.
    183       RegionsToInvalidate.push_back(R);
    184     }
    185   }
    186 
    187   // Invalidate designated regions using the batch invalidation API.
    188   // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
    189   //  global variables.
    190   return Result->invalidateRegions(RegionsToInvalidate, getOriginExpr(),
    191                                    BlockCount, getLocationContext(),
    192                                    /*Symbols=*/0, this);
    193 }
    194 
    195 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
    196                                         const ProgramPointTag *Tag) const {
    197   if (const Expr *E = getOriginExpr()) {
    198     if (IsPreVisit)
    199       return PreStmt(E, getLocationContext(), Tag);
    200     return PostStmt(E, getLocationContext(), Tag);
    201   }
    202 
    203   const Decl *D = getDecl();
    204   assert(D && "Cannot get a program point without a statement or decl");
    205 
    206   SourceLocation Loc = getSourceRange().getBegin();
    207   if (IsPreVisit)
    208     return PreImplicitCall(D, Loc, getLocationContext(), Tag);
    209   return PostImplicitCall(D, Loc, getLocationContext(), Tag);
    210 }
    211 
    212 SVal CallEvent::getArgSVal(unsigned Index) const {
    213   const Expr *ArgE = getArgExpr(Index);
    214   if (!ArgE)
    215     return UnknownVal();
    216   return getSVal(ArgE);
    217 }
    218 
    219 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
    220   const Expr *ArgE = getArgExpr(Index);
    221   if (!ArgE)
    222     return SourceRange();
    223   return ArgE->getSourceRange();
    224 }
    225 
    226 void CallEvent::dump() const {
    227   dump(llvm::errs());
    228 }
    229 
    230 void CallEvent::dump(raw_ostream &Out) const {
    231   ASTContext &Ctx = getState()->getStateManager().getContext();
    232   if (const Expr *E = getOriginExpr()) {
    233     E->printPretty(Out, 0, Ctx.getPrintingPolicy());
    234     Out << "\n";
    235     return;
    236   }
    237 
    238   if (const Decl *D = getDecl()) {
    239     Out << "Call to ";
    240     D->print(Out, Ctx.getPrintingPolicy());
    241     return;
    242   }
    243 
    244   // FIXME: a string representation of the kind would be nice.
    245   Out << "Unknown call (type " << getKind() << ")";
    246 }
    247 
    248 
    249 bool CallEvent::isCallStmt(const Stmt *S) {
    250   return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
    251                           || isa<CXXConstructExpr>(S)
    252                           || isa<CXXNewExpr>(S);
    253 }
    254 
    255 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
    256                                          CallEvent::BindingsTy &Bindings,
    257                                          SValBuilder &SVB,
    258                                          const CallEvent &Call,
    259                                          CallEvent::param_iterator I,
    260                                          CallEvent::param_iterator E) {
    261   MemRegionManager &MRMgr = SVB.getRegionManager();
    262 
    263   unsigned Idx = 0;
    264   for (; I != E; ++I, ++Idx) {
    265     const ParmVarDecl *ParamDecl = *I;
    266     assert(ParamDecl && "Formal parameter has no decl?");
    267 
    268     SVal ArgVal = Call.getArgSVal(Idx);
    269     if (!ArgVal.isUnknown()) {
    270       Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
    271       Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
    272     }
    273   }
    274 
    275   // FIXME: Variadic arguments are not handled at all right now.
    276 }
    277 
    278 
    279 CallEvent::param_iterator AnyFunctionCall::param_begin() const {
    280   const FunctionDecl *D = getDecl();
    281   if (!D)
    282     return 0;
    283 
    284   return D->param_begin();
    285 }
    286 
    287 CallEvent::param_iterator AnyFunctionCall::param_end() const {
    288   const FunctionDecl *D = getDecl();
    289   if (!D)
    290     return 0;
    291 
    292   return D->param_end();
    293 }
    294 
    295 void AnyFunctionCall::getInitialStackFrameContents(
    296                                         const StackFrameContext *CalleeCtx,
    297                                         BindingsTy &Bindings) const {
    298   const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
    299   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
    300   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
    301                                D->param_begin(), D->param_end());
    302 }
    303 
    304 bool AnyFunctionCall::argumentsMayEscape() const {
    305   if (hasNonZeroCallbackArg())
    306     return true;
    307 
    308   const FunctionDecl *D = getDecl();
    309   if (!D)
    310     return true;
    311 
    312   const IdentifierInfo *II = D->getIdentifier();
    313   if (!II)
    314     return true;
    315 
    316   // This set of "escaping" APIs is
    317 
    318   // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
    319   //   value into thread local storage. The value can later be retrieved with
    320   //   'void *ptheread_getspecific(pthread_key)'. So even thought the
    321   //   parameter is 'const void *', the region escapes through the call.
    322   if (II->isStr("pthread_setspecific"))
    323     return true;
    324 
    325   // - xpc_connection_set_context stores a value which can be retrieved later
    326   //   with xpc_connection_get_context.
    327   if (II->isStr("xpc_connection_set_context"))
    328     return true;
    329 
    330   // - funopen - sets a buffer for future IO calls.
    331   if (II->isStr("funopen"))
    332     return true;
    333 
    334   StringRef FName = II->getName();
    335 
    336   // - CoreFoundation functions that end with "NoCopy" can free a passed-in
    337   //   buffer even if it is const.
    338   if (FName.endswith("NoCopy"))
    339     return true;
    340 
    341   // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
    342   //   be deallocated by NSMapRemove.
    343   if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
    344     return true;
    345 
    346   // - Many CF containers allow objects to escape through custom
    347   //   allocators/deallocators upon container construction. (PR12101)
    348   if (FName.startswith("CF") || FName.startswith("CG")) {
    349     return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
    350            StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
    351            StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
    352            StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
    353            StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
    354            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
    355   }
    356 
    357   return false;
    358 }
    359 
    360 
    361 const FunctionDecl *SimpleCall::getDecl() const {
    362   const FunctionDecl *D = getOriginExpr()->getDirectCallee();
    363   if (D)
    364     return D;
    365 
    366   return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
    367 }
    368 
    369 
    370 const FunctionDecl *CXXInstanceCall::getDecl() const {
    371   const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
    372   if (!CE)
    373     return AnyFunctionCall::getDecl();
    374 
    375   const FunctionDecl *D = CE->getDirectCallee();
    376   if (D)
    377     return D;
    378 
    379   return getSVal(CE->getCallee()).getAsFunctionDecl();
    380 }
    381 
    382 void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
    383   if (const MemRegion *R = getCXXThisVal().getAsRegion())
    384     Regions.push_back(R);
    385 }
    386 
    387 SVal CXXInstanceCall::getCXXThisVal() const {
    388   const Expr *Base = getCXXThisExpr();
    389   // FIXME: This doesn't handle an overloaded ->* operator.
    390   if (!Base)
    391     return UnknownVal();
    392 
    393   SVal ThisVal = getSVal(Base);
    394 
    395   // FIXME: This is only necessary because we can call member functions on
    396   // struct rvalues, which do not have regions we can use for a 'this' pointer.
    397   // Ideally this should eventually be changed to an assert, i.e. all
    398   // non-Unknown, non-null 'this' values should be loc::MemRegionVals.
    399   if (isa<DefinedSVal>(ThisVal))
    400     if (!ThisVal.getAsRegion() && !ThisVal.isConstant())
    401       return UnknownVal();
    402 
    403   return ThisVal;
    404 }
    405 
    406 
    407 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
    408   // Do we have a decl at all?
    409   const Decl *D = getDecl();
    410   if (!D)
    411     return RuntimeDefinition();
    412 
    413   // If the method is non-virtual, we know we can inline it.
    414   const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
    415   if (!MD->isVirtual())
    416     return AnyFunctionCall::getRuntimeDefinition();
    417 
    418   // Do we know the implicit 'this' object being called?
    419   const MemRegion *R = getCXXThisVal().getAsRegion();
    420   if (!R)
    421     return RuntimeDefinition();
    422 
    423   // Do we know anything about the type of 'this'?
    424   DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
    425   if (!DynType.isValid())
    426     return RuntimeDefinition();
    427 
    428   // Is the type a C++ class? (This is mostly a defensive check.)
    429   QualType RegionType = DynType.getType()->getPointeeType();
    430   assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
    431 
    432   const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
    433   if (!RD || !RD->hasDefinition())
    434     return RuntimeDefinition();
    435 
    436   // Find the decl for this method in that class.
    437   const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
    438   if (!Result) {
    439     // We might not even get the original statically-resolved method due to
    440     // some particularly nasty casting (e.g. casts to sister classes).
    441     // However, we should at least be able to search up and down our own class
    442     // hierarchy, and some real bugs have been caught by checking this.
    443     assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
    444     assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
    445     return RuntimeDefinition();
    446   }
    447 
    448   // Does the decl that we found have an implementation?
    449   const FunctionDecl *Definition;
    450   if (!Result->hasBody(Definition))
    451     return RuntimeDefinition();
    452 
    453   // We found a definition. If we're not sure that this devirtualization is
    454   // actually what will happen at runtime, make sure to provide the region so
    455   // that ExprEngine can decide what to do with it.
    456   if (DynType.canBeASubClass())
    457     return RuntimeDefinition(Definition, R->StripCasts());
    458   return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
    459 }
    460 
    461 void CXXInstanceCall::getInitialStackFrameContents(
    462                                             const StackFrameContext *CalleeCtx,
    463                                             BindingsTy &Bindings) const {
    464   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
    465 
    466   // Handle the binding of 'this' in the new stack frame.
    467   SVal ThisVal = getCXXThisVal();
    468   if (!ThisVal.isUnknown()) {
    469     ProgramStateManager &StateMgr = getState()->getStateManager();
    470     SValBuilder &SVB = StateMgr.getSValBuilder();
    471 
    472     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
    473     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
    474 
    475     // If we devirtualized to a different member function, we need to make sure
    476     // we have the proper layering of CXXBaseObjectRegions.
    477     if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
    478       ASTContext &Ctx = SVB.getContext();
    479       const CXXRecordDecl *Class = MD->getParent();
    480       QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
    481 
    482       // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
    483       bool Failed;
    484       ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
    485       assert(!Failed && "Calling an incorrectly devirtualized method");
    486     }
    487 
    488     if (!ThisVal.isUnknown())
    489       Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
    490   }
    491 }
    492 
    493 
    494 
    495 const Expr *CXXMemberCall::getCXXThisExpr() const {
    496   return getOriginExpr()->getImplicitObjectArgument();
    497 }
    498 
    499 
    500 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
    501   return getOriginExpr()->getArg(0);
    502 }
    503 
    504 
    505 const BlockDataRegion *BlockCall::getBlockRegion() const {
    506   const Expr *Callee = getOriginExpr()->getCallee();
    507   const MemRegion *DataReg = getSVal(Callee).getAsRegion();
    508 
    509   return dyn_cast_or_null<BlockDataRegion>(DataReg);
    510 }
    511 
    512 CallEvent::param_iterator BlockCall::param_begin() const {
    513   const BlockDecl *D = getBlockDecl();
    514   if (!D)
    515     return 0;
    516   return D->param_begin();
    517 }
    518 
    519 CallEvent::param_iterator BlockCall::param_end() const {
    520   const BlockDecl *D = getBlockDecl();
    521   if (!D)
    522     return 0;
    523   return D->param_end();
    524 }
    525 
    526 void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
    527   // FIXME: This also needs to invalidate captured globals.
    528   if (const MemRegion *R = getBlockRegion())
    529     Regions.push_back(R);
    530 }
    531 
    532 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    533                                              BindingsTy &Bindings) const {
    534   const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
    535   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
    536   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
    537                                D->param_begin(), D->param_end());
    538 }
    539 
    540 
    541 SVal CXXConstructorCall::getCXXThisVal() const {
    542   if (Data)
    543     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
    544   return UnknownVal();
    545 }
    546 
    547 void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
    548   if (Data)
    549     Regions.push_back(static_cast<const MemRegion *>(Data));
    550 }
    551 
    552 void CXXConstructorCall::getInitialStackFrameContents(
    553                                              const StackFrameContext *CalleeCtx,
    554                                              BindingsTy &Bindings) const {
    555   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
    556 
    557   SVal ThisVal = getCXXThisVal();
    558   if (!ThisVal.isUnknown()) {
    559     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
    560     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
    561     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
    562     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
    563   }
    564 }
    565 
    566 
    567 
    568 SVal CXXDestructorCall::getCXXThisVal() const {
    569   if (Data)
    570     return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
    571   return UnknownVal();
    572 }
    573 
    574 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
    575   // Base destructors are always called non-virtually.
    576   // Skip CXXInstanceCall's devirtualization logic in this case.
    577   if (isBaseDestructor())
    578     return AnyFunctionCall::getRuntimeDefinition();
    579 
    580   return CXXInstanceCall::getRuntimeDefinition();
    581 }
    582 
    583 
    584 CallEvent::param_iterator ObjCMethodCall::param_begin() const {
    585   const ObjCMethodDecl *D = getDecl();
    586   if (!D)
    587     return 0;
    588 
    589   return D->param_begin();
    590 }
    591 
    592 CallEvent::param_iterator ObjCMethodCall::param_end() const {
    593   const ObjCMethodDecl *D = getDecl();
    594   if (!D)
    595     return 0;
    596 
    597   return D->param_end();
    598 }
    599 
    600 void
    601 ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
    602   if (const MemRegion *R = getReceiverSVal().getAsRegion())
    603     Regions.push_back(R);
    604 }
    605 
    606 SVal ObjCMethodCall::getSelfSVal() const {
    607   const LocationContext *LCtx = getLocationContext();
    608   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
    609   if (!SelfDecl)
    610     return SVal();
    611   return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
    612 }
    613 
    614 SVal ObjCMethodCall::getReceiverSVal() const {
    615   // FIXME: Is this the best way to handle class receivers?
    616   if (!isInstanceMessage())
    617     return UnknownVal();
    618 
    619   if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
    620     return getSVal(RecE);
    621 
    622   // An instance message with no expression means we are sending to super.
    623   // In this case the object reference is the same as 'self'.
    624   assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
    625   SVal SelfVal = getSelfSVal();
    626   assert(SelfVal.isValid() && "Calling super but not in ObjC method");
    627   return SelfVal;
    628 }
    629 
    630 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
    631   if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
    632       getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
    633       return true;
    634 
    635   if (!isInstanceMessage())
    636     return false;
    637 
    638   SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
    639 
    640   return (RecVal == getSelfSVal());
    641 }
    642 
    643 SourceRange ObjCMethodCall::getSourceRange() const {
    644   switch (getMessageKind()) {
    645   case OCM_Message:
    646     return getOriginExpr()->getSourceRange();
    647   case OCM_PropertyAccess:
    648   case OCM_Subscript:
    649     return getContainingPseudoObjectExpr()->getSourceRange();
    650   }
    651   llvm_unreachable("unknown message kind");
    652 }
    653 
    654 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
    655 
    656 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
    657   assert(Data != 0 && "Lazy lookup not yet performed.");
    658   assert(getMessageKind() != OCM_Message && "Explicit message send.");
    659   return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
    660 }
    661 
    662 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
    663   if (Data == 0) {
    664     ParentMap &PM = getLocationContext()->getParentMap();
    665     const Stmt *S = PM.getParent(getOriginExpr());
    666     if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
    667       const Expr *Syntactic = POE->getSyntacticForm();
    668 
    669       // This handles the funny case of assigning to the result of a getter.
    670       // This can happen if the getter returns a non-const reference.
    671       if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
    672         Syntactic = BO->getLHS();
    673 
    674       ObjCMessageKind K;
    675       switch (Syntactic->getStmtClass()) {
    676       case Stmt::ObjCPropertyRefExprClass:
    677         K = OCM_PropertyAccess;
    678         break;
    679       case Stmt::ObjCSubscriptRefExprClass:
    680         K = OCM_Subscript;
    681         break;
    682       default:
    683         // FIXME: Can this ever happen?
    684         K = OCM_Message;
    685         break;
    686       }
    687 
    688       if (K != OCM_Message) {
    689         const_cast<ObjCMethodCall *>(this)->Data
    690           = ObjCMessageDataTy(POE, K).getOpaqueValue();
    691         assert(getMessageKind() == K);
    692         return K;
    693       }
    694     }
    695 
    696     const_cast<ObjCMethodCall *>(this)->Data
    697       = ObjCMessageDataTy(0, 1).getOpaqueValue();
    698     assert(getMessageKind() == OCM_Message);
    699     return OCM_Message;
    700   }
    701 
    702   ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
    703   if (!Info.getPointer())
    704     return OCM_Message;
    705   return static_cast<ObjCMessageKind>(Info.getInt());
    706 }
    707 
    708 
    709 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
    710                                              Selector Sel) const {
    711   assert(IDecl);
    712   const SourceManager &SM =
    713     getState()->getStateManager().getContext().getSourceManager();
    714 
    715   // If the class interface is declared inside the main file, assume it is not
    716   // subcassed.
    717   // TODO: It could actually be subclassed if the subclass is private as well.
    718   // This is probably very rare.
    719   SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
    720   if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
    721     return false;
    722 
    723   // Assume that property accessors are not overridden.
    724   if (getMessageKind() == OCM_PropertyAccess)
    725     return false;
    726 
    727   // We assume that if the method is public (declared outside of main file) or
    728   // has a parent which publicly declares the method, the method could be
    729   // overridden in a subclass.
    730 
    731   // Find the first declaration in the class hierarchy that declares
    732   // the selector.
    733   ObjCMethodDecl *D = 0;
    734   while (true) {
    735     D = IDecl->lookupMethod(Sel, true);
    736 
    737     // Cannot find a public definition.
    738     if (!D)
    739       return false;
    740 
    741     // If outside the main file,
    742     if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
    743       return true;
    744 
    745     if (D->isOverriding()) {
    746       // Search in the superclass on the next iteration.
    747       IDecl = D->getClassInterface();
    748       if (!IDecl)
    749         return false;
    750 
    751       IDecl = IDecl->getSuperClass();
    752       if (!IDecl)
    753         return false;
    754 
    755       continue;
    756     }
    757 
    758     return false;
    759   };
    760 
    761   llvm_unreachable("The while loop should always terminate.");
    762 }
    763 
    764 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
    765   const ObjCMessageExpr *E = getOriginExpr();
    766   assert(E);
    767   Selector Sel = E->getSelector();
    768 
    769   if (E->isInstanceMessage()) {
    770 
    771     // Find the the receiver type.
    772     const ObjCObjectPointerType *ReceiverT = 0;
    773     bool CanBeSubClassed = false;
    774     QualType SupersType = E->getSuperType();
    775     const MemRegion *Receiver = 0;
    776 
    777     if (!SupersType.isNull()) {
    778       // Super always means the type of immediate predecessor to the method
    779       // where the call occurs.
    780       ReceiverT = cast<ObjCObjectPointerType>(SupersType);
    781     } else {
    782       Receiver = getReceiverSVal().getAsRegion();
    783       if (!Receiver)
    784         return RuntimeDefinition();
    785 
    786       DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
    787       QualType DynType = DTI.getType();
    788       CanBeSubClassed = DTI.canBeASubClass();
    789       ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
    790 
    791       if (ReceiverT && CanBeSubClassed)
    792         if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
    793           if (!canBeOverridenInSubclass(IDecl, Sel))
    794             CanBeSubClassed = false;
    795     }
    796 
    797     // Lookup the method implementation.
    798     if (ReceiverT)
    799       if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
    800         const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel);
    801         if (CanBeSubClassed)
    802           return RuntimeDefinition(MD, Receiver);
    803         else
    804           return RuntimeDefinition(MD, 0);
    805       }
    806 
    807   } else {
    808     // This is a class method.
    809     // If we have type info for the receiver class, we are calling via
    810     // class name.
    811     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
    812       // Find/Return the method implementation.
    813       return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
    814     }
    815   }
    816 
    817   return RuntimeDefinition();
    818 }
    819 
    820 void ObjCMethodCall::getInitialStackFrameContents(
    821                                              const StackFrameContext *CalleeCtx,
    822                                              BindingsTy &Bindings) const {
    823   const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
    824   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
    825   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
    826                                D->param_begin(), D->param_end());
    827 
    828   SVal SelfVal = getReceiverSVal();
    829   if (!SelfVal.isUnknown()) {
    830     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
    831     MemRegionManager &MRMgr = SVB.getRegionManager();
    832     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
    833     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
    834   }
    835 }
    836 
    837 CallEventRef<>
    838 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
    839                                 const LocationContext *LCtx) {
    840   if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
    841     return create<CXXMemberCall>(MCE, State, LCtx);
    842 
    843   if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
    844     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
    845     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
    846       if (MD->isInstance())
    847         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
    848 
    849   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
    850     return create<BlockCall>(CE, State, LCtx);
    851   }
    852 
    853   // Otherwise, it's a normal function call, static member function call, or
    854   // something we can't reason about.
    855   return create<FunctionCall>(CE, State, LCtx);
    856 }
    857 
    858 
    859 CallEventRef<>
    860 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
    861                             ProgramStateRef State) {
    862   const LocationContext *ParentCtx = CalleeCtx->getParent();
    863   const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
    864   assert(CallerCtx && "This should not be used for top-level stack frames");
    865 
    866   const Stmt *CallSite = CalleeCtx->getCallSite();
    867 
    868   if (CallSite) {
    869     if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
    870       return getSimpleCall(CE, State, CallerCtx);
    871 
    872     switch (CallSite->getStmtClass()) {
    873     case Stmt::CXXConstructExprClass:
    874     case Stmt::CXXTemporaryObjectExprClass: {
    875       SValBuilder &SVB = State->getStateManager().getSValBuilder();
    876       const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
    877       Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
    878       SVal ThisVal = State->getSVal(ThisPtr);
    879 
    880       return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
    881                                    ThisVal.getAsRegion(), State, CallerCtx);
    882     }
    883     case Stmt::CXXNewExprClass:
    884       return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
    885     case Stmt::ObjCMessageExprClass:
    886       return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
    887                                State, CallerCtx);
    888     default:
    889       llvm_unreachable("This is not an inlineable statement.");
    890     }
    891   }
    892 
    893   // Fall back to the CFG. The only thing we haven't handled yet is
    894   // destructors, though this could change in the future.
    895   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
    896   CFGElement E = (*B)[CalleeCtx->getIndex()];
    897   assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
    898   assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
    899 
    900   SValBuilder &SVB = State->getStateManager().getSValBuilder();
    901   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
    902   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
    903   SVal ThisVal = State->getSVal(ThisPtr);
    904 
    905   const Stmt *Trigger;
    906   if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
    907     Trigger = AutoDtor->getTriggerStmt();
    908   else
    909     Trigger = Dtor->getBody();
    910 
    911   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
    912                               isa<CFGBaseDtor>(E), State, CallerCtx);
    913 }
    914