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 "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
28 QualType CallEvent::getResultType() const {
29 const Expr *E = getOriginExpr();
30 assert(E && "Calls without origin expressions do not have results");
31 QualType ResultTy = E->getType();
33 ASTContext &Ctx = getState()->getStateManager().getContext();
35 // A function that returns a reference to 'int' will have a result type
36 // of simply 'int'. Check the origin expr's value kind to recover the
38 switch (E->getValueKind()) {
40 ResultTy = Ctx.getLValueReferenceType(ResultTy);
43 ResultTy = Ctx.getRValueReferenceType(ResultTy);
46 // No adjustment is necessary.
53 static bool isCallback(QualType T) {
54 // If a parameter is a block or a callback, assume it can modify pointer.
55 if (T->isBlockPointerType() ||
56 T->isFunctionPointerType() ||
60 // Check if a callback is passed inside a struct (for both, struct passed by
61 // reference and by value). Dig just one level into the struct for now.
63 if (T->isAnyPointerType() || T->isReferenceType())
64 T = T->getPointeeType();
66 if (const RecordType *RT = T->getAsStructureType()) {
67 const RecordDecl *RD = RT->getDecl();
68 for (const auto *I : RD->fields()) {
69 QualType FieldT = I->getType();
70 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
77 static bool isVoidPointerToNonConst(QualType T) {
78 if (const PointerType *PT = T->getAs<PointerType>()) {
79 QualType PointeeTy = PT->getPointeeType();
80 if (PointeeTy.isConstQualified())
82 return PointeeTy->isVoidType();
87 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
88 unsigned NumOfArgs = getNumArgs();
90 // If calling using a function pointer, assume the function does not
91 // satisfy the callback.
92 // TODO: We could check the types of the arguments here.
97 for (CallEvent::param_type_iterator I = param_type_begin(),
99 I != E && Idx < NumOfArgs; ++I, ++Idx) {
100 if (NumOfArgs <= Idx)
103 // If the parameter is 0, it's harmless.
104 if (getArgSVal(Idx).isZeroConstant())
113 bool CallEvent::hasNonZeroCallbackArg() const {
114 return hasNonNullArgumentsWithType(isCallback);
117 bool CallEvent::hasVoidPointerToNonConstArg() const {
118 return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
121 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
122 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
126 return CheckerContext::isCLibraryFunction(FD, FunctionName);
129 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
130 /// with no further indirection.
131 static bool isPointerToConst(QualType Ty) {
132 QualType PointeeTy = Ty->getPointeeType();
133 if (PointeeTy == QualType())
135 if (!PointeeTy.isConstQualified())
137 if (PointeeTy->isAnyPointerType())
142 // Try to retrieve the function declaration and find the function parameter
143 // types which are pointers/references to a non-pointer const.
144 // We will not invalidate the corresponding argument regions.
145 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
146 const CallEvent &Call) {
148 for (CallEvent::param_type_iterator I = Call.param_type_begin(),
149 E = Call.param_type_end();
150 I != E; ++I, ++Idx) {
151 if (isPointerToConst(*I))
152 PreserveArgs.insert(Idx);
156 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
157 ProgramStateRef Orig) const {
158 ProgramStateRef Result = (Orig ? Orig : getState());
160 // Don't invalidate anything if the callee is marked pure/const.
161 if (const Decl *callee = getDecl())
162 if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
165 SmallVector<SVal, 8> ValuesToInvalidate;
166 RegionAndSymbolInvalidationTraits ETraits;
168 getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
170 // Indexes of arguments whose values will be preserved by the call.
171 llvm::SmallSet<unsigned, 4> PreserveArgs;
172 if (!argumentsMayEscape())
173 findPtrToConstParams(PreserveArgs, *this);
175 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
176 // Mark this region for invalidation. We batch invalidate regions
177 // below for efficiency.
178 if (PreserveArgs.count(Idx))
179 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
180 ETraits.setTrait(MR->getBaseRegion(),
181 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
182 // TODO: Factor this out + handle the lower level const pointers.
184 ValuesToInvalidate.push_back(getArgSVal(Idx));
187 // Invalidate designated regions using the batch invalidation API.
188 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
190 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
191 BlockCount, getLocationContext(),
192 /*CausedByPointerEscape*/ true,
193 /*Symbols=*/nullptr, this, &ETraits);
196 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
197 const ProgramPointTag *Tag) const {
198 if (const Expr *E = getOriginExpr()) {
200 return PreStmt(E, getLocationContext(), Tag);
201 return PostStmt(E, getLocationContext(), Tag);
204 const Decl *D = getDecl();
205 assert(D && "Cannot get a program point without a statement or decl");
207 SourceLocation Loc = getSourceRange().getBegin();
209 return PreImplicitCall(D, Loc, getLocationContext(), Tag);
210 return PostImplicitCall(D, Loc, getLocationContext(), Tag);
213 bool CallEvent::isCalled(const CallDescription &CD) const {
214 assert(getKind() != CE_ObjCMessage && "Obj-C methods are not supported");
215 if (!CD.IsLookupDone) {
216 CD.IsLookupDone = true;
217 CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
219 const IdentifierInfo *II = getCalleeIdentifier();
220 if (!II || II != CD.II)
222 return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
223 CD.RequiredArgs == getNumArgs());
226 SVal CallEvent::getArgSVal(unsigned Index) const {
227 const Expr *ArgE = getArgExpr(Index);
230 return getSVal(ArgE);
233 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
234 const Expr *ArgE = getArgExpr(Index);
236 return SourceRange();
237 return ArgE->getSourceRange();
240 SVal CallEvent::getReturnValue() const {
241 const Expr *E = getOriginExpr();
243 return UndefinedVal();
247 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
249 void CallEvent::dump(raw_ostream &Out) const {
250 ASTContext &Ctx = getState()->getStateManager().getContext();
251 if (const Expr *E = getOriginExpr()) {
252 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
257 if (const Decl *D = getDecl()) {
259 D->print(Out, Ctx.getPrintingPolicy());
263 // FIXME: a string representation of the kind would be nice.
264 Out << "Unknown call (type " << getKind() << ")";
268 bool CallEvent::isCallStmt(const Stmt *S) {
269 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
270 || isa<CXXConstructExpr>(S)
271 || isa<CXXNewExpr>(S);
274 QualType CallEvent::getDeclaredResultType(const Decl *D) {
276 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
277 return FD->getReturnType();
278 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
279 return MD->getReturnType();
280 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
281 // Blocks are difficult because the return type may not be stored in the
282 // BlockDecl itself. The AST should probably be enhanced, but for now we
283 // just do what we can.
284 // If the block is declared without an explicit argument list, the
285 // signature-as-written just includes the return type, not the entire
287 // FIXME: All blocks should have signatures-as-written, even if the return
288 // type is inferred. (That's signified with a dependent result type.)
289 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
290 QualType Ty = TSI->getType();
291 if (const FunctionType *FT = Ty->getAs<FunctionType>())
292 Ty = FT->getReturnType();
293 if (!Ty->isDependentType())
300 llvm_unreachable("unknown callable kind");
303 bool CallEvent::isVariadic(const Decl *D) {
306 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
307 return FD->isVariadic();
308 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
309 return MD->isVariadic();
310 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
311 return BD->isVariadic();
313 llvm_unreachable("unknown callable kind");
316 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
317 CallEvent::BindingsTy &Bindings,
319 const CallEvent &Call,
320 ArrayRef<ParmVarDecl*> parameters) {
321 MemRegionManager &MRMgr = SVB.getRegionManager();
323 // If the function has fewer parameters than the call has arguments, we simply
324 // do not bind any values to them.
325 unsigned NumArgs = Call.getNumArgs();
327 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
328 for (; I != E && Idx < NumArgs; ++I, ++Idx) {
329 const ParmVarDecl *ParamDecl = *I;
330 assert(ParamDecl && "Formal parameter has no decl?");
332 SVal ArgVal = Call.getArgSVal(Idx);
333 if (!ArgVal.isUnknown()) {
334 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
335 Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
339 // FIXME: Variadic arguments are not handled at all right now.
342 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
343 const FunctionDecl *D = getDecl();
346 return D->parameters();
349 void AnyFunctionCall::getInitialStackFrameContents(
350 const StackFrameContext *CalleeCtx,
351 BindingsTy &Bindings) const {
352 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
353 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
354 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
358 bool AnyFunctionCall::argumentsMayEscape() const {
359 if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
362 const FunctionDecl *D = getDecl();
366 const IdentifierInfo *II = D->getIdentifier();
370 // This set of "escaping" APIs is
372 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
373 // value into thread local storage. The value can later be retrieved with
374 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
375 // parameter is 'const void *', the region escapes through the call.
376 if (II->isStr("pthread_setspecific"))
379 // - xpc_connection_set_context stores a value which can be retrieved later
380 // with xpc_connection_get_context.
381 if (II->isStr("xpc_connection_set_context"))
384 // - funopen - sets a buffer for future IO calls.
385 if (II->isStr("funopen"))
388 // - __cxa_demangle - can reallocate memory and can return the pointer to
390 if (II->isStr("__cxa_demangle"))
393 StringRef FName = II->getName();
395 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
396 // buffer even if it is const.
397 if (FName.endswith("NoCopy"))
400 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
401 // be deallocated by NSMapRemove.
402 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
405 // - Many CF containers allow objects to escape through custom
406 // allocators/deallocators upon container construction. (PR12101)
407 if (FName.startswith("CF") || FName.startswith("CG")) {
408 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
409 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
410 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
411 StrInStrNoCase(FName, "WithData") != StringRef::npos ||
412 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
413 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
420 const FunctionDecl *SimpleFunctionCall::getDecl() const {
421 const FunctionDecl *D = getOriginExpr()->getDirectCallee();
425 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
429 const FunctionDecl *CXXInstanceCall::getDecl() const {
430 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
432 return AnyFunctionCall::getDecl();
434 const FunctionDecl *D = CE->getDirectCallee();
438 return getSVal(CE->getCallee()).getAsFunctionDecl();
441 void CXXInstanceCall::getExtraInvalidatedValues(
442 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
443 SVal ThisVal = getCXXThisVal();
444 Values.push_back(ThisVal);
446 // Don't invalidate if the method is const and there are no mutable fields.
447 if (const CXXMethodDecl *D = cast_or_null<CXXMethodDecl>(getDecl())) {
450 // Get the record decl for the class of 'This'. D->getParent() may return a
451 // base class decl, rather than the class of the instance which needs to be
452 // checked for mutable fields.
453 const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
454 const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl();
455 if (!ParentRecord || ParentRecord->hasMutableFields())
458 const MemRegion *ThisRegion = ThisVal.getAsRegion();
462 ETraits->setTrait(ThisRegion->getBaseRegion(),
463 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
467 SVal CXXInstanceCall::getCXXThisVal() const {
468 const Expr *Base = getCXXThisExpr();
469 // FIXME: This doesn't handle an overloaded ->* operator.
473 SVal ThisVal = getSVal(Base);
474 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
479 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
480 // Do we have a decl at all?
481 const Decl *D = getDecl();
483 return RuntimeDefinition();
485 // If the method is non-virtual, we know we can inline it.
486 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
487 if (!MD->isVirtual())
488 return AnyFunctionCall::getRuntimeDefinition();
490 // Do we know the implicit 'this' object being called?
491 const MemRegion *R = getCXXThisVal().getAsRegion();
493 return RuntimeDefinition();
495 // Do we know anything about the type of 'this'?
496 DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
497 if (!DynType.isValid())
498 return RuntimeDefinition();
500 // Is the type a C++ class? (This is mostly a defensive check.)
501 QualType RegionType = DynType.getType()->getPointeeType();
502 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
504 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
505 if (!RD || !RD->hasDefinition())
506 return RuntimeDefinition();
508 // Find the decl for this method in that class.
509 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
511 // We might not even get the original statically-resolved method due to
512 // some particularly nasty casting (e.g. casts to sister classes).
513 // However, we should at least be able to search up and down our own class
514 // hierarchy, and some real bugs have been caught by checking this.
515 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
517 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
518 // the static type. However, because we currently don't update
519 // DynamicTypeInfo when an object is cast, we can't actually be sure the
520 // DynamicTypeInfo is up to date. This assert should be re-enabled once
521 // this is fixed. <rdar://problem/12287087>
522 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
524 return RuntimeDefinition();
527 // Does the decl that we found have an implementation?
528 const FunctionDecl *Definition;
529 if (!Result->hasBody(Definition))
530 return RuntimeDefinition();
532 // We found a definition. If we're not sure that this devirtualization is
533 // actually what will happen at runtime, make sure to provide the region so
534 // that ExprEngine can decide what to do with it.
535 if (DynType.canBeASubClass())
536 return RuntimeDefinition(Definition, R->StripCasts());
537 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
540 void CXXInstanceCall::getInitialStackFrameContents(
541 const StackFrameContext *CalleeCtx,
542 BindingsTy &Bindings) const {
543 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
545 // Handle the binding of 'this' in the new stack frame.
546 SVal ThisVal = getCXXThisVal();
547 if (!ThisVal.isUnknown()) {
548 ProgramStateManager &StateMgr = getState()->getStateManager();
549 SValBuilder &SVB = StateMgr.getSValBuilder();
551 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
552 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
554 // If we devirtualized to a different member function, we need to make sure
555 // we have the proper layering of CXXBaseObjectRegions.
556 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
557 ASTContext &Ctx = SVB.getContext();
558 const CXXRecordDecl *Class = MD->getParent();
559 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
561 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
563 ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
564 assert(!Failed && "Calling an incorrectly devirtualized method");
567 if (!ThisVal.isUnknown())
568 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
574 const Expr *CXXMemberCall::getCXXThisExpr() const {
575 return getOriginExpr()->getImplicitObjectArgument();
578 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
579 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
580 // id-expression in the class member access expression is a qualified-id,
581 // that function is called. Otherwise, its final overrider in the dynamic type
582 // of the object expression is called.
583 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
584 if (ME->hasQualifier())
585 return AnyFunctionCall::getRuntimeDefinition();
587 return CXXInstanceCall::getRuntimeDefinition();
591 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
592 return getOriginExpr()->getArg(0);
596 const BlockDataRegion *BlockCall::getBlockRegion() const {
597 const Expr *Callee = getOriginExpr()->getCallee();
598 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
600 return dyn_cast_or_null<BlockDataRegion>(DataReg);
603 ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
604 const BlockDecl *D = getDecl();
607 return D->parameters();
610 void BlockCall::getExtraInvalidatedValues(ValueList &Values,
611 RegionAndSymbolInvalidationTraits *ETraits) const {
612 // FIXME: This also needs to invalidate captured globals.
613 if (const MemRegion *R = getBlockRegion())
614 Values.push_back(loc::MemRegionVal(R));
617 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
618 BindingsTy &Bindings) const {
619 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
620 ArrayRef<ParmVarDecl*> Params;
621 if (isConversionFromLambda()) {
622 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
623 Params = LambdaOperatorDecl->parameters();
625 // For blocks converted from a C++ lambda, the callee declaration is the
626 // operator() method on the lambda so we bind "this" to
627 // the lambda captured by the block.
628 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
629 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
630 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
631 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
633 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
636 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
641 SVal CXXConstructorCall::getCXXThisVal() const {
643 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
647 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
648 RegionAndSymbolInvalidationTraits *ETraits) const {
650 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
653 void CXXConstructorCall::getInitialStackFrameContents(
654 const StackFrameContext *CalleeCtx,
655 BindingsTy &Bindings) const {
656 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
658 SVal ThisVal = getCXXThisVal();
659 if (!ThisVal.isUnknown()) {
660 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
661 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
662 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
663 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
667 SVal CXXDestructorCall::getCXXThisVal() const {
669 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
673 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
674 // Base destructors are always called non-virtually.
675 // Skip CXXInstanceCall's devirtualization logic in this case.
676 if (isBaseDestructor())
677 return AnyFunctionCall::getRuntimeDefinition();
679 return CXXInstanceCall::getRuntimeDefinition();
682 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
683 const ObjCMethodDecl *D = getDecl();
686 return D->parameters();
689 void ObjCMethodCall::getExtraInvalidatedValues(
690 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
692 // If the method call is a setter for property known to be backed by
693 // an instance variable, don't invalidate the entire receiver, just
694 // the storage for that instance variable.
695 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
696 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
697 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
698 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
701 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
704 RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
705 Values.push_back(IvarLVal);
711 Values.push_back(getReceiverSVal());
714 SVal ObjCMethodCall::getSelfSVal() const {
715 const LocationContext *LCtx = getLocationContext();
716 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
719 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
722 SVal ObjCMethodCall::getReceiverSVal() const {
723 // FIXME: Is this the best way to handle class receivers?
724 if (!isInstanceMessage())
727 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
728 return getSVal(RecE);
730 // An instance message with no expression means we are sending to super.
731 // In this case the object reference is the same as 'self'.
732 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
733 SVal SelfVal = getSelfSVal();
734 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
738 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
739 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
740 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
743 if (!isInstanceMessage())
746 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
748 return (RecVal == getSelfSVal());
751 SourceRange ObjCMethodCall::getSourceRange() const {
752 switch (getMessageKind()) {
754 return getOriginExpr()->getSourceRange();
755 case OCM_PropertyAccess:
757 return getContainingPseudoObjectExpr()->getSourceRange();
759 llvm_unreachable("unknown message kind");
762 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
764 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
765 assert(Data && "Lazy lookup not yet performed.");
766 assert(getMessageKind() != OCM_Message && "Explicit message send.");
767 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
771 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
772 const Expr *Syntactic = POE->getSyntacticForm();
774 // This handles the funny case of assigning to the result of a getter.
775 // This can happen if the getter returns a non-const reference.
776 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
777 Syntactic = BO->getLHS();
782 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
785 // Find the parent, ignoring implicit casts.
786 ParentMap &PM = getLocationContext()->getParentMap();
787 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
789 // Check if parent is a PseudoObjectExpr.
790 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
791 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
794 switch (Syntactic->getStmtClass()) {
795 case Stmt::ObjCPropertyRefExprClass:
796 K = OCM_PropertyAccess;
798 case Stmt::ObjCSubscriptRefExprClass:
802 // FIXME: Can this ever happen?
807 if (K != OCM_Message) {
808 const_cast<ObjCMethodCall *>(this)->Data
809 = ObjCMessageDataTy(POE, K).getOpaqueValue();
810 assert(getMessageKind() == K);
815 const_cast<ObjCMethodCall *>(this)->Data
816 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
817 assert(getMessageKind() == OCM_Message);
821 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
822 if (!Info.getPointer())
824 return static_cast<ObjCMessageKind>(Info.getInt());
827 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
828 // Look for properties accessed with property syntax (foo.bar = ...)
829 if ( getMessageKind() == OCM_PropertyAccess) {
830 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
831 assert(POE && "Property access without PseudoObjectExpr?");
833 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
834 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
836 if (RefExpr->isExplicitProperty())
837 return RefExpr->getExplicitProperty();
840 // Look for properties accessed with method syntax ([foo setBar:...]).
841 const ObjCMethodDecl *MD = getDecl();
842 if (!MD || !MD->isPropertyAccessor())
845 // Note: This is potentially quite slow.
846 return MD->findPropertyDecl();
849 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
850 Selector Sel) const {
852 const SourceManager &SM =
853 getState()->getStateManager().getContext().getSourceManager();
855 // If the class interface is declared inside the main file, assume it is not
857 // TODO: It could actually be subclassed if the subclass is private as well.
858 // This is probably very rare.
859 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
860 if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
863 // Assume that property accessors are not overridden.
864 if (getMessageKind() == OCM_PropertyAccess)
867 // We assume that if the method is public (declared outside of main file) or
868 // has a parent which publicly declares the method, the method could be
869 // overridden in a subclass.
871 // Find the first declaration in the class hierarchy that declares
873 ObjCMethodDecl *D = nullptr;
875 D = IDecl->lookupMethod(Sel, true);
877 // Cannot find a public definition.
881 // If outside the main file,
882 if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
885 if (D->isOverriding()) {
886 // Search in the superclass on the next iteration.
887 IDecl = D->getClassInterface();
891 IDecl = IDecl->getSuperClass();
901 llvm_unreachable("The while loop should always terminate.");
904 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
908 // Find the redeclaration that defines the method.
909 if (!MD->hasBody()) {
910 for (auto I : MD->redecls())
912 MD = cast<ObjCMethodDecl>(I);
917 static bool isCallToSelfClass(const ObjCMessageExpr *ME) {
918 const Expr* InstRec = ME->getInstanceReceiver();
921 const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts());
923 // Check that receiver is called 'self'.
924 if (!InstRecIg || !InstRecIg->getFoundDecl() ||
925 !InstRecIg->getFoundDecl()->getName().equals("self"))
928 // Check that the method name is 'class'.
929 if (ME->getSelector().getNumArgs() != 0 ||
930 !ME->getSelector().getNameForSlot(0).equals("class"))
936 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
937 const ObjCMessageExpr *E = getOriginExpr();
939 Selector Sel = E->getSelector();
941 if (E->isInstanceMessage()) {
943 // Find the receiver type.
944 const ObjCObjectPointerType *ReceiverT = nullptr;
945 bool CanBeSubClassed = false;
946 QualType SupersType = E->getSuperType();
947 const MemRegion *Receiver = nullptr;
949 if (!SupersType.isNull()) {
950 // The receiver is guaranteed to be 'super' in this case.
951 // Super always means the type of immediate predecessor to the method
952 // where the call occurs.
953 ReceiverT = cast<ObjCObjectPointerType>(SupersType);
955 Receiver = getReceiverSVal().getAsRegion();
957 return RuntimeDefinition();
959 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
960 if (!DTI.isValid()) {
961 assert(isa<AllocaRegion>(Receiver) &&
962 "Unhandled untyped region class!");
963 return RuntimeDefinition();
966 QualType DynType = DTI.getType();
967 CanBeSubClassed = DTI.canBeASubClass();
968 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
970 if (ReceiverT && CanBeSubClassed)
971 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
972 if (!canBeOverridenInSubclass(IDecl, Sel))
973 CanBeSubClassed = false;
976 // Handle special cases of '[self classMethod]' and
977 // '[[self class] classMethod]', which are treated by the compiler as
978 // instance (not class) messages. We will statically dispatch to those.
979 if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) {
980 // For [self classMethod], return the compiler visible declaration.
981 if (PT->getObjectType()->isObjCClass() &&
982 Receiver == getSelfSVal().getAsRegion())
983 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
985 // Similarly, handle [[self class] classMethod].
986 // TODO: We are currently doing a syntactic match for this pattern with is
987 // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m
988 // shows. A better way would be to associate the meta type with the symbol
989 // using the dynamic type info tracking and use it here. We can add a new
990 // SVal for ObjC 'Class' values that know what interface declaration they
991 // come from. Then 'self' in a class method would be filled in with
992 // something meaningful in ObjCMethodCall::getReceiverSVal() and we could
993 // do proper dynamic dispatch for class methods just like we do for
994 // instance methods now.
995 if (E->getInstanceReceiver())
996 if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver()))
997 if (isCallToSelfClass(M))
998 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1001 // Lookup the instance method implementation.
1003 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
1004 // Repeatedly calling lookupPrivateMethod() is expensive, especially
1005 // when in many cases it returns null. We cache the results so
1006 // that repeated queries on the same ObjCIntefaceDecl and Selector
1007 // don't incur the same cost. On some test cases, we can see the
1008 // same query being issued thousands of times.
1010 // NOTE: This cache is essentially a "global" variable, but it
1011 // only gets lazily created when we get here. The value of the
1012 // cache probably comes from it being global across ExprEngines,
1013 // where the same queries may get issued. If we are worried about
1014 // concurrency, or possibly loading/unloading ASTs, etc., we may
1015 // need to revisit this someday. In terms of memory, this table
1016 // stays around until clang quits, which also may be bad if we
1017 // need to release memory.
1018 typedef std::pair<const ObjCInterfaceDecl*, Selector>
1020 typedef llvm::DenseMap<PrivateMethodKey,
1021 Optional<const ObjCMethodDecl *> >
1024 static PrivateMethodCache PMC;
1025 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
1027 // Query lookupPrivateMethod() if the cache does not hit.
1028 if (!Val.hasValue()) {
1029 Val = IDecl->lookupPrivateMethod(Sel);
1031 // If the method is a property accessor, we should try to "inline" it
1032 // even if we don't actually have an implementation.
1034 if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
1035 if (CompileTimeMD->isPropertyAccessor()) {
1036 if (!CompileTimeMD->getSelfDecl() &&
1037 isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
1038 // If the method is an accessor in a category, and it doesn't
1039 // have a self declaration, first
1040 // try to find the method in a class extension. This
1041 // works around a bug in Sema where multiple accessors
1042 // are synthesized for properties in class
1043 // extensions that are redeclared in a category and the
1044 // the implicit parameters are not filled in for
1045 // the method on the category.
1046 // This ensures we find the accessor in the extension, which
1047 // has the implicit parameters filled in.
1048 auto *ID = CompileTimeMD->getClassInterface();
1049 for (auto *CatDecl : ID->visible_extensions()) {
1050 Val = CatDecl->getMethod(Sel,
1051 CompileTimeMD->isInstanceMethod());
1057 Val = IDecl->lookupInstanceMethod(Sel);
1061 const ObjCMethodDecl *MD = Val.getValue();
1062 if (CanBeSubClassed)
1063 return RuntimeDefinition(MD, Receiver);
1065 return RuntimeDefinition(MD, nullptr);
1069 // This is a class method.
1070 // If we have type info for the receiver class, we are calling via
1072 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1073 // Find/Return the method implementation.
1074 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1078 return RuntimeDefinition();
1081 bool ObjCMethodCall::argumentsMayEscape() const {
1082 if (isInSystemHeader() && !isInstanceMessage()) {
1083 Selector Sel = getSelector();
1084 if (Sel.getNumArgs() == 1 &&
1085 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1089 return CallEvent::argumentsMayEscape();
1092 void ObjCMethodCall::getInitialStackFrameContents(
1093 const StackFrameContext *CalleeCtx,
1094 BindingsTy &Bindings) const {
1095 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1096 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1097 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1100 SVal SelfVal = getReceiverSVal();
1101 if (!SelfVal.isUnknown()) {
1102 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1103 MemRegionManager &MRMgr = SVB.getRegionManager();
1104 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1105 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1110 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1111 const LocationContext *LCtx) {
1112 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1113 return create<CXXMemberCall>(MCE, State, LCtx);
1115 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1116 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1117 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1118 if (MD->isInstance())
1119 return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1121 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1122 return create<BlockCall>(CE, State, LCtx);
1125 // Otherwise, it's a normal function call, static member function call, or
1126 // something we can't reason about.
1127 return create<SimpleFunctionCall>(CE, State, LCtx);
1132 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1133 ProgramStateRef State) {
1134 const LocationContext *ParentCtx = CalleeCtx->getParent();
1135 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
1136 assert(CallerCtx && "This should not be used for top-level stack frames");
1138 const Stmt *CallSite = CalleeCtx->getCallSite();
1141 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
1142 return getSimpleCall(CE, State, CallerCtx);
1144 switch (CallSite->getStmtClass()) {
1145 case Stmt::CXXConstructExprClass:
1146 case Stmt::CXXTemporaryObjectExprClass: {
1147 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1148 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1149 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1150 SVal ThisVal = State->getSVal(ThisPtr);
1152 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
1153 ThisVal.getAsRegion(), State, CallerCtx);
1155 case Stmt::CXXNewExprClass:
1156 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
1157 case Stmt::ObjCMessageExprClass:
1158 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
1161 llvm_unreachable("This is not an inlineable statement.");
1165 // Fall back to the CFG. The only thing we haven't handled yet is
1166 // destructors, though this could change in the future.
1167 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1168 CFGElement E = (*B)[CalleeCtx->getIndex()];
1169 assert(E.getAs<CFGImplicitDtor>() &&
1170 "All other CFG elements should have exprs");
1171 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
1173 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1174 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1175 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1176 SVal ThisVal = State->getSVal(ThisPtr);
1178 const Stmt *Trigger;
1179 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1180 Trigger = AutoDtor->getTriggerStmt();
1181 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1182 Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
1184 Trigger = Dtor->getBody();
1186 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1187 E.getAs<CFGBaseDtor>().hasValue(), State,