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"
24 #include "llvm/Support/Debug.h"
26 #define DEBUG_TYPE "static-analyzer-call-event"
28 using namespace clang;
31 QualType CallEvent::getResultType() const {
32 const Expr *E = getOriginExpr();
33 assert(E && "Calls without origin expressions do not have results");
34 QualType ResultTy = E->getType();
36 ASTContext &Ctx = getState()->getStateManager().getContext();
38 // A function that returns a reference to 'int' will have a result type
39 // of simply 'int'. Check the origin expr's value kind to recover the
41 switch (E->getValueKind()) {
43 ResultTy = Ctx.getLValueReferenceType(ResultTy);
46 ResultTy = Ctx.getRValueReferenceType(ResultTy);
49 // No adjustment is necessary.
56 static bool isCallback(QualType T) {
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 (const auto *I : RD->fields()) {
72 QualType FieldT = I->getType();
73 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
80 static bool isVoidPointerToNonConst(QualType T) {
81 if (const PointerType *PT = T->getAs<PointerType>()) {
82 QualType PointeeTy = PT->getPointeeType();
83 if (PointeeTy.isConstQualified())
85 return PointeeTy->isVoidType();
90 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
91 unsigned NumOfArgs = getNumArgs();
93 // If calling using a function pointer, assume the function does not
94 // satisfy the callback.
95 // TODO: We could check the types of the arguments here.
100 for (CallEvent::param_type_iterator I = param_type_begin(),
101 E = param_type_end();
102 I != E && Idx < NumOfArgs; ++I, ++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 // FIXME: Add ObjC Message support.
215 if (getKind() == CE_ObjCMessage)
217 if (!CD.IsLookupDone) {
218 CD.IsLookupDone = true;
219 CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
221 const IdentifierInfo *II = getCalleeIdentifier();
222 if (!II || II != CD.II)
224 return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
225 CD.RequiredArgs == getNumArgs());
228 SVal CallEvent::getArgSVal(unsigned Index) const {
229 const Expr *ArgE = getArgExpr(Index);
232 return getSVal(ArgE);
235 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
236 const Expr *ArgE = getArgExpr(Index);
238 return SourceRange();
239 return ArgE->getSourceRange();
242 SVal CallEvent::getReturnValue() const {
243 const Expr *E = getOriginExpr();
245 return UndefinedVal();
249 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
251 void CallEvent::dump(raw_ostream &Out) const {
252 ASTContext &Ctx = getState()->getStateManager().getContext();
253 if (const Expr *E = getOriginExpr()) {
254 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
259 if (const Decl *D = getDecl()) {
261 D->print(Out, Ctx.getPrintingPolicy());
265 // FIXME: a string representation of the kind would be nice.
266 Out << "Unknown call (type " << getKind() << ")";
270 bool CallEvent::isCallStmt(const Stmt *S) {
271 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
272 || isa<CXXConstructExpr>(S)
273 || isa<CXXNewExpr>(S);
276 QualType CallEvent::getDeclaredResultType(const Decl *D) {
278 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
279 return FD->getReturnType();
280 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
281 return MD->getReturnType();
282 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
283 // Blocks are difficult because the return type may not be stored in the
284 // BlockDecl itself. The AST should probably be enhanced, but for now we
285 // just do what we can.
286 // If the block is declared without an explicit argument list, the
287 // signature-as-written just includes the return type, not the entire
289 // FIXME: All blocks should have signatures-as-written, even if the return
290 // type is inferred. (That's signified with a dependent result type.)
291 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
292 QualType Ty = TSI->getType();
293 if (const FunctionType *FT = Ty->getAs<FunctionType>())
294 Ty = FT->getReturnType();
295 if (!Ty->isDependentType())
302 llvm_unreachable("unknown callable kind");
305 bool CallEvent::isVariadic(const Decl *D) {
308 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
309 return FD->isVariadic();
310 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
311 return MD->isVariadic();
312 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
313 return BD->isVariadic();
315 llvm_unreachable("unknown callable kind");
318 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
319 CallEvent::BindingsTy &Bindings,
321 const CallEvent &Call,
322 ArrayRef<ParmVarDecl*> parameters) {
323 MemRegionManager &MRMgr = SVB.getRegionManager();
325 // If the function has fewer parameters than the call has arguments, we simply
326 // do not bind any values to them.
327 unsigned NumArgs = Call.getNumArgs();
329 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
330 for (; I != E && Idx < NumArgs; ++I, ++Idx) {
331 const ParmVarDecl *ParamDecl = *I;
332 assert(ParamDecl && "Formal parameter has no decl?");
334 SVal ArgVal = Call.getArgSVal(Idx);
335 if (!ArgVal.isUnknown()) {
336 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
337 Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
341 // FIXME: Variadic arguments are not handled at all right now.
344 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
345 const FunctionDecl *D = getDecl();
348 return D->parameters();
351 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
352 const FunctionDecl *FD = getDecl();
353 // Note that the AnalysisDeclContext will have the FunctionDecl with
354 // the definition (if one exists).
356 AnalysisDeclContext *AD =
357 getLocationContext()->getAnalysisDeclContext()->
358 getManager()->getContext(FD);
359 bool IsAutosynthesized;
360 Stmt* Body = AD->getBody(IsAutosynthesized);
362 if (IsAutosynthesized)
363 llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
367 const Decl* Decl = AD->getDecl();
368 return RuntimeDefinition(Decl);
372 return RuntimeDefinition();
375 void AnyFunctionCall::getInitialStackFrameContents(
376 const StackFrameContext *CalleeCtx,
377 BindingsTy &Bindings) const {
378 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
379 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
380 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
384 bool AnyFunctionCall::argumentsMayEscape() const {
385 if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
388 const FunctionDecl *D = getDecl();
392 const IdentifierInfo *II = D->getIdentifier();
396 // This set of "escaping" APIs is
398 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
399 // value into thread local storage. The value can later be retrieved with
400 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
401 // parameter is 'const void *', the region escapes through the call.
402 if (II->isStr("pthread_setspecific"))
405 // - xpc_connection_set_context stores a value which can be retrieved later
406 // with xpc_connection_get_context.
407 if (II->isStr("xpc_connection_set_context"))
410 // - funopen - sets a buffer for future IO calls.
411 if (II->isStr("funopen"))
414 // - __cxa_demangle - can reallocate memory and can return the pointer to
416 if (II->isStr("__cxa_demangle"))
419 StringRef FName = II->getName();
421 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
422 // buffer even if it is const.
423 if (FName.endswith("NoCopy"))
426 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
427 // be deallocated by NSMapRemove.
428 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
431 // - Many CF containers allow objects to escape through custom
432 // allocators/deallocators upon container construction. (PR12101)
433 if (FName.startswith("CF") || FName.startswith("CG")) {
434 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
435 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
436 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
437 StrInStrNoCase(FName, "WithData") != StringRef::npos ||
438 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
439 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
446 const FunctionDecl *SimpleFunctionCall::getDecl() const {
447 const FunctionDecl *D = getOriginExpr()->getDirectCallee();
451 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
455 const FunctionDecl *CXXInstanceCall::getDecl() const {
456 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
458 return AnyFunctionCall::getDecl();
460 const FunctionDecl *D = CE->getDirectCallee();
464 return getSVal(CE->getCallee()).getAsFunctionDecl();
467 void CXXInstanceCall::getExtraInvalidatedValues(
468 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
469 SVal ThisVal = getCXXThisVal();
470 Values.push_back(ThisVal);
472 // Don't invalidate if the method is const and there are no mutable fields.
473 if (const CXXMethodDecl *D = cast_or_null<CXXMethodDecl>(getDecl())) {
476 // Get the record decl for the class of 'This'. D->getParent() may return a
477 // base class decl, rather than the class of the instance which needs to be
478 // checked for mutable fields.
479 const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
480 const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl();
481 if (!ParentRecord || ParentRecord->hasMutableFields())
484 const MemRegion *ThisRegion = ThisVal.getAsRegion();
488 ETraits->setTrait(ThisRegion->getBaseRegion(),
489 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
493 SVal CXXInstanceCall::getCXXThisVal() const {
494 const Expr *Base = getCXXThisExpr();
495 // FIXME: This doesn't handle an overloaded ->* operator.
499 SVal ThisVal = getSVal(Base);
500 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
505 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
506 // Do we have a decl at all?
507 const Decl *D = getDecl();
509 return RuntimeDefinition();
511 // If the method is non-virtual, we know we can inline it.
512 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
513 if (!MD->isVirtual())
514 return AnyFunctionCall::getRuntimeDefinition();
516 // Do we know the implicit 'this' object being called?
517 const MemRegion *R = getCXXThisVal().getAsRegion();
519 return RuntimeDefinition();
521 // Do we know anything about the type of 'this'?
522 DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
523 if (!DynType.isValid())
524 return RuntimeDefinition();
526 // Is the type a C++ class? (This is mostly a defensive check.)
527 QualType RegionType = DynType.getType()->getPointeeType();
528 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
530 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
531 if (!RD || !RD->hasDefinition())
532 return RuntimeDefinition();
534 // Find the decl for this method in that class.
535 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
537 // We might not even get the original statically-resolved method due to
538 // some particularly nasty casting (e.g. casts to sister classes).
539 // However, we should at least be able to search up and down our own class
540 // hierarchy, and some real bugs have been caught by checking this.
541 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
543 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
544 // the static type. However, because we currently don't update
545 // DynamicTypeInfo when an object is cast, we can't actually be sure the
546 // DynamicTypeInfo is up to date. This assert should be re-enabled once
547 // this is fixed. <rdar://problem/12287087>
548 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
550 return RuntimeDefinition();
553 // Does the decl that we found have an implementation?
554 const FunctionDecl *Definition;
555 if (!Result->hasBody(Definition))
556 return RuntimeDefinition();
558 // We found a definition. If we're not sure that this devirtualization is
559 // actually what will happen at runtime, make sure to provide the region so
560 // that ExprEngine can decide what to do with it.
561 if (DynType.canBeASubClass())
562 return RuntimeDefinition(Definition, R->StripCasts());
563 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
566 void CXXInstanceCall::getInitialStackFrameContents(
567 const StackFrameContext *CalleeCtx,
568 BindingsTy &Bindings) const {
569 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
571 // Handle the binding of 'this' in the new stack frame.
572 SVal ThisVal = getCXXThisVal();
573 if (!ThisVal.isUnknown()) {
574 ProgramStateManager &StateMgr = getState()->getStateManager();
575 SValBuilder &SVB = StateMgr.getSValBuilder();
577 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
578 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
580 // If we devirtualized to a different member function, we need to make sure
581 // we have the proper layering of CXXBaseObjectRegions.
582 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
583 ASTContext &Ctx = SVB.getContext();
584 const CXXRecordDecl *Class = MD->getParent();
585 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
587 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
589 ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
590 assert(!Failed && "Calling an incorrectly devirtualized method");
593 if (!ThisVal.isUnknown())
594 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
600 const Expr *CXXMemberCall::getCXXThisExpr() const {
601 return getOriginExpr()->getImplicitObjectArgument();
604 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
605 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
606 // id-expression in the class member access expression is a qualified-id,
607 // that function is called. Otherwise, its final overrider in the dynamic type
608 // of the object expression is called.
609 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
610 if (ME->hasQualifier())
611 return AnyFunctionCall::getRuntimeDefinition();
613 return CXXInstanceCall::getRuntimeDefinition();
617 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
618 return getOriginExpr()->getArg(0);
622 const BlockDataRegion *BlockCall::getBlockRegion() const {
623 const Expr *Callee = getOriginExpr()->getCallee();
624 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
626 return dyn_cast_or_null<BlockDataRegion>(DataReg);
629 ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
630 const BlockDecl *D = getDecl();
633 return D->parameters();
636 void BlockCall::getExtraInvalidatedValues(ValueList &Values,
637 RegionAndSymbolInvalidationTraits *ETraits) const {
638 // FIXME: This also needs to invalidate captured globals.
639 if (const MemRegion *R = getBlockRegion())
640 Values.push_back(loc::MemRegionVal(R));
643 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
644 BindingsTy &Bindings) const {
645 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
646 ArrayRef<ParmVarDecl*> Params;
647 if (isConversionFromLambda()) {
648 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
649 Params = LambdaOperatorDecl->parameters();
651 // For blocks converted from a C++ lambda, the callee declaration is the
652 // operator() method on the lambda so we bind "this" to
653 // the lambda captured by the block.
654 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
655 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
656 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
657 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
659 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
662 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
667 SVal CXXConstructorCall::getCXXThisVal() const {
669 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
673 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
674 RegionAndSymbolInvalidationTraits *ETraits) const {
676 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
679 void CXXConstructorCall::getInitialStackFrameContents(
680 const StackFrameContext *CalleeCtx,
681 BindingsTy &Bindings) const {
682 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
684 SVal ThisVal = getCXXThisVal();
685 if (!ThisVal.isUnknown()) {
686 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
687 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
688 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
689 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
693 SVal CXXDestructorCall::getCXXThisVal() const {
695 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
699 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
700 // Base destructors are always called non-virtually.
701 // Skip CXXInstanceCall's devirtualization logic in this case.
702 if (isBaseDestructor())
703 return AnyFunctionCall::getRuntimeDefinition();
705 return CXXInstanceCall::getRuntimeDefinition();
708 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
709 const ObjCMethodDecl *D = getDecl();
712 return D->parameters();
715 void ObjCMethodCall::getExtraInvalidatedValues(
716 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
718 // If the method call is a setter for property known to be backed by
719 // an instance variable, don't invalidate the entire receiver, just
720 // the storage for that instance variable.
721 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
722 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
723 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
724 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
727 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
730 RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
731 Values.push_back(IvarLVal);
737 Values.push_back(getReceiverSVal());
740 SVal ObjCMethodCall::getSelfSVal() const {
741 const LocationContext *LCtx = getLocationContext();
742 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
745 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
748 SVal ObjCMethodCall::getReceiverSVal() const {
749 // FIXME: Is this the best way to handle class receivers?
750 if (!isInstanceMessage())
753 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
754 return getSVal(RecE);
756 // An instance message with no expression means we are sending to super.
757 // In this case the object reference is the same as 'self'.
758 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
759 SVal SelfVal = getSelfSVal();
760 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
764 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
765 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
766 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
769 if (!isInstanceMessage())
772 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
774 return (RecVal == getSelfSVal());
777 SourceRange ObjCMethodCall::getSourceRange() const {
778 switch (getMessageKind()) {
780 return getOriginExpr()->getSourceRange();
781 case OCM_PropertyAccess:
783 return getContainingPseudoObjectExpr()->getSourceRange();
785 llvm_unreachable("unknown message kind");
788 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
790 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
791 assert(Data && "Lazy lookup not yet performed.");
792 assert(getMessageKind() != OCM_Message && "Explicit message send.");
793 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
797 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
798 const Expr *Syntactic = POE->getSyntacticForm();
800 // This handles the funny case of assigning to the result of a getter.
801 // This can happen if the getter returns a non-const reference.
802 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
803 Syntactic = BO->getLHS();
808 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
811 // Find the parent, ignoring implicit casts.
812 ParentMap &PM = getLocationContext()->getParentMap();
813 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
815 // Check if parent is a PseudoObjectExpr.
816 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
817 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
820 switch (Syntactic->getStmtClass()) {
821 case Stmt::ObjCPropertyRefExprClass:
822 K = OCM_PropertyAccess;
824 case Stmt::ObjCSubscriptRefExprClass:
828 // FIXME: Can this ever happen?
833 if (K != OCM_Message) {
834 const_cast<ObjCMethodCall *>(this)->Data
835 = ObjCMessageDataTy(POE, K).getOpaqueValue();
836 assert(getMessageKind() == K);
841 const_cast<ObjCMethodCall *>(this)->Data
842 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
843 assert(getMessageKind() == OCM_Message);
847 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
848 if (!Info.getPointer())
850 return static_cast<ObjCMessageKind>(Info.getInt());
853 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
854 // Look for properties accessed with property syntax (foo.bar = ...)
855 if ( getMessageKind() == OCM_PropertyAccess) {
856 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
857 assert(POE && "Property access without PseudoObjectExpr?");
859 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
860 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
862 if (RefExpr->isExplicitProperty())
863 return RefExpr->getExplicitProperty();
866 // Look for properties accessed with method syntax ([foo setBar:...]).
867 const ObjCMethodDecl *MD = getDecl();
868 if (!MD || !MD->isPropertyAccessor())
871 // Note: This is potentially quite slow.
872 return MD->findPropertyDecl();
875 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
876 Selector Sel) const {
878 const SourceManager &SM =
879 getState()->getStateManager().getContext().getSourceManager();
881 // If the class interface is declared inside the main file, assume it is not
883 // TODO: It could actually be subclassed if the subclass is private as well.
884 // This is probably very rare.
885 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
886 if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
889 // Assume that property accessors are not overridden.
890 if (getMessageKind() == OCM_PropertyAccess)
893 // We assume that if the method is public (declared outside of main file) or
894 // has a parent which publicly declares the method, the method could be
895 // overridden in a subclass.
897 // Find the first declaration in the class hierarchy that declares
899 ObjCMethodDecl *D = nullptr;
901 D = IDecl->lookupMethod(Sel, true);
903 // Cannot find a public definition.
907 // If outside the main file,
908 if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
911 if (D->isOverriding()) {
912 // Search in the superclass on the next iteration.
913 IDecl = D->getClassInterface();
917 IDecl = IDecl->getSuperClass();
927 llvm_unreachable("The while loop should always terminate.");
930 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
934 // Find the redeclaration that defines the method.
935 if (!MD->hasBody()) {
936 for (auto I : MD->redecls())
938 MD = cast<ObjCMethodDecl>(I);
943 static bool isCallToSelfClass(const ObjCMessageExpr *ME) {
944 const Expr* InstRec = ME->getInstanceReceiver();
947 const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts());
949 // Check that receiver is called 'self'.
950 if (!InstRecIg || !InstRecIg->getFoundDecl() ||
951 !InstRecIg->getFoundDecl()->getName().equals("self"))
954 // Check that the method name is 'class'.
955 if (ME->getSelector().getNumArgs() != 0 ||
956 !ME->getSelector().getNameForSlot(0).equals("class"))
962 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
963 const ObjCMessageExpr *E = getOriginExpr();
965 Selector Sel = E->getSelector();
967 if (E->isInstanceMessage()) {
969 // Find the receiver type.
970 const ObjCObjectPointerType *ReceiverT = nullptr;
971 bool CanBeSubClassed = false;
972 QualType SupersType = E->getSuperType();
973 const MemRegion *Receiver = nullptr;
975 if (!SupersType.isNull()) {
976 // The receiver is guaranteed to be 'super' in this case.
977 // Super always means the type of immediate predecessor to the method
978 // where the call occurs.
979 ReceiverT = cast<ObjCObjectPointerType>(SupersType);
981 Receiver = getReceiverSVal().getAsRegion();
983 return RuntimeDefinition();
985 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
986 if (!DTI.isValid()) {
987 assert(isa<AllocaRegion>(Receiver) &&
988 "Unhandled untyped region class!");
989 return RuntimeDefinition();
992 QualType DynType = DTI.getType();
993 CanBeSubClassed = DTI.canBeASubClass();
994 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
996 if (ReceiverT && CanBeSubClassed)
997 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
998 if (!canBeOverridenInSubclass(IDecl, Sel))
999 CanBeSubClassed = false;
1002 // Handle special cases of '[self classMethod]' and
1003 // '[[self class] classMethod]', which are treated by the compiler as
1004 // instance (not class) messages. We will statically dispatch to those.
1005 if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) {
1006 // For [self classMethod], return the compiler visible declaration.
1007 if (PT->getObjectType()->isObjCClass() &&
1008 Receiver == getSelfSVal().getAsRegion())
1009 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1011 // Similarly, handle [[self class] classMethod].
1012 // TODO: We are currently doing a syntactic match for this pattern with is
1013 // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m
1014 // shows. A better way would be to associate the meta type with the symbol
1015 // using the dynamic type info tracking and use it here. We can add a new
1016 // SVal for ObjC 'Class' values that know what interface declaration they
1017 // come from. Then 'self' in a class method would be filled in with
1018 // something meaningful in ObjCMethodCall::getReceiverSVal() and we could
1019 // do proper dynamic dispatch for class methods just like we do for
1020 // instance methods now.
1021 if (E->getInstanceReceiver())
1022 if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver()))
1023 if (isCallToSelfClass(M))
1024 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1027 // Lookup the instance method implementation.
1029 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
1030 // Repeatedly calling lookupPrivateMethod() is expensive, especially
1031 // when in many cases it returns null. We cache the results so
1032 // that repeated queries on the same ObjCIntefaceDecl and Selector
1033 // don't incur the same cost. On some test cases, we can see the
1034 // same query being issued thousands of times.
1036 // NOTE: This cache is essentially a "global" variable, but it
1037 // only gets lazily created when we get here. The value of the
1038 // cache probably comes from it being global across ExprEngines,
1039 // where the same queries may get issued. If we are worried about
1040 // concurrency, or possibly loading/unloading ASTs, etc., we may
1041 // need to revisit this someday. In terms of memory, this table
1042 // stays around until clang quits, which also may be bad if we
1043 // need to release memory.
1044 typedef std::pair<const ObjCInterfaceDecl*, Selector>
1046 typedef llvm::DenseMap<PrivateMethodKey,
1047 Optional<const ObjCMethodDecl *> >
1050 static PrivateMethodCache PMC;
1051 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
1053 // Query lookupPrivateMethod() if the cache does not hit.
1054 if (!Val.hasValue()) {
1055 Val = IDecl->lookupPrivateMethod(Sel);
1057 // If the method is a property accessor, we should try to "inline" it
1058 // even if we don't actually have an implementation.
1060 if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
1061 if (CompileTimeMD->isPropertyAccessor()) {
1062 if (!CompileTimeMD->getSelfDecl() &&
1063 isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
1064 // If the method is an accessor in a category, and it doesn't
1065 // have a self declaration, first
1066 // try to find the method in a class extension. This
1067 // works around a bug in Sema where multiple accessors
1068 // are synthesized for properties in class
1069 // extensions that are redeclared in a category and the
1070 // the implicit parameters are not filled in for
1071 // the method on the category.
1072 // This ensures we find the accessor in the extension, which
1073 // has the implicit parameters filled in.
1074 auto *ID = CompileTimeMD->getClassInterface();
1075 for (auto *CatDecl : ID->visible_extensions()) {
1076 Val = CatDecl->getMethod(Sel,
1077 CompileTimeMD->isInstanceMethod());
1083 Val = IDecl->lookupInstanceMethod(Sel);
1087 const ObjCMethodDecl *MD = Val.getValue();
1088 if (CanBeSubClassed)
1089 return RuntimeDefinition(MD, Receiver);
1091 return RuntimeDefinition(MD, nullptr);
1095 // This is a class method.
1096 // If we have type info for the receiver class, we are calling via
1098 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1099 // Find/Return the method implementation.
1100 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1104 return RuntimeDefinition();
1107 bool ObjCMethodCall::argumentsMayEscape() const {
1108 if (isInSystemHeader() && !isInstanceMessage()) {
1109 Selector Sel = getSelector();
1110 if (Sel.getNumArgs() == 1 &&
1111 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1115 return CallEvent::argumentsMayEscape();
1118 void ObjCMethodCall::getInitialStackFrameContents(
1119 const StackFrameContext *CalleeCtx,
1120 BindingsTy &Bindings) const {
1121 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1122 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1123 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1126 SVal SelfVal = getReceiverSVal();
1127 if (!SelfVal.isUnknown()) {
1128 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1129 MemRegionManager &MRMgr = SVB.getRegionManager();
1130 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1131 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1136 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1137 const LocationContext *LCtx) {
1138 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1139 return create<CXXMemberCall>(MCE, State, LCtx);
1141 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1142 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1143 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1144 if (MD->isInstance())
1145 return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1147 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1148 return create<BlockCall>(CE, State, LCtx);
1151 // Otherwise, it's a normal function call, static member function call, or
1152 // something we can't reason about.
1153 return create<SimpleFunctionCall>(CE, State, LCtx);
1158 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1159 ProgramStateRef State) {
1160 const LocationContext *ParentCtx = CalleeCtx->getParent();
1161 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
1162 assert(CallerCtx && "This should not be used for top-level stack frames");
1164 const Stmt *CallSite = CalleeCtx->getCallSite();
1167 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
1168 return getSimpleCall(CE, State, CallerCtx);
1170 switch (CallSite->getStmtClass()) {
1171 case Stmt::CXXConstructExprClass:
1172 case Stmt::CXXTemporaryObjectExprClass: {
1173 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1174 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1175 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1176 SVal ThisVal = State->getSVal(ThisPtr);
1178 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
1179 ThisVal.getAsRegion(), State, CallerCtx);
1181 case Stmt::CXXNewExprClass:
1182 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
1183 case Stmt::ObjCMessageExprClass:
1184 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
1187 llvm_unreachable("This is not an inlineable statement.");
1191 // Fall back to the CFG. The only thing we haven't handled yet is
1192 // destructors, though this could change in the future.
1193 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1194 CFGElement E = (*B)[CalleeCtx->getIndex()];
1195 assert(E.getAs<CFGImplicitDtor>() &&
1196 "All other CFG elements should have exprs");
1197 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
1199 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1200 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1201 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1202 SVal ThisVal = State->getSVal(ThisPtr);
1204 const Stmt *Trigger;
1205 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1206 Trigger = AutoDtor->getTriggerStmt();
1207 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1208 Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
1210 Trigger = Dtor->getBody();
1212 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1213 E.getAs<CFGBaseDtor>().hasValue(), State,