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