1 //===- Calls.cpp - Wrapper for all function and method calls ------*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
14 //===----------------------------------------------------------------------===//
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"
24 using namespace clang;
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();
32 ASTContext &Ctx = getState()->getStateManager().getContext();
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
37 switch (E->getValueKind()) {
39 ResultTy = Ctx.getLValueReferenceType(ResultTy);
42 ResultTy = Ctx.getRValueReferenceType(ResultTy);
45 // No adjustment is necessary.
52 static bool isCallbackArg(SVal V, QualType T) {
53 // If the parameter is 0, it's harmless.
54 if (V.isZeroConstant())
57 // If a parameter is a block or a callback, assume it can modify pointer.
58 if (T->isBlockPointerType() ||
59 T->isFunctionPointerType() ||
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.
66 if (T->isAnyPointerType() || T->isReferenceType())
67 T = T->getPointeeType();
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();
73 QualType FieldT = I->getType();
74 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
82 bool CallEvent::hasNonZeroCallbackArg() const {
83 unsigned NumOfArgs = getNumArgs();
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.
91 for (CallEvent::param_type_iterator I = param_type_begin(),
93 I != E && Idx < NumOfArgs; ++I, ++Idx) {
97 if (isCallbackArg(getArgSVal(Idx), *I))
104 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
105 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
109 return CheckerContext::isCLibraryFunction(FD, FunctionName);
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())
118 if (!PointeeTy.isConstQualified())
120 if (PointeeTy->isAnyPointerType())
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, 4> &PreserveArgs,
129 const CallEvent &Call) {
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);
139 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
140 ProgramStateRef Orig) const {
141 ProgramStateRef Result = (Orig ? Orig : getState());
143 SmallVector<SVal, 8> ConstValues;
144 SmallVector<SVal, 8> ValuesToInvalidate;
146 getExtraInvalidatedValues(ValuesToInvalidate);
148 // Indexes of arguments whose values will be preserved by the call.
149 llvm::SmallSet<unsigned, 4> PreserveArgs;
150 if (!argumentsMayEscape())
151 findPtrToConstParams(PreserveArgs, *this);
153 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
154 // Mark this region for invalidation. We batch invalidate regions
155 // below for efficiency.
156 if (PreserveArgs.count(Idx))
157 ConstValues.push_back(getArgSVal(Idx));
159 ValuesToInvalidate.push_back(getArgSVal(Idx));
162 // Invalidate designated regions using the batch invalidation API.
163 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
165 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
166 BlockCount, getLocationContext(),
167 /*CausedByPointerEscape*/ true,
168 /*Symbols=*/0, this, ConstValues);
171 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
172 const ProgramPointTag *Tag) const {
173 if (const Expr *E = getOriginExpr()) {
175 return PreStmt(E, getLocationContext(), Tag);
176 return PostStmt(E, getLocationContext(), Tag);
179 const Decl *D = getDecl();
180 assert(D && "Cannot get a program point without a statement or decl");
182 SourceLocation Loc = getSourceRange().getBegin();
184 return PreImplicitCall(D, Loc, getLocationContext(), Tag);
185 return PostImplicitCall(D, Loc, getLocationContext(), Tag);
188 SVal CallEvent::getArgSVal(unsigned Index) const {
189 const Expr *ArgE = getArgExpr(Index);
192 return getSVal(ArgE);
195 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
196 const Expr *ArgE = getArgExpr(Index);
198 return SourceRange();
199 return ArgE->getSourceRange();
202 SVal CallEvent::getReturnValue() const {
203 const Expr *E = getOriginExpr();
205 return UndefinedVal();
209 void CallEvent::dump() const {
213 void CallEvent::dump(raw_ostream &Out) const {
214 ASTContext &Ctx = getState()->getStateManager().getContext();
215 if (const Expr *E = getOriginExpr()) {
216 E->printPretty(Out, 0, Ctx.getPrintingPolicy());
221 if (const Decl *D = getDecl()) {
223 D->print(Out, Ctx.getPrintingPolicy());
227 // FIXME: a string representation of the kind would be nice.
228 Out << "Unknown call (type " << getKind() << ")";
232 bool CallEvent::isCallStmt(const Stmt *S) {
233 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
234 || isa<CXXConstructExpr>(S)
235 || isa<CXXNewExpr>(S);
238 QualType CallEvent::getDeclaredResultType(const Decl *D) {
240 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
241 return FD->getResultType();
242 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
243 return MD->getResultType();
244 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
245 // Blocks are difficult because the return type may not be stored in the
246 // BlockDecl itself. The AST should probably be enhanced, but for now we
247 // just do what we can.
248 QualType Ty = BD->getSignatureAsWritten()->getType();
249 if (const FunctionType *FT = Ty->getAs<FunctionType>())
250 if (!FT->getResultType()->isDependentType())
251 return FT->getResultType();
259 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
260 CallEvent::BindingsTy &Bindings,
262 const CallEvent &Call,
263 CallEvent::param_iterator I,
264 CallEvent::param_iterator E) {
265 MemRegionManager &MRMgr = SVB.getRegionManager();
268 for (; I != E; ++I, ++Idx) {
269 const ParmVarDecl *ParamDecl = *I;
270 assert(ParamDecl && "Formal parameter has no decl?");
272 SVal ArgVal = Call.getArgSVal(Idx);
273 if (!ArgVal.isUnknown()) {
274 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
275 Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
279 // FIXME: Variadic arguments are not handled at all right now.
283 CallEvent::param_iterator AnyFunctionCall::param_begin() const {
284 const FunctionDecl *D = getDecl();
288 return D->param_begin();
291 CallEvent::param_iterator AnyFunctionCall::param_end() const {
292 const FunctionDecl *D = getDecl();
296 return D->param_end();
299 void AnyFunctionCall::getInitialStackFrameContents(
300 const StackFrameContext *CalleeCtx,
301 BindingsTy &Bindings) const {
302 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
303 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
304 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
305 D->param_begin(), D->param_end());
308 bool AnyFunctionCall::argumentsMayEscape() const {
309 if (hasNonZeroCallbackArg())
312 const FunctionDecl *D = getDecl();
316 const IdentifierInfo *II = D->getIdentifier();
320 // This set of "escaping" APIs is
322 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
323 // value into thread local storage. The value can later be retrieved with
324 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
325 // parameter is 'const void *', the region escapes through the call.
326 if (II->isStr("pthread_setspecific"))
329 // - xpc_connection_set_context stores a value which can be retrieved later
330 // with xpc_connection_get_context.
331 if (II->isStr("xpc_connection_set_context"))
334 // - funopen - sets a buffer for future IO calls.
335 if (II->isStr("funopen"))
338 StringRef FName = II->getName();
340 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
341 // buffer even if it is const.
342 if (FName.endswith("NoCopy"))
345 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
346 // be deallocated by NSMapRemove.
347 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
350 // - Many CF containers allow objects to escape through custom
351 // allocators/deallocators upon container construction. (PR12101)
352 if (FName.startswith("CF") || FName.startswith("CG")) {
353 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
354 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
355 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
356 StrInStrNoCase(FName, "WithData") != StringRef::npos ||
357 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
358 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
365 const FunctionDecl *SimpleCall::getDecl() const {
366 const FunctionDecl *D = getOriginExpr()->getDirectCallee();
370 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
374 const FunctionDecl *CXXInstanceCall::getDecl() const {
375 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
377 return AnyFunctionCall::getDecl();
379 const FunctionDecl *D = CE->getDirectCallee();
383 return getSVal(CE->getCallee()).getAsFunctionDecl();
386 void CXXInstanceCall::getExtraInvalidatedValues(ValueList &Values) const {
387 Values.push_back(getCXXThisVal());
390 SVal CXXInstanceCall::getCXXThisVal() const {
391 const Expr *Base = getCXXThisExpr();
392 // FIXME: This doesn't handle an overloaded ->* operator.
396 SVal ThisVal = getSVal(Base);
397 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
402 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
403 // Do we have a decl at all?
404 const Decl *D = getDecl();
406 return RuntimeDefinition();
408 // If the method is non-virtual, we know we can inline it.
409 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
410 if (!MD->isVirtual())
411 return AnyFunctionCall::getRuntimeDefinition();
413 // Do we know the implicit 'this' object being called?
414 const MemRegion *R = getCXXThisVal().getAsRegion();
416 return RuntimeDefinition();
418 // Do we know anything about the type of 'this'?
419 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
420 if (!DynType.isValid())
421 return RuntimeDefinition();
423 // Is the type a C++ class? (This is mostly a defensive check.)
424 QualType RegionType = DynType.getType()->getPointeeType();
425 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
427 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
428 if (!RD || !RD->hasDefinition())
429 return RuntimeDefinition();
431 // Find the decl for this method in that class.
432 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
434 // We might not even get the original statically-resolved method due to
435 // some particularly nasty casting (e.g. casts to sister classes).
436 // However, we should at least be able to search up and down our own class
437 // hierarchy, and some real bugs have been caught by checking this.
438 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
440 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
441 // the static type. However, because we currently don't update
442 // DynamicTypeInfo when an object is cast, we can't actually be sure the
443 // DynamicTypeInfo is up to date. This assert should be re-enabled once
444 // this is fixed. <rdar://problem/12287087>
445 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
447 return RuntimeDefinition();
450 // Does the decl that we found have an implementation?
451 const FunctionDecl *Definition;
452 if (!Result->hasBody(Definition))
453 return RuntimeDefinition();
455 // We found a definition. If we're not sure that this devirtualization is
456 // actually what will happen at runtime, make sure to provide the region so
457 // that ExprEngine can decide what to do with it.
458 if (DynType.canBeASubClass())
459 return RuntimeDefinition(Definition, R->StripCasts());
460 return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
463 void CXXInstanceCall::getInitialStackFrameContents(
464 const StackFrameContext *CalleeCtx,
465 BindingsTy &Bindings) const {
466 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
468 // Handle the binding of 'this' in the new stack frame.
469 SVal ThisVal = getCXXThisVal();
470 if (!ThisVal.isUnknown()) {
471 ProgramStateManager &StateMgr = getState()->getStateManager();
472 SValBuilder &SVB = StateMgr.getSValBuilder();
474 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
475 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
477 // If we devirtualized to a different member function, we need to make sure
478 // we have the proper layering of CXXBaseObjectRegions.
479 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
480 ASTContext &Ctx = SVB.getContext();
481 const CXXRecordDecl *Class = MD->getParent();
482 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
484 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
486 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
487 assert(!Failed && "Calling an incorrectly devirtualized method");
490 if (!ThisVal.isUnknown())
491 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
497 const Expr *CXXMemberCall::getCXXThisExpr() const {
498 return getOriginExpr()->getImplicitObjectArgument();
501 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
502 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
503 // id-expression in the class member access expression is a qualified-id,
504 // that function is called. Otherwise, its final overrider in the dynamic type
505 // of the object expression is called.
506 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
507 if (ME->hasQualifier())
508 return AnyFunctionCall::getRuntimeDefinition();
510 return CXXInstanceCall::getRuntimeDefinition();
514 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
515 return getOriginExpr()->getArg(0);
519 const BlockDataRegion *BlockCall::getBlockRegion() const {
520 const Expr *Callee = getOriginExpr()->getCallee();
521 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
523 return dyn_cast_or_null<BlockDataRegion>(DataReg);
526 CallEvent::param_iterator BlockCall::param_begin() const {
527 const BlockDecl *D = getBlockDecl();
530 return D->param_begin();
533 CallEvent::param_iterator BlockCall::param_end() const {
534 const BlockDecl *D = getBlockDecl();
537 return D->param_end();
540 void BlockCall::getExtraInvalidatedValues(ValueList &Values) const {
541 // FIXME: This also needs to invalidate captured globals.
542 if (const MemRegion *R = getBlockRegion())
543 Values.push_back(loc::MemRegionVal(R));
546 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
547 BindingsTy &Bindings) const {
548 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
549 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
550 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
551 D->param_begin(), D->param_end());
555 SVal CXXConstructorCall::getCXXThisVal() const {
557 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
561 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values) const {
563 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
566 void CXXConstructorCall::getInitialStackFrameContents(
567 const StackFrameContext *CalleeCtx,
568 BindingsTy &Bindings) const {
569 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
571 SVal ThisVal = getCXXThisVal();
572 if (!ThisVal.isUnknown()) {
573 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
574 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
575 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
576 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
582 SVal CXXDestructorCall::getCXXThisVal() const {
584 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
588 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
589 // Base destructors are always called non-virtually.
590 // Skip CXXInstanceCall's devirtualization logic in this case.
591 if (isBaseDestructor())
592 return AnyFunctionCall::getRuntimeDefinition();
594 return CXXInstanceCall::getRuntimeDefinition();
598 CallEvent::param_iterator ObjCMethodCall::param_begin() const {
599 const ObjCMethodDecl *D = getDecl();
603 return D->param_begin();
606 CallEvent::param_iterator ObjCMethodCall::param_end() const {
607 const ObjCMethodDecl *D = getDecl();
611 return D->param_end();
615 ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values) const {
616 Values.push_back(getReceiverSVal());
619 SVal ObjCMethodCall::getSelfSVal() const {
620 const LocationContext *LCtx = getLocationContext();
621 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
624 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
627 SVal ObjCMethodCall::getReceiverSVal() const {
628 // FIXME: Is this the best way to handle class receivers?
629 if (!isInstanceMessage())
632 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
633 return getSVal(RecE);
635 // An instance message with no expression means we are sending to super.
636 // In this case the object reference is the same as 'self'.
637 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
638 SVal SelfVal = getSelfSVal();
639 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
643 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
644 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
645 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
648 if (!isInstanceMessage())
651 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
653 return (RecVal == getSelfSVal());
656 SourceRange ObjCMethodCall::getSourceRange() const {
657 switch (getMessageKind()) {
659 return getOriginExpr()->getSourceRange();
660 case OCM_PropertyAccess:
662 return getContainingPseudoObjectExpr()->getSourceRange();
664 llvm_unreachable("unknown message kind");
667 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
669 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
670 assert(Data != 0 && "Lazy lookup not yet performed.");
671 assert(getMessageKind() != OCM_Message && "Explicit message send.");
672 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
675 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
677 ParentMap &PM = getLocationContext()->getParentMap();
678 const Stmt *S = PM.getParent(getOriginExpr());
679 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
680 const Expr *Syntactic = POE->getSyntacticForm();
682 // This handles the funny case of assigning to the result of a getter.
683 // This can happen if the getter returns a non-const reference.
684 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
685 Syntactic = BO->getLHS();
688 switch (Syntactic->getStmtClass()) {
689 case Stmt::ObjCPropertyRefExprClass:
690 K = OCM_PropertyAccess;
692 case Stmt::ObjCSubscriptRefExprClass:
696 // FIXME: Can this ever happen?
701 if (K != OCM_Message) {
702 const_cast<ObjCMethodCall *>(this)->Data
703 = ObjCMessageDataTy(POE, K).getOpaqueValue();
704 assert(getMessageKind() == K);
709 const_cast<ObjCMethodCall *>(this)->Data
710 = ObjCMessageDataTy(0, 1).getOpaqueValue();
711 assert(getMessageKind() == OCM_Message);
715 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
716 if (!Info.getPointer())
718 return static_cast<ObjCMessageKind>(Info.getInt());
722 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
723 Selector Sel) const {
725 const SourceManager &SM =
726 getState()->getStateManager().getContext().getSourceManager();
728 // If the class interface is declared inside the main file, assume it is not
730 // TODO: It could actually be subclassed if the subclass is private as well.
731 // This is probably very rare.
732 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
733 if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
736 // Assume that property accessors are not overridden.
737 if (getMessageKind() == OCM_PropertyAccess)
740 // We assume that if the method is public (declared outside of main file) or
741 // has a parent which publicly declares the method, the method could be
742 // overridden in a subclass.
744 // Find the first declaration in the class hierarchy that declares
746 ObjCMethodDecl *D = 0;
748 D = IDecl->lookupMethod(Sel, true);
750 // Cannot find a public definition.
754 // If outside the main file,
755 if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
758 if (D->isOverriding()) {
759 // Search in the superclass on the next iteration.
760 IDecl = D->getClassInterface();
764 IDecl = IDecl->getSuperClass();
774 llvm_unreachable("The while loop should always terminate.");
777 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
778 const ObjCMessageExpr *E = getOriginExpr();
780 Selector Sel = E->getSelector();
782 if (E->isInstanceMessage()) {
784 // Find the the receiver type.
785 const ObjCObjectPointerType *ReceiverT = 0;
786 bool CanBeSubClassed = false;
787 QualType SupersType = E->getSuperType();
788 const MemRegion *Receiver = 0;
790 if (!SupersType.isNull()) {
791 // Super always means the type of immediate predecessor to the method
792 // where the call occurs.
793 ReceiverT = cast<ObjCObjectPointerType>(SupersType);
795 Receiver = getReceiverSVal().getAsRegion();
797 return RuntimeDefinition();
799 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
800 QualType DynType = DTI.getType();
801 CanBeSubClassed = DTI.canBeASubClass();
802 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
804 if (ReceiverT && CanBeSubClassed)
805 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
806 if (!canBeOverridenInSubclass(IDecl, Sel))
807 CanBeSubClassed = false;
810 // Lookup the method implementation.
812 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
813 // Repeatedly calling lookupPrivateMethod() is expensive, especially
814 // when in many cases it returns null. We cache the results so
815 // that repeated queries on the same ObjCIntefaceDecl and Selector
816 // don't incur the same cost. On some test cases, we can see the
817 // same query being issued thousands of times.
819 // NOTE: This cache is essentially a "global" variable, but it
820 // only gets lazily created when we get here. The value of the
821 // cache probably comes from it being global across ExprEngines,
822 // where the same queries may get issued. If we are worried about
823 // concurrency, or possibly loading/unloading ASTs, etc., we may
824 // need to revisit this someday. In terms of memory, this table
825 // stays around until clang quits, which also may be bad if we
826 // need to release memory.
827 typedef std::pair<const ObjCInterfaceDecl*, Selector>
829 typedef llvm::DenseMap<PrivateMethodKey,
830 Optional<const ObjCMethodDecl *> >
833 static PrivateMethodCache PMC;
834 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
836 // Query lookupPrivateMethod() if the cache does not hit.
838 Val = IDecl->lookupPrivateMethod(Sel);
840 const ObjCMethodDecl *MD = Val.getValue();
842 return RuntimeDefinition(MD, Receiver);
844 return RuntimeDefinition(MD, 0);
848 // This is a class method.
849 // If we have type info for the receiver class, we are calling via
851 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
852 // Find/Return the method implementation.
853 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
857 return RuntimeDefinition();
860 void ObjCMethodCall::getInitialStackFrameContents(
861 const StackFrameContext *CalleeCtx,
862 BindingsTy &Bindings) const {
863 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
864 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
865 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
866 D->param_begin(), D->param_end());
868 SVal SelfVal = getReceiverSVal();
869 if (!SelfVal.isUnknown()) {
870 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
871 MemRegionManager &MRMgr = SVB.getRegionManager();
872 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
873 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
878 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
879 const LocationContext *LCtx) {
880 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
881 return create<CXXMemberCall>(MCE, State, LCtx);
883 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
884 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
885 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
886 if (MD->isInstance())
887 return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
889 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
890 return create<BlockCall>(CE, State, LCtx);
893 // Otherwise, it's a normal function call, static member function call, or
894 // something we can't reason about.
895 return create<FunctionCall>(CE, State, LCtx);
900 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
901 ProgramStateRef State) {
902 const LocationContext *ParentCtx = CalleeCtx->getParent();
903 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
904 assert(CallerCtx && "This should not be used for top-level stack frames");
906 const Stmt *CallSite = CalleeCtx->getCallSite();
909 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
910 return getSimpleCall(CE, State, CallerCtx);
912 switch (CallSite->getStmtClass()) {
913 case Stmt::CXXConstructExprClass:
914 case Stmt::CXXTemporaryObjectExprClass: {
915 SValBuilder &SVB = State->getStateManager().getSValBuilder();
916 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
917 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
918 SVal ThisVal = State->getSVal(ThisPtr);
920 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
921 ThisVal.getAsRegion(), State, CallerCtx);
923 case Stmt::CXXNewExprClass:
924 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
925 case Stmt::ObjCMessageExprClass:
926 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
929 llvm_unreachable("This is not an inlineable statement.");
933 // Fall back to the CFG. The only thing we haven't handled yet is
934 // destructors, though this could change in the future.
935 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
936 CFGElement E = (*B)[CalleeCtx->getIndex()];
937 assert(E.getAs<CFGImplicitDtor>() &&
938 "All other CFG elements should have exprs");
939 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
941 SValBuilder &SVB = State->getStateManager().getSValBuilder();
942 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
943 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
944 SVal ThisVal = State->getSVal(ThisPtr);
947 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
948 Trigger = AutoDtor->getTriggerStmt();
950 Trigger = Dtor->getBody();
952 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
953 E.getAs<CFGBaseDtor>().hasValue(), State,