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/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
18 #include "clang/Analysis/ProgramPoint.h"
19 #include "clang/AST/ParentMap.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringExtras.h"
23 using namespace clang;
26 QualType CallEvent::getResultType() const {
27 const Expr *E = getOriginExpr();
28 assert(E && "Calls without origin expressions do not have results");
29 QualType ResultTy = E->getType();
31 ASTContext &Ctx = getState()->getStateManager().getContext();
33 // A function that returns a reference to 'int' will have a result type
34 // of simply 'int'. Check the origin expr's value kind to recover the
36 switch (E->getValueKind()) {
38 ResultTy = Ctx.getLValueReferenceType(ResultTy);
41 ResultTy = Ctx.getRValueReferenceType(ResultTy);
44 // No adjustment is necessary.
51 static bool isCallbackArg(SVal V, QualType T) {
52 // If the parameter is 0, it's harmless.
53 if (V.isZeroConstant())
56 // If a parameter is a block or a callback, assume it can modify pointer.
57 if (T->isBlockPointerType() ||
58 T->isFunctionPointerType() ||
62 // Check if a callback is passed inside a struct (for both, struct passed by
63 // reference and by value). Dig just one level into the struct for now.
65 if (T->isAnyPointerType() || T->isReferenceType())
66 T = T->getPointeeType();
68 if (const RecordType *RT = T->getAsStructureType()) {
69 const RecordDecl *RD = RT->getDecl();
70 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
72 QualType FieldT = I->getType();
73 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
81 bool CallEvent::hasNonZeroCallbackArg() const {
82 unsigned NumOfArgs = getNumArgs();
84 // If calling using a function pointer, assume the function does not
85 // have a callback. TODO: We could check the types of the arguments here.
90 for (CallEvent::param_type_iterator I = param_type_begin(),
92 I != E && Idx < NumOfArgs; ++I, ++Idx) {
96 if (isCallbackArg(getArgSVal(Idx), *I))
103 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
104 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
108 return CheckerContext::isCLibraryFunction(FD, FunctionName);
111 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
112 /// with no further indirection.
113 static bool isPointerToConst(QualType Ty) {
114 QualType PointeeTy = Ty->getPointeeType();
115 if (PointeeTy == QualType())
117 if (!PointeeTy.isConstQualified())
119 if (PointeeTy->isAnyPointerType())
124 // Try to retrieve the function declaration and find the function parameter
125 // types which are pointers/references to a non-pointer const.
126 // We will not invalidate the corresponding argument regions.
127 static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
128 const CallEvent &Call) {
130 for (CallEvent::param_type_iterator I = Call.param_type_begin(),
131 E = Call.param_type_end();
132 I != E; ++I, ++Idx) {
133 if (isPointerToConst(*I))
134 PreserveArgs.insert(Idx);
138 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
139 ProgramStateRef Orig) const {
140 ProgramStateRef Result = (Orig ? Orig : getState());
142 SmallVector<const MemRegion *, 8> RegionsToInvalidate;
143 getExtraInvalidatedRegions(RegionsToInvalidate);
145 // Indexes of arguments whose values will be preserved by the call.
146 llvm::SmallSet<unsigned, 1> PreserveArgs;
147 if (!argumentsMayEscape())
148 findPtrToConstParams(PreserveArgs, *this);
150 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
151 if (PreserveArgs.count(Idx))
154 SVal V = getArgSVal(Idx);
156 // If we are passing a location wrapped as an integer, unwrap it and
157 // invalidate the values referred by the location.
158 if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
159 V = Wrapped->getLoc();
160 else if (!isa<Loc>(V))
163 if (const MemRegion *R = V.getAsRegion()) {
164 // Invalidate the value of the variable passed by reference.
166 // Are we dealing with an ElementRegion? If the element type is
167 // a basic integer type (e.g., char, int) and the underlying region
168 // is a variable region then strip off the ElementRegion.
169 // FIXME: We really need to think about this for the general case
170 // as sometimes we are reasoning about arrays and other times
171 // about (char*), etc., is just a form of passing raw bytes.
172 // e.g., void *p = alloca(); foo((char*)p);
173 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
174 // Checking for 'integral type' is probably too promiscuous, but
175 // we'll leave it in for now until we have a systematic way of
176 // handling all of these cases. Eventually we need to come up
177 // with an interface to StoreManager so that this logic can be
178 // appropriately delegated to the respective StoreManagers while
179 // still allowing us to do checker-specific logic (e.g.,
180 // invalidating reference counts), probably via callbacks.
181 if (ER->getElementType()->isIntegralOrEnumerationType()) {
182 const MemRegion *superReg = ER->getSuperRegion();
183 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
184 isa<ObjCIvarRegion>(superReg))
185 R = cast<TypedRegion>(superReg);
187 // FIXME: What about layers of ElementRegions?
190 // Mark this region for invalidation. We batch invalidate regions
191 // below for efficiency.
192 RegionsToInvalidate.push_back(R);
196 // Invalidate designated regions using the batch invalidation API.
197 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
199 return Result->invalidateRegions(RegionsToInvalidate, getOriginExpr(),
200 BlockCount, getLocationContext(),
201 /*Symbols=*/0, this);
204 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
205 const ProgramPointTag *Tag) const {
206 if (const Expr *E = getOriginExpr()) {
208 return PreStmt(E, getLocationContext(), Tag);
209 return PostStmt(E, getLocationContext(), Tag);
212 const Decl *D = getDecl();
213 assert(D && "Cannot get a program point without a statement or decl");
215 SourceLocation Loc = getSourceRange().getBegin();
217 return PreImplicitCall(D, Loc, getLocationContext(), Tag);
218 return PostImplicitCall(D, Loc, getLocationContext(), Tag);
221 SVal CallEvent::getArgSVal(unsigned Index) const {
222 const Expr *ArgE = getArgExpr(Index);
225 return getSVal(ArgE);
228 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
229 const Expr *ArgE = getArgExpr(Index);
231 return SourceRange();
232 return ArgE->getSourceRange();
235 SVal CallEvent::getReturnValue() const {
236 const Expr *E = getOriginExpr();
238 return UndefinedVal();
242 void CallEvent::dump() const {
246 void CallEvent::dump(raw_ostream &Out) const {
247 ASTContext &Ctx = getState()->getStateManager().getContext();
248 if (const Expr *E = getOriginExpr()) {
249 E->printPretty(Out, 0, Ctx.getPrintingPolicy());
254 if (const Decl *D = getDecl()) {
256 D->print(Out, Ctx.getPrintingPolicy());
260 // FIXME: a string representation of the kind would be nice.
261 Out << "Unknown call (type " << getKind() << ")";
265 bool CallEvent::isCallStmt(const Stmt *S) {
266 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
267 || isa<CXXConstructExpr>(S)
268 || isa<CXXNewExpr>(S);
271 /// \brief Returns the result type, adjusted for references.
272 QualType CallEvent::getDeclaredResultType(const Decl *D) {
274 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
275 return FD->getResultType();
276 else if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
277 return MD->getResultType();
281 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
282 CallEvent::BindingsTy &Bindings,
284 const CallEvent &Call,
285 CallEvent::param_iterator I,
286 CallEvent::param_iterator E) {
287 MemRegionManager &MRMgr = SVB.getRegionManager();
290 for (; I != E; ++I, ++Idx) {
291 const ParmVarDecl *ParamDecl = *I;
292 assert(ParamDecl && "Formal parameter has no decl?");
294 SVal ArgVal = Call.getArgSVal(Idx);
295 if (!ArgVal.isUnknown()) {
296 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
297 Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
301 // FIXME: Variadic arguments are not handled at all right now.
305 CallEvent::param_iterator AnyFunctionCall::param_begin() const {
306 const FunctionDecl *D = getDecl();
310 return D->param_begin();
313 CallEvent::param_iterator AnyFunctionCall::param_end() const {
314 const FunctionDecl *D = getDecl();
318 return D->param_end();
321 void AnyFunctionCall::getInitialStackFrameContents(
322 const StackFrameContext *CalleeCtx,
323 BindingsTy &Bindings) const {
324 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
325 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
326 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
327 D->param_begin(), D->param_end());
330 bool AnyFunctionCall::argumentsMayEscape() const {
331 if (hasNonZeroCallbackArg())
334 const FunctionDecl *D = getDecl();
338 const IdentifierInfo *II = D->getIdentifier();
342 // This set of "escaping" APIs is
344 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
345 // value into thread local storage. The value can later be retrieved with
346 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
347 // parameter is 'const void *', the region escapes through the call.
348 if (II->isStr("pthread_setspecific"))
351 // - xpc_connection_set_context stores a value which can be retrieved later
352 // with xpc_connection_get_context.
353 if (II->isStr("xpc_connection_set_context"))
356 // - funopen - sets a buffer for future IO calls.
357 if (II->isStr("funopen"))
360 StringRef FName = II->getName();
362 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
363 // buffer even if it is const.
364 if (FName.endswith("NoCopy"))
367 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
368 // be deallocated by NSMapRemove.
369 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
372 // - Many CF containers allow objects to escape through custom
373 // allocators/deallocators upon container construction. (PR12101)
374 if (FName.startswith("CF") || FName.startswith("CG")) {
375 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
376 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
377 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
378 StrInStrNoCase(FName, "WithData") != StringRef::npos ||
379 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
380 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
387 const FunctionDecl *SimpleCall::getDecl() const {
388 const FunctionDecl *D = getOriginExpr()->getDirectCallee();
392 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
396 const FunctionDecl *CXXInstanceCall::getDecl() const {
397 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
399 return AnyFunctionCall::getDecl();
401 const FunctionDecl *D = CE->getDirectCallee();
405 return getSVal(CE->getCallee()).getAsFunctionDecl();
408 void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
409 if (const MemRegion *R = getCXXThisVal().getAsRegion())
410 Regions.push_back(R);
413 SVal CXXInstanceCall::getCXXThisVal() const {
414 const Expr *Base = getCXXThisExpr();
415 // FIXME: This doesn't handle an overloaded ->* operator.
419 SVal ThisVal = getSVal(Base);
420 assert(ThisVal.isUnknownOrUndef() || isa<Loc>(ThisVal));
425 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
426 // Do we have a decl at all?
427 const Decl *D = getDecl();
429 return RuntimeDefinition();
431 // If the method is non-virtual, we know we can inline it.
432 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
433 if (!MD->isVirtual())
434 return AnyFunctionCall::getRuntimeDefinition();
436 // Do we know the implicit 'this' object being called?
437 const MemRegion *R = getCXXThisVal().getAsRegion();
439 return RuntimeDefinition();
441 // Do we know anything about the type of 'this'?
442 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
443 if (!DynType.isValid())
444 return RuntimeDefinition();
446 // Is the type a C++ class? (This is mostly a defensive check.)
447 QualType RegionType = DynType.getType()->getPointeeType();
448 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
450 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
451 if (!RD || !RD->hasDefinition())
452 return RuntimeDefinition();
454 // Find the decl for this method in that class.
455 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
457 // We might not even get the original statically-resolved method due to
458 // some particularly nasty casting (e.g. casts to sister classes).
459 // However, we should at least be able to search up and down our own class
460 // hierarchy, and some real bugs have been caught by checking this.
461 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
463 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
464 // the static type. However, because we currently don't update
465 // DynamicTypeInfo when an object is cast, we can't actually be sure the
466 // DynamicTypeInfo is up to date. This assert should be re-enabled once
467 // this is fixed. <rdar://problem/12287087>
468 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
470 return RuntimeDefinition();
473 // Does the decl that we found have an implementation?
474 const FunctionDecl *Definition;
475 if (!Result->hasBody(Definition))
476 return RuntimeDefinition();
478 // We found a definition. If we're not sure that this devirtualization is
479 // actually what will happen at runtime, make sure to provide the region so
480 // that ExprEngine can decide what to do with it.
481 if (DynType.canBeASubClass())
482 return RuntimeDefinition(Definition, R->StripCasts());
483 return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
486 void CXXInstanceCall::getInitialStackFrameContents(
487 const StackFrameContext *CalleeCtx,
488 BindingsTy &Bindings) const {
489 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
491 // Handle the binding of 'this' in the new stack frame.
492 SVal ThisVal = getCXXThisVal();
493 if (!ThisVal.isUnknown()) {
494 ProgramStateManager &StateMgr = getState()->getStateManager();
495 SValBuilder &SVB = StateMgr.getSValBuilder();
497 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
498 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
500 // If we devirtualized to a different member function, we need to make sure
501 // we have the proper layering of CXXBaseObjectRegions.
502 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
503 ASTContext &Ctx = SVB.getContext();
504 const CXXRecordDecl *Class = MD->getParent();
505 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
507 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
509 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
510 assert(!Failed && "Calling an incorrectly devirtualized method");
513 if (!ThisVal.isUnknown())
514 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
520 const Expr *CXXMemberCall::getCXXThisExpr() const {
521 return getOriginExpr()->getImplicitObjectArgument();
524 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
525 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
526 // id-expression in the class member access expression is a qualified-id,
527 // that function is called. Otherwise, its final overrider in the dynamic type
528 // of the object expression is called.
529 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
530 if (ME->hasQualifier())
531 return AnyFunctionCall::getRuntimeDefinition();
533 return CXXInstanceCall::getRuntimeDefinition();
537 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
538 return getOriginExpr()->getArg(0);
542 const BlockDataRegion *BlockCall::getBlockRegion() const {
543 const Expr *Callee = getOriginExpr()->getCallee();
544 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
546 return dyn_cast_or_null<BlockDataRegion>(DataReg);
549 CallEvent::param_iterator BlockCall::param_begin() const {
550 const BlockDecl *D = getBlockDecl();
553 return D->param_begin();
556 CallEvent::param_iterator BlockCall::param_end() const {
557 const BlockDecl *D = getBlockDecl();
560 return D->param_end();
563 void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
564 // FIXME: This also needs to invalidate captured globals.
565 if (const MemRegion *R = getBlockRegion())
566 Regions.push_back(R);
569 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
570 BindingsTy &Bindings) const {
571 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
572 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
573 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
574 D->param_begin(), D->param_end());
578 SVal CXXConstructorCall::getCXXThisVal() const {
580 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
584 void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
586 Regions.push_back(static_cast<const MemRegion *>(Data));
589 void CXXConstructorCall::getInitialStackFrameContents(
590 const StackFrameContext *CalleeCtx,
591 BindingsTy &Bindings) const {
592 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
594 SVal ThisVal = getCXXThisVal();
595 if (!ThisVal.isUnknown()) {
596 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
597 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
598 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
599 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
605 SVal CXXDestructorCall::getCXXThisVal() const {
607 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
611 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
612 // Base destructors are always called non-virtually.
613 // Skip CXXInstanceCall's devirtualization logic in this case.
614 if (isBaseDestructor())
615 return AnyFunctionCall::getRuntimeDefinition();
617 return CXXInstanceCall::getRuntimeDefinition();
621 CallEvent::param_iterator ObjCMethodCall::param_begin() const {
622 const ObjCMethodDecl *D = getDecl();
626 return D->param_begin();
629 CallEvent::param_iterator ObjCMethodCall::param_end() const {
630 const ObjCMethodDecl *D = getDecl();
634 return D->param_end();
638 ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
639 if (const MemRegion *R = getReceiverSVal().getAsRegion())
640 Regions.push_back(R);
643 SVal ObjCMethodCall::getSelfSVal() const {
644 const LocationContext *LCtx = getLocationContext();
645 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
648 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
651 SVal ObjCMethodCall::getReceiverSVal() const {
652 // FIXME: Is this the best way to handle class receivers?
653 if (!isInstanceMessage())
656 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
657 return getSVal(RecE);
659 // An instance message with no expression means we are sending to super.
660 // In this case the object reference is the same as 'self'.
661 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
662 SVal SelfVal = getSelfSVal();
663 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
667 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
668 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
669 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
672 if (!isInstanceMessage())
675 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
677 return (RecVal == getSelfSVal());
680 SourceRange ObjCMethodCall::getSourceRange() const {
681 switch (getMessageKind()) {
683 return getOriginExpr()->getSourceRange();
684 case OCM_PropertyAccess:
686 return getContainingPseudoObjectExpr()->getSourceRange();
688 llvm_unreachable("unknown message kind");
691 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
693 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
694 assert(Data != 0 && "Lazy lookup not yet performed.");
695 assert(getMessageKind() != OCM_Message && "Explicit message send.");
696 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
699 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
701 ParentMap &PM = getLocationContext()->getParentMap();
702 const Stmt *S = PM.getParent(getOriginExpr());
703 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
704 const Expr *Syntactic = POE->getSyntacticForm();
706 // This handles the funny case of assigning to the result of a getter.
707 // This can happen if the getter returns a non-const reference.
708 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
709 Syntactic = BO->getLHS();
712 switch (Syntactic->getStmtClass()) {
713 case Stmt::ObjCPropertyRefExprClass:
714 K = OCM_PropertyAccess;
716 case Stmt::ObjCSubscriptRefExprClass:
720 // FIXME: Can this ever happen?
725 if (K != OCM_Message) {
726 const_cast<ObjCMethodCall *>(this)->Data
727 = ObjCMessageDataTy(POE, K).getOpaqueValue();
728 assert(getMessageKind() == K);
733 const_cast<ObjCMethodCall *>(this)->Data
734 = ObjCMessageDataTy(0, 1).getOpaqueValue();
735 assert(getMessageKind() == OCM_Message);
739 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
740 if (!Info.getPointer())
742 return static_cast<ObjCMessageKind>(Info.getInt());
746 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
747 Selector Sel) const {
749 const SourceManager &SM =
750 getState()->getStateManager().getContext().getSourceManager();
752 // If the class interface is declared inside the main file, assume it is not
754 // TODO: It could actually be subclassed if the subclass is private as well.
755 // This is probably very rare.
756 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
757 if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
760 // Assume that property accessors are not overridden.
761 if (getMessageKind() == OCM_PropertyAccess)
764 // We assume that if the method is public (declared outside of main file) or
765 // has a parent which publicly declares the method, the method could be
766 // overridden in a subclass.
768 // Find the first declaration in the class hierarchy that declares
770 ObjCMethodDecl *D = 0;
772 D = IDecl->lookupMethod(Sel, true);
774 // Cannot find a public definition.
778 // If outside the main file,
779 if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
782 if (D->isOverriding()) {
783 // Search in the superclass on the next iteration.
784 IDecl = D->getClassInterface();
788 IDecl = IDecl->getSuperClass();
798 llvm_unreachable("The while loop should always terminate.");
801 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
802 const ObjCMessageExpr *E = getOriginExpr();
804 Selector Sel = E->getSelector();
806 if (E->isInstanceMessage()) {
808 // Find the the receiver type.
809 const ObjCObjectPointerType *ReceiverT = 0;
810 bool CanBeSubClassed = false;
811 QualType SupersType = E->getSuperType();
812 const MemRegion *Receiver = 0;
814 if (!SupersType.isNull()) {
815 // Super always means the type of immediate predecessor to the method
816 // where the call occurs.
817 ReceiverT = cast<ObjCObjectPointerType>(SupersType);
819 Receiver = getReceiverSVal().getAsRegion();
821 return RuntimeDefinition();
823 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
824 QualType DynType = DTI.getType();
825 CanBeSubClassed = DTI.canBeASubClass();
826 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
828 if (ReceiverT && CanBeSubClassed)
829 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
830 if (!canBeOverridenInSubclass(IDecl, Sel))
831 CanBeSubClassed = false;
834 // Lookup the method implementation.
836 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
837 const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel);
839 return RuntimeDefinition(MD, Receiver);
841 return RuntimeDefinition(MD, 0);
845 // This is a class method.
846 // If we have type info for the receiver class, we are calling via
848 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
849 // Find/Return the method implementation.
850 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
854 return RuntimeDefinition();
857 void ObjCMethodCall::getInitialStackFrameContents(
858 const StackFrameContext *CalleeCtx,
859 BindingsTy &Bindings) const {
860 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
861 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
862 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
863 D->param_begin(), D->param_end());
865 SVal SelfVal = getReceiverSVal();
866 if (!SelfVal.isUnknown()) {
867 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
868 MemRegionManager &MRMgr = SVB.getRegionManager();
869 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
870 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
875 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
876 const LocationContext *LCtx) {
877 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
878 return create<CXXMemberCall>(MCE, State, LCtx);
880 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
881 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
882 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
883 if (MD->isInstance())
884 return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
886 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
887 return create<BlockCall>(CE, State, LCtx);
890 // Otherwise, it's a normal function call, static member function call, or
891 // something we can't reason about.
892 return create<FunctionCall>(CE, State, LCtx);
897 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
898 ProgramStateRef State) {
899 const LocationContext *ParentCtx = CalleeCtx->getParent();
900 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
901 assert(CallerCtx && "This should not be used for top-level stack frames");
903 const Stmt *CallSite = CalleeCtx->getCallSite();
906 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
907 return getSimpleCall(CE, State, CallerCtx);
909 switch (CallSite->getStmtClass()) {
910 case Stmt::CXXConstructExprClass:
911 case Stmt::CXXTemporaryObjectExprClass: {
912 SValBuilder &SVB = State->getStateManager().getSValBuilder();
913 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
914 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
915 SVal ThisVal = State->getSVal(ThisPtr);
917 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
918 ThisVal.getAsRegion(), State, CallerCtx);
920 case Stmt::CXXNewExprClass:
921 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
922 case Stmt::ObjCMessageExprClass:
923 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
926 llvm_unreachable("This is not an inlineable statement.");
930 // Fall back to the CFG. The only thing we haven't handled yet is
931 // destructors, though this could change in the future.
932 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
933 CFGElement E = (*B)[CalleeCtx->getIndex()];
934 assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
935 assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
937 SValBuilder &SVB = State->getStateManager().getSValBuilder();
938 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
939 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
940 SVal ThisVal = State->getSVal(ThisPtr);
943 if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
944 Trigger = AutoDtor->getTriggerStmt();
946 Trigger = Dtor->getBody();
948 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
949 isa<CFGBaseDtor>(E), State, CallerCtx);