14f7df9beSJordan Rose //===- Calls.cpp - Wrapper for all function and method calls ------*- C++ -*--//
24f7df9beSJordan Rose //
34f7df9beSJordan Rose //                     The LLVM Compiler Infrastructure
44f7df9beSJordan Rose //
54f7df9beSJordan Rose // This file is distributed under the University of Illinois Open Source
64f7df9beSJordan Rose // License. See LICENSE.TXT for details.
74f7df9beSJordan Rose //
84f7df9beSJordan Rose //===----------------------------------------------------------------------===//
94f7df9beSJordan Rose //
104f7df9beSJordan Rose /// \file This file defines CallEvent and its subclasses, which represent path-
114f7df9beSJordan Rose /// sensitive instances of different kinds of function and method calls
124f7df9beSJordan Rose /// (C, C++, and Objective-C).
134f7df9beSJordan Rose //
144f7df9beSJordan Rose //===----------------------------------------------------------------------===//
154f7df9beSJordan Rose 
164f7df9beSJordan Rose #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
174f7df9beSJordan Rose #include "clang/AST/ParentMap.h"
183a02247dSChandler Carruth #include "clang/Analysis/ProgramPoint.h"
193a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
204df9d812SGabor Horvath #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
214f7df9beSJordan Rose #include "llvm/ADT/SmallSet.h"
224f7df9beSJordan Rose #include "llvm/ADT/StringExtras.h"
23444a1304SBenjamin Kramer #include "llvm/Support/raw_ostream.h"
244f7df9beSJordan Rose 
254f7df9beSJordan Rose using namespace clang;
264f7df9beSJordan Rose using namespace ento;
274f7df9beSJordan Rose 
284f7df9beSJordan Rose QualType CallEvent::getResultType() const {
292da56438SJordan Rose   const Expr *E = getOriginExpr();
302da56438SJordan Rose   assert(E && "Calls without origin expressions do not have results");
312da56438SJordan Rose   QualType ResultTy = E->getType();
324f7df9beSJordan Rose 
332da56438SJordan Rose   ASTContext &Ctx = getState()->getStateManager().getContext();
342da56438SJordan Rose 
352da56438SJordan Rose   // A function that returns a reference to 'int' will have a result type
362da56438SJordan Rose   // of simply 'int'. Check the origin expr's value kind to recover the
372da56438SJordan Rose   // proper type.
382da56438SJordan Rose   switch (E->getValueKind()) {
392da56438SJordan Rose   case VK_LValue:
402da56438SJordan Rose     ResultTy = Ctx.getLValueReferenceType(ResultTy);
412da56438SJordan Rose     break;
422da56438SJordan Rose   case VK_XValue:
432da56438SJordan Rose     ResultTy = Ctx.getRValueReferenceType(ResultTy);
442da56438SJordan Rose     break;
452da56438SJordan Rose   case VK_RValue:
462da56438SJordan Rose     // No adjustment is necessary.
472da56438SJordan Rose     break;
482da56438SJordan Rose   }
494f7df9beSJordan Rose 
504f7df9beSJordan Rose   return ResultTy;
514f7df9beSJordan Rose }
524f7df9beSJordan Rose 
53fe1eca51SAnna Zaks static bool isCallback(QualType T) {
544f7df9beSJordan Rose   // If a parameter is a block or a callback, assume it can modify pointer.
554f7df9beSJordan Rose   if (T->isBlockPointerType() ||
564f7df9beSJordan Rose       T->isFunctionPointerType() ||
574f7df9beSJordan Rose       T->isObjCSelType())
584f7df9beSJordan Rose     return true;
594f7df9beSJordan Rose 
604f7df9beSJordan Rose   // Check if a callback is passed inside a struct (for both, struct passed by
614f7df9beSJordan Rose   // reference and by value). Dig just one level into the struct for now.
624f7df9beSJordan Rose 
63d1a08b6eSJordan Rose   if (T->isAnyPointerType() || T->isReferenceType())
644f7df9beSJordan Rose     T = T->getPointeeType();
654f7df9beSJordan Rose 
664f7df9beSJordan Rose   if (const RecordType *RT = T->getAsStructureType()) {
674f7df9beSJordan Rose     const RecordDecl *RD = RT->getDecl();
68e8a8baefSAaron Ballman     for (const auto *I : RD->fields()) {
694f7df9beSJordan Rose       QualType FieldT = I->getType();
704f7df9beSJordan Rose       if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
714f7df9beSJordan Rose         return true;
724f7df9beSJordan Rose     }
734f7df9beSJordan Rose   }
744f7df9beSJordan Rose   return false;
754f7df9beSJordan Rose }
764f7df9beSJordan Rose 
77fe1eca51SAnna Zaks static bool isVoidPointerToNonConst(QualType T) {
78fe1eca51SAnna Zaks   if (const PointerType *PT = T->getAs<PointerType>()) {
79fe1eca51SAnna Zaks     QualType PointeeTy = PT->getPointeeType();
80fe1eca51SAnna Zaks     if (PointeeTy.isConstQualified())
81fe1eca51SAnna Zaks       return false;
82fe1eca51SAnna Zaks     return PointeeTy->isVoidType();
83fe1eca51SAnna Zaks   } else
84fe1eca51SAnna Zaks     return false;
85fe1eca51SAnna Zaks }
86fe1eca51SAnna Zaks 
87fe1eca51SAnna Zaks bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
884f7df9beSJordan Rose   unsigned NumOfArgs = getNumArgs();
894f7df9beSJordan Rose 
904f7df9beSJordan Rose   // If calling using a function pointer, assume the function does not
91fe1eca51SAnna Zaks   // satisfy the callback.
92fe1eca51SAnna Zaks   // TODO: We could check the types of the arguments here.
934f7df9beSJordan Rose   if (!getDecl())
944f7df9beSJordan Rose     return false;
954f7df9beSJordan Rose 
964f7df9beSJordan Rose   unsigned Idx = 0;
974f7df9beSJordan Rose   for (CallEvent::param_type_iterator I = param_type_begin(),
984f7df9beSJordan Rose                                       E = param_type_end();
994f7df9beSJordan Rose        I != E && Idx < NumOfArgs; ++I, ++Idx) {
1004f7df9beSJordan Rose     if (NumOfArgs <= Idx)
1014f7df9beSJordan Rose       break;
1024f7df9beSJordan Rose 
103fe1eca51SAnna Zaks     // If the parameter is 0, it's harmless.
104fe1eca51SAnna Zaks     if (getArgSVal(Idx).isZeroConstant())
105fe1eca51SAnna Zaks       continue;
106fe1eca51SAnna Zaks 
107fe1eca51SAnna Zaks     if (Condition(*I))
1084f7df9beSJordan Rose       return true;
1094f7df9beSJordan Rose   }
1104f7df9beSJordan Rose   return false;
1114f7df9beSJordan Rose }
1124f7df9beSJordan Rose 
113fe1eca51SAnna Zaks bool CallEvent::hasNonZeroCallbackArg() const {
114fe1eca51SAnna Zaks   return hasNonNullArgumentsWithType(isCallback);
115fe1eca51SAnna Zaks }
116fe1eca51SAnna Zaks 
117fe1eca51SAnna Zaks bool CallEvent::hasVoidPointerToNonConstArg() const {
118fe1eca51SAnna Zaks   return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
119fe1eca51SAnna Zaks }
120fe1eca51SAnna Zaks 
121829c3831SJordan Rose bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
122829c3831SJordan Rose   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
123829c3831SJordan Rose   if (!FD)
124829c3831SJordan Rose     return false;
125829c3831SJordan Rose 
126829c3831SJordan Rose   return CheckerContext::isCLibraryFunction(FD, FunctionName);
127829c3831SJordan Rose }
128829c3831SJordan Rose 
1294f7df9beSJordan Rose /// \brief Returns true if a type is a pointer-to-const or reference-to-const
1304f7df9beSJordan Rose /// with no further indirection.
1314f7df9beSJordan Rose static bool isPointerToConst(QualType Ty) {
1324f7df9beSJordan Rose   QualType PointeeTy = Ty->getPointeeType();
1334f7df9beSJordan Rose   if (PointeeTy == QualType())
1344f7df9beSJordan Rose     return false;
1354f7df9beSJordan Rose   if (!PointeeTy.isConstQualified())
1364f7df9beSJordan Rose     return false;
1374f7df9beSJordan Rose   if (PointeeTy->isAnyPointerType())
1384f7df9beSJordan Rose     return false;
1394f7df9beSJordan Rose   return true;
1404f7df9beSJordan Rose }
1414f7df9beSJordan Rose 
1424f7df9beSJordan Rose // Try to retrieve the function declaration and find the function parameter
1434f7df9beSJordan Rose // types which are pointers/references to a non-pointer const.
1444f7df9beSJordan Rose // We will not invalidate the corresponding argument regions.
1455413aaa7SJordan Rose static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
1464f7df9beSJordan Rose                                  const CallEvent &Call) {
1474f7df9beSJordan Rose   unsigned Idx = 0;
1484f7df9beSJordan Rose   for (CallEvent::param_type_iterator I = Call.param_type_begin(),
1494f7df9beSJordan Rose                                       E = Call.param_type_end();
1504f7df9beSJordan Rose        I != E; ++I, ++Idx) {
1514f7df9beSJordan Rose     if (isPointerToConst(*I))
1524f7df9beSJordan Rose       PreserveArgs.insert(Idx);
1534f7df9beSJordan Rose   }
1544f7df9beSJordan Rose }
1554f7df9beSJordan Rose 
1564f7df9beSJordan Rose ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
1574f7df9beSJordan Rose                                              ProgramStateRef Orig) const {
1584f7df9beSJordan Rose   ProgramStateRef Result = (Orig ? Orig : getState());
1594f7df9beSJordan Rose 
1602741654bSJordan Rose   // Don't invalidate anything if the callee is marked pure/const.
1612741654bSJordan Rose   if (const Decl *callee = getDecl())
1622741654bSJordan Rose     if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
1632741654bSJordan Rose       return Result;
1642741654bSJordan Rose 
16560bf5f45SAnna Zaks   SmallVector<SVal, 8> ValuesToInvalidate;
166424ad95fSAnton Yartsev   RegionAndSymbolInvalidationTraits ETraits;
16760bf5f45SAnna Zaks 
1684f770deeSDevin Coughlin   getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
1694f7df9beSJordan Rose 
1704f7df9beSJordan Rose   // Indexes of arguments whose values will be preserved by the call.
1715413aaa7SJordan Rose   llvm::SmallSet<unsigned, 4> PreserveArgs;
1724f7df9beSJordan Rose   if (!argumentsMayEscape())
1734f7df9beSJordan Rose     findPtrToConstParams(PreserveArgs, *this);
1744f7df9beSJordan Rose 
1754f7df9beSJordan Rose   for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
1764f7df9beSJordan Rose     // Mark this region for invalidation.  We batch invalidate regions
1774f7df9beSJordan Rose     // below for efficiency.
1785413aaa7SJordan Rose     if (PreserveArgs.count(Idx))
179424ad95fSAnton Yartsev       if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
18070247e69SArtem Dergachev         ETraits.setTrait(MR->getBaseRegion(),
181424ad95fSAnton Yartsev                         RegionAndSymbolInvalidationTraits::TK_PreserveContents);
182424ad95fSAnton Yartsev         // TODO: Factor this out + handle the lower level const pointers.
183424ad95fSAnton Yartsev 
18460bf5f45SAnna Zaks     ValuesToInvalidate.push_back(getArgSVal(Idx));
1854f7df9beSJordan Rose   }
1864f7df9beSJordan Rose 
1874f7df9beSJordan Rose   // Invalidate designated regions using the batch invalidation API.
1884f7df9beSJordan Rose   // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
1894f7df9beSJordan Rose   //  global variables.
19060bf5f45SAnna Zaks   return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
1914f7df9beSJordan Rose                                    BlockCount, getLocationContext(),
1929747febbSAnna Zaks                                    /*CausedByPointerEscape*/ true,
1930dbb783cSCraig Topper                                    /*Symbols=*/nullptr, this, &ETraits);
1944f7df9beSJordan Rose }
1954f7df9beSJordan Rose 
1964f7df9beSJordan Rose ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
1974f7df9beSJordan Rose                                         const ProgramPointTag *Tag) const {
1984f7df9beSJordan Rose   if (const Expr *E = getOriginExpr()) {
1994f7df9beSJordan Rose     if (IsPreVisit)
2004f7df9beSJordan Rose       return PreStmt(E, getLocationContext(), Tag);
2014f7df9beSJordan Rose     return PostStmt(E, getLocationContext(), Tag);
2024f7df9beSJordan Rose   }
2034f7df9beSJordan Rose 
2044f7df9beSJordan Rose   const Decl *D = getDecl();
2054f7df9beSJordan Rose   assert(D && "Cannot get a program point without a statement or decl");
2064f7df9beSJordan Rose 
2074f7df9beSJordan Rose   SourceLocation Loc = getSourceRange().getBegin();
2084f7df9beSJordan Rose   if (IsPreVisit)
2094f7df9beSJordan Rose     return PreImplicitCall(D, Loc, getLocationContext(), Tag);
2104f7df9beSJordan Rose   return PostImplicitCall(D, Loc, getLocationContext(), Tag);
2114f7df9beSJordan Rose }
2124f7df9beSJordan Rose 
213343730c5SGabor Horvath bool CallEvent::isCalled(const CallDescription &CD) const {
214343730c5SGabor Horvath   assert(getKind() != CE_ObjCMessage && "Obj-C methods are not supported");
215343730c5SGabor Horvath   if (!CD.II)
216343730c5SGabor Horvath     CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
217343730c5SGabor Horvath   if (getCalleeIdentifier() != CD.II)
218343730c5SGabor Horvath     return false;
219343730c5SGabor Horvath   return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
220343730c5SGabor Horvath           CD.RequiredArgs == getNumArgs());
221343730c5SGabor Horvath }
222343730c5SGabor Horvath 
22372ce8e2dSJordan Rose SVal CallEvent::getArgSVal(unsigned Index) const {
22472ce8e2dSJordan Rose   const Expr *ArgE = getArgExpr(Index);
22572ce8e2dSJordan Rose   if (!ArgE)
22672ce8e2dSJordan Rose     return UnknownVal();
22772ce8e2dSJordan Rose   return getSVal(ArgE);
22872ce8e2dSJordan Rose }
22972ce8e2dSJordan Rose 
23072ce8e2dSJordan Rose SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
23172ce8e2dSJordan Rose   const Expr *ArgE = getArgExpr(Index);
23272ce8e2dSJordan Rose   if (!ArgE)
23372ce8e2dSJordan Rose     return SourceRange();
23472ce8e2dSJordan Rose   return ArgE->getSourceRange();
23572ce8e2dSJordan Rose }
23672ce8e2dSJordan Rose 
237829c3831SJordan Rose SVal CallEvent::getReturnValue() const {
238829c3831SJordan Rose   const Expr *E = getOriginExpr();
239829c3831SJordan Rose   if (!E)
240829c3831SJordan Rose     return UndefinedVal();
241829c3831SJordan Rose   return getSVal(E);
242829c3831SJordan Rose }
243829c3831SJordan Rose 
244ef6b007dSAlp Toker LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
2459299d8c2SBenjamin Kramer 
24672ce8e2dSJordan Rose void CallEvent::dump(raw_ostream &Out) const {
24772ce8e2dSJordan Rose   ASTContext &Ctx = getState()->getStateManager().getContext();
24872ce8e2dSJordan Rose   if (const Expr *E = getOriginExpr()) {
2490dbb783cSCraig Topper     E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
25072ce8e2dSJordan Rose     Out << "\n";
25172ce8e2dSJordan Rose     return;
25272ce8e2dSJordan Rose   }
25372ce8e2dSJordan Rose 
25472ce8e2dSJordan Rose   if (const Decl *D = getDecl()) {
25572ce8e2dSJordan Rose     Out << "Call to ";
25672ce8e2dSJordan Rose     D->print(Out, Ctx.getPrintingPolicy());
25772ce8e2dSJordan Rose     return;
25872ce8e2dSJordan Rose   }
25972ce8e2dSJordan Rose 
26072ce8e2dSJordan Rose   // FIXME: a string representation of the kind would be nice.
26172ce8e2dSJordan Rose   Out << "Unknown call (type " << getKind() << ")";
26272ce8e2dSJordan Rose }
26372ce8e2dSJordan Rose 
2644f7df9beSJordan Rose 
265e537cc05SJordan Rose bool CallEvent::isCallStmt(const Stmt *S) {
26672ce8e2dSJordan Rose   return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
267e537cc05SJordan Rose                           || isa<CXXConstructExpr>(S)
268e537cc05SJordan Rose                           || isa<CXXNewExpr>(S);
2694f7df9beSJordan Rose }
2704f7df9beSJordan Rose 
2715d2964e7SAnna Zaks QualType CallEvent::getDeclaredResultType(const Decl *D) {
2725d2964e7SAnna Zaks   assert(D);
2735d2964e7SAnna Zaks   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
274314cc81bSAlp Toker     return FD->getReturnType();
275add14263SJordan Rose   if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
276314cc81bSAlp Toker     return MD->getReturnType();
277add14263SJordan Rose   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
278add14263SJordan Rose     // Blocks are difficult because the return type may not be stored in the
279add14263SJordan Rose     // BlockDecl itself. The AST should probably be enhanced, but for now we
280add14263SJordan Rose     // just do what we can.
281278d9de3SJordan Rose     // If the block is declared without an explicit argument list, the
282278d9de3SJordan Rose     // signature-as-written just includes the return type, not the entire
283278d9de3SJordan Rose     // function type.
2841bfe9c78SJordan Rose     // FIXME: All blocks should have signatures-as-written, even if the return
285278d9de3SJordan Rose     // type is inferred. (That's signified with a dependent result type.)
2861bfe9c78SJordan Rose     if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
287278d9de3SJordan Rose       QualType Ty = TSI->getType();
288278d9de3SJordan Rose       if (const FunctionType *FT = Ty->getAs<FunctionType>())
289314cc81bSAlp Toker         Ty = FT->getReturnType();
290278d9de3SJordan Rose       if (!Ty->isDependentType())
291278d9de3SJordan Rose         return Ty;
2921bfe9c78SJordan Rose     }
293add14263SJordan Rose 
294add14263SJordan Rose     return QualType();
295add14263SJordan Rose   }
296add14263SJordan Rose 
2973553bb38SJordan Rose   llvm_unreachable("unknown callable kind");
2983553bb38SJordan Rose }
2993553bb38SJordan Rose 
3003553bb38SJordan Rose bool CallEvent::isVariadic(const Decl *D) {
3013553bb38SJordan Rose   assert(D);
3023553bb38SJordan Rose 
3033553bb38SJordan Rose   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3043553bb38SJordan Rose     return FD->isVariadic();
3053553bb38SJordan Rose   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3063553bb38SJordan Rose     return MD->isVariadic();
3073553bb38SJordan Rose   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
3083553bb38SJordan Rose     return BD->isVariadic();
3093553bb38SJordan Rose 
3103553bb38SJordan Rose   llvm_unreachable("unknown callable kind");
3115d2964e7SAnna Zaks }
3125d2964e7SAnna Zaks 
31342e8d649SJordan Rose static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
31442e8d649SJordan Rose                                          CallEvent::BindingsTy &Bindings,
31542e8d649SJordan Rose                                          SValBuilder &SVB,
31642e8d649SJordan Rose                                          const CallEvent &Call,
3172ff16004STed Kremenek                                          ArrayRef<ParmVarDecl*> parameters) {
31842e8d649SJordan Rose   MemRegionManager &MRMgr = SVB.getRegionManager();
3194f7df9beSJordan Rose 
320963f91b3SPavel Labath   // If the function has fewer parameters than the call has arguments, we simply
321963f91b3SPavel Labath   // do not bind any values to them.
322963f91b3SPavel Labath   unsigned NumArgs = Call.getNumArgs();
32342e8d649SJordan Rose   unsigned Idx = 0;
3242ff16004STed Kremenek   ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
325963f91b3SPavel Labath   for (; I != E && Idx < NumArgs; ++I, ++Idx) {
32642e8d649SJordan Rose     const ParmVarDecl *ParamDecl = *I;
32742e8d649SJordan Rose     assert(ParamDecl && "Formal parameter has no decl?");
3284f7df9beSJordan Rose 
32942e8d649SJordan Rose     SVal ArgVal = Call.getArgSVal(Idx);
33042e8d649SJordan Rose     if (!ArgVal.isUnknown()) {
33142e8d649SJordan Rose       Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
33242e8d649SJordan Rose       Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
33342e8d649SJordan Rose     }
3344f7df9beSJordan Rose   }
3354f7df9beSJordan Rose 
33642e8d649SJordan Rose   // FIXME: Variadic arguments are not handled at all right now.
33742e8d649SJordan Rose }
33842e8d649SJordan Rose 
3392ff16004STed Kremenek ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
34042e8d649SJordan Rose   const FunctionDecl *D = getDecl();
3414f7df9beSJordan Rose   if (!D)
34200bbdcf9SCraig Topper     return None;
3432ff16004STed Kremenek   return D->parameters();
34442e8d649SJordan Rose }
34542e8d649SJordan Rose 
34642e8d649SJordan Rose void AnyFunctionCall::getInitialStackFrameContents(
34742e8d649SJordan Rose                                         const StackFrameContext *CalleeCtx,
34842e8d649SJordan Rose                                         BindingsTy &Bindings) const {
34942e8d649SJordan Rose   const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
35042e8d649SJordan Rose   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
35142e8d649SJordan Rose   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
3522ff16004STed Kremenek                                D->parameters());
3534f7df9beSJordan Rose }
3544f7df9beSJordan Rose 
3554f7df9beSJordan Rose bool AnyFunctionCall::argumentsMayEscape() const {
356fe1eca51SAnna Zaks   if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
3574f7df9beSJordan Rose     return true;
3584f7df9beSJordan Rose 
3594f7df9beSJordan Rose   const FunctionDecl *D = getDecl();
3604f7df9beSJordan Rose   if (!D)
3614f7df9beSJordan Rose     return true;
3624f7df9beSJordan Rose 
3634f7df9beSJordan Rose   const IdentifierInfo *II = D->getIdentifier();
3644f7df9beSJordan Rose   if (!II)
3657bd0674dSAnna Zaks     return false;
3664f7df9beSJordan Rose 
3674f7df9beSJordan Rose   // This set of "escaping" APIs is
3684f7df9beSJordan Rose 
3694f7df9beSJordan Rose   // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
3704f7df9beSJordan Rose   //   value into thread local storage. The value can later be retrieved with
3714f7df9beSJordan Rose   //   'void *ptheread_getspecific(pthread_key)'. So even thought the
3724f7df9beSJordan Rose   //   parameter is 'const void *', the region escapes through the call.
3734f7df9beSJordan Rose   if (II->isStr("pthread_setspecific"))
3744f7df9beSJordan Rose     return true;
3754f7df9beSJordan Rose 
3764f7df9beSJordan Rose   // - xpc_connection_set_context stores a value which can be retrieved later
3774f7df9beSJordan Rose   //   with xpc_connection_get_context.
3784f7df9beSJordan Rose   if (II->isStr("xpc_connection_set_context"))
3794f7df9beSJordan Rose     return true;
3804f7df9beSJordan Rose 
3814f7df9beSJordan Rose   // - funopen - sets a buffer for future IO calls.
3824f7df9beSJordan Rose   if (II->isStr("funopen"))
3834f7df9beSJordan Rose     return true;
3844f7df9beSJordan Rose 
3854f7df9beSJordan Rose   StringRef FName = II->getName();
3864f7df9beSJordan Rose 
3874f7df9beSJordan Rose   // - CoreFoundation functions that end with "NoCopy" can free a passed-in
3884f7df9beSJordan Rose   //   buffer even if it is const.
3894f7df9beSJordan Rose   if (FName.endswith("NoCopy"))
3904f7df9beSJordan Rose     return true;
3914f7df9beSJordan Rose 
3924f7df9beSJordan Rose   // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
3934f7df9beSJordan Rose   //   be deallocated by NSMapRemove.
3944f7df9beSJordan Rose   if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
3954f7df9beSJordan Rose     return true;
3964f7df9beSJordan Rose 
3974f7df9beSJordan Rose   // - Many CF containers allow objects to escape through custom
3984f7df9beSJordan Rose   //   allocators/deallocators upon container construction. (PR12101)
3994f7df9beSJordan Rose   if (FName.startswith("CF") || FName.startswith("CG")) {
4004f7df9beSJordan Rose     return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
4014f7df9beSJordan Rose            StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
4024f7df9beSJordan Rose            StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
4034f7df9beSJordan Rose            StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
4044f7df9beSJordan Rose            StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
4054f7df9beSJordan Rose            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
4064f7df9beSJordan Rose   }
4074f7df9beSJordan Rose 
4084f7df9beSJordan Rose   return false;
4094f7df9beSJordan Rose }
4104f7df9beSJordan Rose 
4114f7df9beSJordan Rose 
4122a833ca5SJordan Rose const FunctionDecl *SimpleFunctionCall::getDecl() const {
4134f7df9beSJordan Rose   const FunctionDecl *D = getOriginExpr()->getDirectCallee();
4144f7df9beSJordan Rose   if (D)
4154f7df9beSJordan Rose     return D;
4164f7df9beSJordan Rose 
4174f7df9beSJordan Rose   return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
4184f7df9beSJordan Rose }
4194f7df9beSJordan Rose 
4204f7df9beSJordan Rose 
421ce6c99a5SJordan Rose const FunctionDecl *CXXInstanceCall::getDecl() const {
422ce6c99a5SJordan Rose   const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
423ce6c99a5SJordan Rose   if (!CE)
424ce6c99a5SJordan Rose     return AnyFunctionCall::getDecl();
425ce6c99a5SJordan Rose 
426ce6c99a5SJordan Rose   const FunctionDecl *D = CE->getDirectCallee();
427ce6c99a5SJordan Rose   if (D)
428ce6c99a5SJordan Rose     return D;
429ce6c99a5SJordan Rose 
430ce6c99a5SJordan Rose   return getSVal(CE->getCallee()).getAsFunctionDecl();
431ce6c99a5SJordan Rose }
432ce6c99a5SJordan Rose 
43300e780e1SSean Eveson void CXXInstanceCall::getExtraInvalidatedValues(
43400e780e1SSean Eveson     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
4354f770deeSDevin Coughlin   SVal ThisVal = getCXXThisVal();
4364f770deeSDevin Coughlin   Values.push_back(ThisVal);
4374f770deeSDevin Coughlin 
4383f072ef8SSean Eveson   // Don't invalidate if the method is const and there are no mutable fields.
4394f770deeSDevin Coughlin   if (const CXXMethodDecl *D = cast_or_null<CXXMethodDecl>(getDecl())) {
4404f770deeSDevin Coughlin     if (!D->isConst())
4414f770deeSDevin Coughlin       return;
4424f770deeSDevin Coughlin     // Get the record decl for the class of 'This'. D->getParent() may return a
4434f770deeSDevin Coughlin     // base class decl, rather than the class of the instance which needs to be
4444f770deeSDevin Coughlin     // checked for mutable fields.
4454f770deeSDevin Coughlin     const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
4464f770deeSDevin Coughlin     const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl();
4474f770deeSDevin Coughlin     if (!ParentRecord || ParentRecord->hasMutableFields())
4484f770deeSDevin Coughlin       return;
4494f770deeSDevin Coughlin     // Preserve CXXThis.
4504f770deeSDevin Coughlin     const MemRegion *ThisRegion = ThisVal.getAsRegion();
4519c76869bSDevin Coughlin     if (!ThisRegion)
4529c76869bSDevin Coughlin       return;
4539c76869bSDevin Coughlin 
4544f770deeSDevin Coughlin     ETraits->setTrait(ThisRegion->getBaseRegion(),
4554f770deeSDevin Coughlin                       RegionAndSymbolInvalidationTraits::TK_PreserveContents);
4564f770deeSDevin Coughlin   }
4574f7df9beSJordan Rose }
4584f7df9beSJordan Rose 
459fcdda361SJordan Rose SVal CXXInstanceCall::getCXXThisVal() const {
460fcdda361SJordan Rose   const Expr *Base = getCXXThisExpr();
461fcdda361SJordan Rose   // FIXME: This doesn't handle an overloaded ->* operator.
462fcdda361SJordan Rose   if (!Base)
463fcdda361SJordan Rose     return UnknownVal();
464fcdda361SJordan Rose 
465fcdda361SJordan Rose   SVal ThisVal = getSVal(Base);
4662fdacbc5SDavid Blaikie   assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
467fcdda361SJordan Rose   return ThisVal;
468fcdda361SJordan Rose }
469fcdda361SJordan Rose 
4704f7df9beSJordan Rose 
471089c5510STed Kremenek RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
4720f6d63beSJordan Rose   // Do we have a decl at all?
47351bcb226SJordan Rose   const Decl *D = getDecl();
4744f7df9beSJordan Rose   if (!D)
475123af098SAnna Zaks     return RuntimeDefinition();
4764f7df9beSJordan Rose 
4770f6d63beSJordan Rose   // If the method is non-virtual, we know we can inline it.
4784f7df9beSJordan Rose   const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
4794f7df9beSJordan Rose   if (!MD->isVirtual())
480089c5510STed Kremenek     return AnyFunctionCall::getRuntimeDefinition();
4814f7df9beSJordan Rose 
4820f6d63beSJordan Rose   // Do we know the implicit 'this' object being called?
4830f6d63beSJordan Rose   const MemRegion *R = getCXXThisVal().getAsRegion();
4840f6d63beSJordan Rose   if (!R)
485123af098SAnna Zaks     return RuntimeDefinition();
4860f6d63beSJordan Rose 
4870f6d63beSJordan Rose   // Do we know anything about the type of 'this'?
4884df9d812SGabor Horvath   DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
4890f6d63beSJordan Rose   if (!DynType.isValid())
4900f6d63beSJordan Rose     return RuntimeDefinition();
4910f6d63beSJordan Rose 
4920f6d63beSJordan Rose   // Is the type a C++ class? (This is mostly a defensive check.)
4930f6d63beSJordan Rose   QualType RegionType = DynType.getType()->getPointeeType();
494d1a08b6eSJordan Rose   assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
495d1a08b6eSJordan Rose 
4960f6d63beSJordan Rose   const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
49799107208SJordan Rose   if (!RD || !RD->hasDefinition())
4980f6d63beSJordan Rose     return RuntimeDefinition();
4990f6d63beSJordan Rose 
50099c6c2b4SJordan Rose   // Find the decl for this method in that class.
50199c6c2b4SJordan Rose   const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
50281456d9fSJordan Rose   if (!Result) {
50381456d9fSJordan Rose     // We might not even get the original statically-resolved method due to
50481456d9fSJordan Rose     // some particularly nasty casting (e.g. casts to sister classes).
50581456d9fSJordan Rose     // However, we should at least be able to search up and down our own class
50681456d9fSJordan Rose     // hierarchy, and some real bugs have been caught by checking this.
50781456d9fSJordan Rose     assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
508d44977efSJordan Rose 
509d44977efSJordan Rose     // FIXME: This is checking that our DynamicTypeInfo is at least as good as
510d44977efSJordan Rose     // the static type. However, because we currently don't update
511d44977efSJordan Rose     // DynamicTypeInfo when an object is cast, we can't actually be sure the
512d44977efSJordan Rose     // DynamicTypeInfo is up to date. This assert should be re-enabled once
513d44977efSJordan Rose     // this is fixed. <rdar://problem/12287087>
514d44977efSJordan Rose     //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
515d44977efSJordan Rose 
51681456d9fSJordan Rose     return RuntimeDefinition();
51781456d9fSJordan Rose   }
5180f6d63beSJordan Rose 
5190f6d63beSJordan Rose   // Does the decl that we found have an implementation?
5200f6d63beSJordan Rose   const FunctionDecl *Definition;
5210f6d63beSJordan Rose   if (!Result->hasBody(Definition))
5220f6d63beSJordan Rose     return RuntimeDefinition();
5230f6d63beSJordan Rose 
5240f6d63beSJordan Rose   // We found a definition. If we're not sure that this devirtualization is
5250f6d63beSJordan Rose   // actually what will happen at runtime, make sure to provide the region so
5260f6d63beSJordan Rose   // that ExprEngine can decide what to do with it.
5270f6d63beSJordan Rose   if (DynType.canBeASubClass())
5280f6d63beSJordan Rose     return RuntimeDefinition(Definition, R->StripCasts());
5290dbb783cSCraig Topper   return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
5304f7df9beSJordan Rose }
5314f7df9beSJordan Rose 
53242e8d649SJordan Rose void CXXInstanceCall::getInitialStackFrameContents(
53342e8d649SJordan Rose                                             const StackFrameContext *CalleeCtx,
53442e8d649SJordan Rose                                             BindingsTy &Bindings) const {
53542e8d649SJordan Rose   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
53642e8d649SJordan Rose 
53702e5309bSJordan Rose   // Handle the binding of 'this' in the new stack frame.
53842e8d649SJordan Rose   SVal ThisVal = getCXXThisVal();
53942e8d649SJordan Rose   if (!ThisVal.isUnknown()) {
54002e5309bSJordan Rose     ProgramStateManager &StateMgr = getState()->getStateManager();
54102e5309bSJordan Rose     SValBuilder &SVB = StateMgr.getSValBuilder();
54202e5309bSJordan Rose 
54342e8d649SJordan Rose     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
54442e8d649SJordan Rose     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
54502e5309bSJordan Rose 
54631c3fa9cSJordan Rose     // If we devirtualized to a different member function, we need to make sure
54731c3fa9cSJordan Rose     // we have the proper layering of CXXBaseObjectRegions.
54831c3fa9cSJordan Rose     if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
549710f6b12SJordan Rose       ASTContext &Ctx = SVB.getContext();
55002e5309bSJordan Rose       const CXXRecordDecl *Class = MD->getParent();
551710f6b12SJordan Rose       QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
55202e5309bSJordan Rose 
553710f6b12SJordan Rose       // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
554710f6b12SJordan Rose       bool Failed;
555*44583ce6SGabor Horvath       ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
556710f6b12SJordan Rose       assert(!Failed && "Calling an incorrectly devirtualized method");
55702e5309bSJordan Rose     }
55802e5309bSJordan Rose 
55931c3fa9cSJordan Rose     if (!ThisVal.isUnknown())
56042e8d649SJordan Rose       Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
56142e8d649SJordan Rose   }
56242e8d649SJordan Rose }
56342e8d649SJordan Rose 
56442e8d649SJordan Rose 
5654f7df9beSJordan Rose 
56692e1449bSJordan Rose const Expr *CXXMemberCall::getCXXThisExpr() const {
56792e1449bSJordan Rose   return getOriginExpr()->getImplicitObjectArgument();
5684f7df9beSJordan Rose }
5694f7df9beSJordan Rose 
570089c5510STed Kremenek RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
57112f669e3SJordan Rose   // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
57212f669e3SJordan Rose   // id-expression in the class member access expression is a qualified-id,
57312f669e3SJordan Rose   // that function is called. Otherwise, its final overrider in the dynamic type
57412f669e3SJordan Rose   // of the object expression is called.
57512f669e3SJordan Rose   if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
57612f669e3SJordan Rose     if (ME->hasQualifier())
577089c5510STed Kremenek       return AnyFunctionCall::getRuntimeDefinition();
57812f669e3SJordan Rose 
579089c5510STed Kremenek   return CXXInstanceCall::getRuntimeDefinition();
58012f669e3SJordan Rose }
58112f669e3SJordan Rose 
5824f7df9beSJordan Rose 
58392e1449bSJordan Rose const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
58492e1449bSJordan Rose   return getOriginExpr()->getArg(0);
5854f7df9beSJordan Rose }
5864f7df9beSJordan Rose 
5874f7df9beSJordan Rose 
5884f7df9beSJordan Rose const BlockDataRegion *BlockCall::getBlockRegion() const {
5894f7df9beSJordan Rose   const Expr *Callee = getOriginExpr()->getCallee();
5904f7df9beSJordan Rose   const MemRegion *DataReg = getSVal(Callee).getAsRegion();
5914f7df9beSJordan Rose 
5924f7df9beSJordan Rose   return dyn_cast_or_null<BlockDataRegion>(DataReg);
5934f7df9beSJordan Rose }
5944f7df9beSJordan Rose 
5952ff16004STed Kremenek ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
5962a833ca5SJordan Rose   const BlockDecl *D = getDecl();
5974f7df9beSJordan Rose   if (!D)
5980dbb783cSCraig Topper     return nullptr;
5992ff16004STed Kremenek   return D->parameters();
6004f7df9beSJordan Rose }
6014f7df9beSJordan Rose 
6024f770deeSDevin Coughlin void BlockCall::getExtraInvalidatedValues(ValueList &Values,
6034f770deeSDevin Coughlin                   RegionAndSymbolInvalidationTraits *ETraits) const {
6044f7df9beSJordan Rose   // FIXME: This also needs to invalidate captured globals.
6054f7df9beSJordan Rose   if (const MemRegion *R = getBlockRegion())
60660bf5f45SAnna Zaks     Values.push_back(loc::MemRegionVal(R));
6074f7df9beSJordan Rose }
6084f7df9beSJordan Rose 
60942e8d649SJordan Rose void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
61042e8d649SJordan Rose                                              BindingsTy &Bindings) const {
61142e8d649SJordan Rose   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
612ebeed880SDevin Coughlin   ArrayRef<ParmVarDecl*> Params;
613ebeed880SDevin Coughlin   if (isConversionFromLambda()) {
614ebeed880SDevin Coughlin     auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
615ebeed880SDevin Coughlin     Params = LambdaOperatorDecl->parameters();
616ebeed880SDevin Coughlin 
617ebeed880SDevin Coughlin     // For blocks converted from a C++ lambda, the callee declaration is the
6185690454bSSanjay Patel     // operator() method on the lambda so we bind "this" to
619ebeed880SDevin Coughlin     // the lambda captured by the block.
620ebeed880SDevin Coughlin     const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
621ebeed880SDevin Coughlin     SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
622ebeed880SDevin Coughlin     Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
623ebeed880SDevin Coughlin     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
624ebeed880SDevin Coughlin   } else {
625ebeed880SDevin Coughlin     Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
626ebeed880SDevin Coughlin   }
627ebeed880SDevin Coughlin 
62842e8d649SJordan Rose   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
629ebeed880SDevin Coughlin                                Params);
63042e8d649SJordan Rose }
63142e8d649SJordan Rose 
63242e8d649SJordan Rose 
6334f7df9beSJordan Rose SVal CXXConstructorCall::getCXXThisVal() const {
6344f7df9beSJordan Rose   if (Data)
6354f7df9beSJordan Rose     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
6364f7df9beSJordan Rose   return UnknownVal();
6374f7df9beSJordan Rose }
6384f7df9beSJordan Rose 
6394f770deeSDevin Coughlin void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
6404f770deeSDevin Coughlin                            RegionAndSymbolInvalidationTraits *ETraits) const {
6414f7df9beSJordan Rose   if (Data)
64260bf5f45SAnna Zaks     Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
6434f7df9beSJordan Rose }
6444f7df9beSJordan Rose 
64542e8d649SJordan Rose void CXXConstructorCall::getInitialStackFrameContents(
64642e8d649SJordan Rose                                              const StackFrameContext *CalleeCtx,
64742e8d649SJordan Rose                                              BindingsTy &Bindings) const {
64842e8d649SJordan Rose   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
64942e8d649SJordan Rose 
65042e8d649SJordan Rose   SVal ThisVal = getCXXThisVal();
65142e8d649SJordan Rose   if (!ThisVal.isUnknown()) {
65242e8d649SJordan Rose     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
65342e8d649SJordan Rose     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
65442e8d649SJordan Rose     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
65542e8d649SJordan Rose     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
65642e8d649SJordan Rose   }
65742e8d649SJordan Rose }
65842e8d649SJordan Rose 
6594f7df9beSJordan Rose SVal CXXDestructorCall::getCXXThisVal() const {
6604f7df9beSJordan Rose   if (Data)
6612bc9674bSJordan Rose     return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
6624f7df9beSJordan Rose   return UnknownVal();
6634f7df9beSJordan Rose }
6644f7df9beSJordan Rose 
665089c5510STed Kremenek RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
6662bc9674bSJordan Rose   // Base destructors are always called non-virtually.
6672bc9674bSJordan Rose   // Skip CXXInstanceCall's devirtualization logic in this case.
6682bc9674bSJordan Rose   if (isBaseDestructor())
669089c5510STed Kremenek     return AnyFunctionCall::getRuntimeDefinition();
6702bc9674bSJordan Rose 
671089c5510STed Kremenek   return CXXInstanceCall::getRuntimeDefinition();
6722bc9674bSJordan Rose }
6732bc9674bSJordan Rose 
6742ff16004STed Kremenek ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
67542e8d649SJordan Rose   const ObjCMethodDecl *D = getDecl();
6764f7df9beSJordan Rose   if (!D)
6775fc8fc2dSCraig Topper     return None;
6782ff16004STed Kremenek   return D->parameters();
6794f7df9beSJordan Rose }
6804f7df9beSJordan Rose 
681069a1073SDevin Coughlin void ObjCMethodCall::getExtraInvalidatedValues(
682069a1073SDevin Coughlin     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
683069a1073SDevin Coughlin 
684069a1073SDevin Coughlin   // If the method call is a setter for property known to be backed by
685069a1073SDevin Coughlin   // an instance variable, don't invalidate the entire receiver, just
686069a1073SDevin Coughlin   // the storage for that instance variable.
687069a1073SDevin Coughlin   if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
688069a1073SDevin Coughlin     if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
689069a1073SDevin Coughlin       SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
690069a1073SDevin Coughlin       const MemRegion *IvarRegion = IvarLVal.getAsRegion();
691069a1073SDevin Coughlin       ETraits->setTrait(
692069a1073SDevin Coughlin           IvarRegion,
693069a1073SDevin Coughlin           RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
694069a1073SDevin Coughlin       ETraits->setTrait(IvarRegion,
695069a1073SDevin Coughlin                         RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
696069a1073SDevin Coughlin       Values.push_back(IvarLVal);
697069a1073SDevin Coughlin       return;
698069a1073SDevin Coughlin     }
699069a1073SDevin Coughlin   }
700069a1073SDevin Coughlin 
70160bf5f45SAnna Zaks   Values.push_back(getReceiverSVal());
7024f7df9beSJordan Rose }
7034f7df9beSJordan Rose 
7043d5d3d3eSAnna Zaks SVal ObjCMethodCall::getSelfSVal() const {
7053d5d3d3eSAnna Zaks   const LocationContext *LCtx = getLocationContext();
7063d5d3d3eSAnna Zaks   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
7073d5d3d3eSAnna Zaks   if (!SelfDecl)
7083d5d3d3eSAnna Zaks     return SVal();
7093d5d3d3eSAnna Zaks   return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
7103d5d3d3eSAnna Zaks }
7113d5d3d3eSAnna Zaks 
7124f7df9beSJordan Rose SVal ObjCMethodCall::getReceiverSVal() const {
7134f7df9beSJordan Rose   // FIXME: Is this the best way to handle class receivers?
7144f7df9beSJordan Rose   if (!isInstanceMessage())
7154f7df9beSJordan Rose     return UnknownVal();
7164f7df9beSJordan Rose 
717472dbcf1SAnna Zaks   if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
718472dbcf1SAnna Zaks     return getSVal(RecE);
7194f7df9beSJordan Rose 
7204f7df9beSJordan Rose   // An instance message with no expression means we are sending to super.
7214f7df9beSJordan Rose   // In this case the object reference is the same as 'self'.
7223d5d3d3eSAnna Zaks   assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7233d5d3d3eSAnna Zaks   SVal SelfVal = getSelfSVal();
7243d5d3d3eSAnna Zaks   assert(SelfVal.isValid() && "Calling super but not in ObjC method");
7253d5d3d3eSAnna Zaks   return SelfVal;
7263d5d3d3eSAnna Zaks }
7273d5d3d3eSAnna Zaks 
7283d5d3d3eSAnna Zaks bool ObjCMethodCall::isReceiverSelfOrSuper() const {
7293d5d3d3eSAnna Zaks   if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
7303d5d3d3eSAnna Zaks       getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
7313d5d3d3eSAnna Zaks       return true;
7323d5d3d3eSAnna Zaks 
7333d5d3d3eSAnna Zaks   if (!isInstanceMessage())
7343d5d3d3eSAnna Zaks     return false;
7353d5d3d3eSAnna Zaks 
7363d5d3d3eSAnna Zaks   SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
7373d5d3d3eSAnna Zaks 
7383d5d3d3eSAnna Zaks   return (RecVal == getSelfSVal());
7394f7df9beSJordan Rose }
7404f7df9beSJordan Rose 
7414f7df9beSJordan Rose SourceRange ObjCMethodCall::getSourceRange() const {
7424f7df9beSJordan Rose   switch (getMessageKind()) {
7434f7df9beSJordan Rose   case OCM_Message:
7444f7df9beSJordan Rose     return getOriginExpr()->getSourceRange();
7454f7df9beSJordan Rose   case OCM_PropertyAccess:
7464f7df9beSJordan Rose   case OCM_Subscript:
7474f7df9beSJordan Rose     return getContainingPseudoObjectExpr()->getSourceRange();
7484f7df9beSJordan Rose   }
7494f7df9beSJordan Rose   llvm_unreachable("unknown message kind");
7504f7df9beSJordan Rose }
7514f7df9beSJordan Rose 
7524f7df9beSJordan Rose typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
7534f7df9beSJordan Rose 
7544f7df9beSJordan Rose const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
7550dbb783cSCraig Topper   assert(Data && "Lazy lookup not yet performed.");
7564f7df9beSJordan Rose   assert(getMessageKind() != OCM_Message && "Explicit message send.");
7574f7df9beSJordan Rose   return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
7584f7df9beSJordan Rose }
7594f7df9beSJordan Rose 
760069a1073SDevin Coughlin static const Expr *
761069a1073SDevin Coughlin getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
762069a1073SDevin Coughlin   const Expr *Syntactic = POE->getSyntacticForm();
763069a1073SDevin Coughlin 
764069a1073SDevin Coughlin   // This handles the funny case of assigning to the result of a getter.
765069a1073SDevin Coughlin   // This can happen if the getter returns a non-const reference.
766069a1073SDevin Coughlin   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
767069a1073SDevin Coughlin     Syntactic = BO->getLHS();
768069a1073SDevin Coughlin 
769069a1073SDevin Coughlin   return Syntactic;
770069a1073SDevin Coughlin }
771069a1073SDevin Coughlin 
7724f7df9beSJordan Rose ObjCMessageKind ObjCMethodCall::getMessageKind() const {
7730dbb783cSCraig Topper   if (!Data) {
774226a56faSAnna Zaks 
775226a56faSAnna Zaks     // Find the parent, ignoring implicit casts.
7764f7df9beSJordan Rose     ParentMap &PM = getLocationContext()->getParentMap();
7775770c038SJordan Rose     const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
778226a56faSAnna Zaks 
779226a56faSAnna Zaks     // Check if parent is a PseudoObjectExpr.
7804f7df9beSJordan Rose     if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
781069a1073SDevin Coughlin       const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
7824f7df9beSJordan Rose 
7834f7df9beSJordan Rose       ObjCMessageKind K;
7844f7df9beSJordan Rose       switch (Syntactic->getStmtClass()) {
7854f7df9beSJordan Rose       case Stmt::ObjCPropertyRefExprClass:
7864f7df9beSJordan Rose         K = OCM_PropertyAccess;
7874f7df9beSJordan Rose         break;
7884f7df9beSJordan Rose       case Stmt::ObjCSubscriptRefExprClass:
7894f7df9beSJordan Rose         K = OCM_Subscript;
7904f7df9beSJordan Rose         break;
7914f7df9beSJordan Rose       default:
7924f7df9beSJordan Rose         // FIXME: Can this ever happen?
7934f7df9beSJordan Rose         K = OCM_Message;
7944f7df9beSJordan Rose         break;
7954f7df9beSJordan Rose       }
7964f7df9beSJordan Rose 
7974f7df9beSJordan Rose       if (K != OCM_Message) {
7984f7df9beSJordan Rose         const_cast<ObjCMethodCall *>(this)->Data
7994f7df9beSJordan Rose           = ObjCMessageDataTy(POE, K).getOpaqueValue();
8004f7df9beSJordan Rose         assert(getMessageKind() == K);
8014f7df9beSJordan Rose         return K;
8024f7df9beSJordan Rose       }
8034f7df9beSJordan Rose     }
8044f7df9beSJordan Rose 
8054f7df9beSJordan Rose     const_cast<ObjCMethodCall *>(this)->Data
8060dbb783cSCraig Topper       = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
8074f7df9beSJordan Rose     assert(getMessageKind() == OCM_Message);
8084f7df9beSJordan Rose     return OCM_Message;
8094f7df9beSJordan Rose   }
8104f7df9beSJordan Rose 
8114f7df9beSJordan Rose   ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
8124f7df9beSJordan Rose   if (!Info.getPointer())
8134f7df9beSJordan Rose     return OCM_Message;
8144f7df9beSJordan Rose   return static_cast<ObjCMessageKind>(Info.getInt());
8154f7df9beSJordan Rose }
8164f7df9beSJordan Rose 
817069a1073SDevin Coughlin const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
818069a1073SDevin Coughlin   // Look for properties accessed with property syntax (foo.bar = ...)
819069a1073SDevin Coughlin   if ( getMessageKind() == OCM_PropertyAccess) {
820069a1073SDevin Coughlin     const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
821069a1073SDevin Coughlin     assert(POE && "Property access without PseudoObjectExpr?");
822069a1073SDevin Coughlin 
823069a1073SDevin Coughlin     const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
824069a1073SDevin Coughlin     auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
825069a1073SDevin Coughlin 
826069a1073SDevin Coughlin     if (RefExpr->isExplicitProperty())
827069a1073SDevin Coughlin       return RefExpr->getExplicitProperty();
828069a1073SDevin Coughlin   }
829069a1073SDevin Coughlin 
830069a1073SDevin Coughlin   // Look for properties accessed with method syntax ([foo setBar:...]).
831069a1073SDevin Coughlin   const ObjCMethodDecl *MD = getDecl();
832069a1073SDevin Coughlin   if (!MD || !MD->isPropertyAccessor())
833069a1073SDevin Coughlin     return nullptr;
834069a1073SDevin Coughlin 
835069a1073SDevin Coughlin   // Note: This is potentially quite slow.
836069a1073SDevin Coughlin   return MD->findPropertyDecl();
837069a1073SDevin Coughlin }
838920af014SAnna Zaks 
839920af014SAnna Zaks bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
840920af014SAnna Zaks                                              Selector Sel) const {
841920af014SAnna Zaks   assert(IDecl);
842920af014SAnna Zaks   const SourceManager &SM =
843920af014SAnna Zaks     getState()->getStateManager().getContext().getSourceManager();
844920af014SAnna Zaks 
845920af014SAnna Zaks   // If the class interface is declared inside the main file, assume it is not
846920af014SAnna Zaks   // subcassed.
847920af014SAnna Zaks   // TODO: It could actually be subclassed if the subclass is private as well.
848920af014SAnna Zaks   // This is probably very rare.
849920af014SAnna Zaks   SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
8505ba37d52SEli Friedman   if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
851920af014SAnna Zaks     return false;
852920af014SAnna Zaks 
8536ddb6b1aSAnna Zaks   // Assume that property accessors are not overridden.
8546ddb6b1aSAnna Zaks   if (getMessageKind() == OCM_PropertyAccess)
8556ddb6b1aSAnna Zaks     return false;
856920af014SAnna Zaks 
857920af014SAnna Zaks   // We assume that if the method is public (declared outside of main file) or
858920af014SAnna Zaks   // has a parent which publicly declares the method, the method could be
859920af014SAnna Zaks   // overridden in a subclass.
860920af014SAnna Zaks 
861920af014SAnna Zaks   // Find the first declaration in the class hierarchy that declares
862920af014SAnna Zaks   // the selector.
8630dbb783cSCraig Topper   ObjCMethodDecl *D = nullptr;
864920af014SAnna Zaks   while (true) {
865920af014SAnna Zaks     D = IDecl->lookupMethod(Sel, true);
866920af014SAnna Zaks 
867920af014SAnna Zaks     // Cannot find a public definition.
868920af014SAnna Zaks     if (!D)
869920af014SAnna Zaks       return false;
870920af014SAnna Zaks 
871920af014SAnna Zaks     // If outside the main file,
8725ba37d52SEli Friedman     if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
873920af014SAnna Zaks       return true;
874920af014SAnna Zaks 
875920af014SAnna Zaks     if (D->isOverriding()) {
876920af014SAnna Zaks       // Search in the superclass on the next iteration.
877920af014SAnna Zaks       IDecl = D->getClassInterface();
878920af014SAnna Zaks       if (!IDecl)
879920af014SAnna Zaks         return false;
880920af014SAnna Zaks 
881920af014SAnna Zaks       IDecl = IDecl->getSuperClass();
882920af014SAnna Zaks       if (!IDecl)
883920af014SAnna Zaks         return false;
884920af014SAnna Zaks 
885920af014SAnna Zaks       continue;
886920af014SAnna Zaks     }
887920af014SAnna Zaks 
888920af014SAnna Zaks     return false;
889920af014SAnna Zaks   };
890920af014SAnna Zaks 
891920af014SAnna Zaks   llvm_unreachable("The while loop should always terminate.");
892920af014SAnna Zaks }
893920af014SAnna Zaks 
894089c5510STed Kremenek RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
89563282aefSAnna Zaks   const ObjCMessageExpr *E = getOriginExpr();
89663282aefSAnna Zaks   assert(E);
8975808eb80SAnna Zaks   Selector Sel = E->getSelector();
8984f7df9beSJordan Rose 
89963282aefSAnna Zaks   if (E->isInstanceMessage()) {
9005808eb80SAnna Zaks 
9012c4555adSEric Christopher     // Find the receiver type.
9020dbb783cSCraig Topper     const ObjCObjectPointerType *ReceiverT = nullptr;
90375f49a9cSAnna Zaks     bool CanBeSubClassed = false;
9045808eb80SAnna Zaks     QualType SupersType = E->getSuperType();
9050dbb783cSCraig Topper     const MemRegion *Receiver = nullptr;
906123af098SAnna Zaks 
9075808eb80SAnna Zaks     if (!SupersType.isNull()) {
908123af098SAnna Zaks       // Super always means the type of immediate predecessor to the method
909123af098SAnna Zaks       // where the call occurs.
91075930b65SAnna Zaks       ReceiverT = cast<ObjCObjectPointerType>(SupersType);
9115808eb80SAnna Zaks     } else {
912123af098SAnna Zaks       Receiver = getReceiverSVal().getAsRegion();
9136a97d92eSJordan Rose       if (!Receiver)
914123af098SAnna Zaks         return RuntimeDefinition();
9156a97d92eSJordan Rose 
9164df9d812SGabor Horvath       DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
91775f49a9cSAnna Zaks       QualType DynType = DTI.getType();
91875f49a9cSAnna Zaks       CanBeSubClassed = DTI.canBeASubClass();
91975930b65SAnna Zaks       ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
92075f49a9cSAnna Zaks 
92175f49a9cSAnna Zaks       if (ReceiverT && CanBeSubClassed)
92275f49a9cSAnna Zaks         if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
92375f49a9cSAnna Zaks           if (!canBeOverridenInSubclass(IDecl, Sel))
92475f49a9cSAnna Zaks             CanBeSubClassed = false;
9254f7df9beSJordan Rose     }
9264f7df9beSJordan Rose 
9275808eb80SAnna Zaks     // Lookup the method implementation.
9285808eb80SAnna Zaks     if (ReceiverT)
929920af014SAnna Zaks       if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
930245e45afSTed Kremenek         // Repeatedly calling lookupPrivateMethod() is expensive, especially
931245e45afSTed Kremenek         // when in many cases it returns null.  We cache the results so
932245e45afSTed Kremenek         // that repeated queries on the same ObjCIntefaceDecl and Selector
933245e45afSTed Kremenek         // don't incur the same cost.  On some test cases, we can see the
934245e45afSTed Kremenek         // same query being issued thousands of times.
935245e45afSTed Kremenek         //
936245e45afSTed Kremenek         // NOTE: This cache is essentially a "global" variable, but it
937245e45afSTed Kremenek         // only gets lazily created when we get here.  The value of the
938245e45afSTed Kremenek         // cache probably comes from it being global across ExprEngines,
939245e45afSTed Kremenek         // where the same queries may get issued.  If we are worried about
940245e45afSTed Kremenek         // concurrency, or possibly loading/unloading ASTs, etc., we may
941245e45afSTed Kremenek         // need to revisit this someday.  In terms of memory, this table
942245e45afSTed Kremenek         // stays around until clang quits, which also may be bad if we
943245e45afSTed Kremenek         // need to release memory.
944245e45afSTed Kremenek         typedef std::pair<const ObjCInterfaceDecl*, Selector>
945245e45afSTed Kremenek                 PrivateMethodKey;
946245e45afSTed Kremenek         typedef llvm::DenseMap<PrivateMethodKey,
94705785d16SDavid Blaikie                                Optional<const ObjCMethodDecl *> >
948245e45afSTed Kremenek                 PrivateMethodCache;
949245e45afSTed Kremenek 
950245e45afSTed Kremenek         static PrivateMethodCache PMC;
95105785d16SDavid Blaikie         Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
952245e45afSTed Kremenek 
953245e45afSTed Kremenek         // Query lookupPrivateMethod() if the cache does not hit.
9541a866cd5SJordan Rose         if (!Val.hasValue()) {
955245e45afSTed Kremenek           Val = IDecl->lookupPrivateMethod(Sel);
956245e45afSTed Kremenek 
9571a866cd5SJordan Rose           // If the method is a property accessor, we should try to "inline" it
9581a866cd5SJordan Rose           // even if we don't actually have an implementation.
9591a866cd5SJordan Rose           if (!*Val)
9601a866cd5SJordan Rose             if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
961c239dd13SDevin Coughlin               if (CompileTimeMD->isPropertyAccessor()) {
962c239dd13SDevin Coughlin                 if (!CompileTimeMD->getSelfDecl() &&
963c239dd13SDevin Coughlin                     isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
964c239dd13SDevin Coughlin                   // If the method is an accessor in a category, and it doesn't
965c239dd13SDevin Coughlin                   // have a self declaration, first
966c239dd13SDevin Coughlin                   // try to find the method in a class extension. This
967c239dd13SDevin Coughlin                   // works around a bug in Sema where multiple accessors
968c239dd13SDevin Coughlin                   // are synthesized for properties in class
969c239dd13SDevin Coughlin                   // extensions that are redeclared in a category and the
970c239dd13SDevin Coughlin                   // the implicit parameters are not filled in for
971c239dd13SDevin Coughlin                   // the method on the category.
972c239dd13SDevin Coughlin                   // This ensures we find the accessor in the extension, which
973c239dd13SDevin Coughlin                   // has the implicit parameters filled in.
974c239dd13SDevin Coughlin                   auto *ID = CompileTimeMD->getClassInterface();
975c239dd13SDevin Coughlin                   for (auto *CatDecl : ID->visible_extensions()) {
976c239dd13SDevin Coughlin                     Val = CatDecl->getMethod(Sel,
977c239dd13SDevin Coughlin                                              CompileTimeMD->isInstanceMethod());
978c239dd13SDevin Coughlin                     if (*Val)
979c239dd13SDevin Coughlin                       break;
980c239dd13SDevin Coughlin                   }
981c239dd13SDevin Coughlin                 }
982c239dd13SDevin Coughlin                 if (!*Val)
9831a866cd5SJordan Rose                   Val = IDecl->lookupInstanceMethod(Sel);
9841a866cd5SJordan Rose               }
985c239dd13SDevin Coughlin         }
9861a866cd5SJordan Rose 
987245e45afSTed Kremenek         const ObjCMethodDecl *MD = Val.getValue();
98875f49a9cSAnna Zaks         if (CanBeSubClassed)
98975f49a9cSAnna Zaks           return RuntimeDefinition(MD, Receiver);
990920af014SAnna Zaks         else
9910dbb783cSCraig Topper           return RuntimeDefinition(MD, nullptr);
992920af014SAnna Zaks       }
9935808eb80SAnna Zaks 
99463282aefSAnna Zaks   } else {
99563282aefSAnna Zaks     // This is a class method.
99663282aefSAnna Zaks     // If we have type info for the receiver class, we are calling via
99763282aefSAnna Zaks     // class name.
99863282aefSAnna Zaks     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
99963282aefSAnna Zaks       // Find/Return the method implementation.
100085383182SAnna Zaks       return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
10014f7df9beSJordan Rose     }
100263282aefSAnna Zaks   }
100363282aefSAnna Zaks 
1004123af098SAnna Zaks   return RuntimeDefinition();
10054f7df9beSJordan Rose }
10064f7df9beSJordan Rose 
1007514f9354SJordan Rose bool ObjCMethodCall::argumentsMayEscape() const {
1008514f9354SJordan Rose   if (isInSystemHeader() && !isInstanceMessage()) {
1009514f9354SJordan Rose     Selector Sel = getSelector();
1010514f9354SJordan Rose     if (Sel.getNumArgs() == 1 &&
1011514f9354SJordan Rose         Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1012514f9354SJordan Rose       return true;
1013514f9354SJordan Rose   }
1014514f9354SJordan Rose 
1015514f9354SJordan Rose   return CallEvent::argumentsMayEscape();
1016514f9354SJordan Rose }
1017514f9354SJordan Rose 
101842e8d649SJordan Rose void ObjCMethodCall::getInitialStackFrameContents(
101942e8d649SJordan Rose                                              const StackFrameContext *CalleeCtx,
102042e8d649SJordan Rose                                              BindingsTy &Bindings) const {
102142e8d649SJordan Rose   const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
102242e8d649SJordan Rose   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
102342e8d649SJordan Rose   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
10242ff16004STed Kremenek                                D->parameters());
102542e8d649SJordan Rose 
102642e8d649SJordan Rose   SVal SelfVal = getReceiverSVal();
102742e8d649SJordan Rose   if (!SelfVal.isUnknown()) {
102842e8d649SJordan Rose     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
102942e8d649SJordan Rose     MemRegionManager &MRMgr = SVB.getRegionManager();
103042e8d649SJordan Rose     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
103142e8d649SJordan Rose     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
103242e8d649SJordan Rose   }
103342e8d649SJordan Rose }
103442e8d649SJordan Rose 
1035ce6c99a5SJordan Rose CallEventRef<>
1036fcd016e5SJordan Rose CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1037fcd016e5SJordan Rose                                 const LocationContext *LCtx) {
1038fcd016e5SJordan Rose   if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1039fcd016e5SJordan Rose     return create<CXXMemberCall>(MCE, State, LCtx);
1040fcd016e5SJordan Rose 
1041fcd016e5SJordan Rose   if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1042fcd016e5SJordan Rose     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1043fcd016e5SJordan Rose     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1044fcd016e5SJordan Rose       if (MD->isInstance())
1045fcd016e5SJordan Rose         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1046fcd016e5SJordan Rose 
1047fcd016e5SJordan Rose   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1048fcd016e5SJordan Rose     return create<BlockCall>(CE, State, LCtx);
1049fcd016e5SJordan Rose   }
1050fcd016e5SJordan Rose 
1051fcd016e5SJordan Rose   // Otherwise, it's a normal function call, static member function call, or
1052fcd016e5SJordan Rose   // something we can't reason about.
10532a833ca5SJordan Rose   return create<SimpleFunctionCall>(CE, State, LCtx);
1054fcd016e5SJordan Rose }
1055c2d249ceSJordan Rose 
1056c2d249ceSJordan Rose 
1057c2d249ceSJordan Rose CallEventRef<>
1058c2d249ceSJordan Rose CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1059c2d249ceSJordan Rose                             ProgramStateRef State) {
1060c2d249ceSJordan Rose   const LocationContext *ParentCtx = CalleeCtx->getParent();
1061c2d249ceSJordan Rose   const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
1062c2d249ceSJordan Rose   assert(CallerCtx && "This should not be used for top-level stack frames");
1063c2d249ceSJordan Rose 
1064c2d249ceSJordan Rose   const Stmt *CallSite = CalleeCtx->getCallSite();
1065c2d249ceSJordan Rose 
1066c2d249ceSJordan Rose   if (CallSite) {
1067c2d249ceSJordan Rose     if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
1068c2d249ceSJordan Rose       return getSimpleCall(CE, State, CallerCtx);
1069c2d249ceSJordan Rose 
1070c2d249ceSJordan Rose     switch (CallSite->getStmtClass()) {
10718d48938bSJordan Rose     case Stmt::CXXConstructExprClass:
10728d48938bSJordan Rose     case Stmt::CXXTemporaryObjectExprClass: {
1073c2d249ceSJordan Rose       SValBuilder &SVB = State->getStateManager().getSValBuilder();
1074c2d249ceSJordan Rose       const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1075c2d249ceSJordan Rose       Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1076c2d249ceSJordan Rose       SVal ThisVal = State->getSVal(ThisPtr);
1077c2d249ceSJordan Rose 
1078c2d249ceSJordan Rose       return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
1079c2d249ceSJordan Rose                                    ThisVal.getAsRegion(), State, CallerCtx);
1080c2d249ceSJordan Rose     }
1081c2d249ceSJordan Rose     case Stmt::CXXNewExprClass:
1082c2d249ceSJordan Rose       return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
1083c2d249ceSJordan Rose     case Stmt::ObjCMessageExprClass:
1084c2d249ceSJordan Rose       return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
1085c2d249ceSJordan Rose                                State, CallerCtx);
1086c2d249ceSJordan Rose     default:
1087c2d249ceSJordan Rose       llvm_unreachable("This is not an inlineable statement.");
1088c2d249ceSJordan Rose     }
1089c2d249ceSJordan Rose   }
1090c2d249ceSJordan Rose 
1091c2d249ceSJordan Rose   // Fall back to the CFG. The only thing we haven't handled yet is
1092c2d249ceSJordan Rose   // destructors, though this could change in the future.
1093c2d249ceSJordan Rose   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1094c2d249ceSJordan Rose   CFGElement E = (*B)[CalleeCtx->getIndex()];
10952a01f5d4SDavid Blaikie   assert(E.getAs<CFGImplicitDtor>() &&
10962a01f5d4SDavid Blaikie          "All other CFG elements should have exprs");
10972a01f5d4SDavid Blaikie   assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
1098c2d249ceSJordan Rose 
1099c2d249ceSJordan Rose   SValBuilder &SVB = State->getStateManager().getSValBuilder();
1100c2d249ceSJordan Rose   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1101c2d249ceSJordan Rose   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1102c2d249ceSJordan Rose   SVal ThisVal = State->getSVal(ThisPtr);
1103c2d249ceSJordan Rose 
1104c2d249ceSJordan Rose   const Stmt *Trigger;
110500be69abSDavid Blaikie   if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
110600be69abSDavid Blaikie     Trigger = AutoDtor->getTriggerStmt();
11071ccc43d5SJordan Rose   else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
11081ccc43d5SJordan Rose     Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
1109c2d249ceSJordan Rose   else
1110c2d249ceSJordan Rose     Trigger = Dtor->getBody();
1111c2d249ceSJordan Rose 
1112c2d249ceSJordan Rose   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
111300be69abSDavid Blaikie                               E.getAs<CFGBaseDtor>().hasValue(), State,
111400be69abSDavid Blaikie                               CallerCtx);
1115c2d249ceSJordan Rose }
1116